1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
18 * Author: David Zeuthen <davidz@redhat.com>
24 * - would be nice to expose GDBusAuthMechanism and an extension point
26 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
27 * the mechanism VFuncs need to be able to set an error.
29 * - Need to document other mechanisms/sources for determining the D-Bus
30 * address of a well-known bus.
32 * - e.g. on Win32 we need code like from here
34 * http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
36 * that was never copied over here because it originally was copy-paste
37 * from the GPLv2 / AFL 2.1 libdbus sources.
39 * - on OS X we need to look in launchd for the address
41 * https://bugs.freedesktop.org/show_bug.cgi?id=14259
43 * - on X11 we need to look in a X11 property on the X server
44 * - (we can also just use dbus-launch(1) from the D-Bus
47 * - (ideally) this requires D-Bus spec work because none of
48 * this has never really been specced out properly (except
51 * - Related to the above, we also need to be able to launch a message bus
52 * instance.... Since we don't want to write our own bus daemon we should
53 * launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
55 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
56 * to specify where the nonce is stored. This will allow people to use
57 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
58 * to easily achieve secure RPC via nonce-tcp.
60 * - need to expose an extension point for resolving D-Bus address and
61 * turning them into GIOStream objects. This will allow us to implement
62 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
64 * - see g_dbus_address_connect() in gdbusaddress.c
66 * - would be cute to use kernel-specific APIs to resolve fds for
67 * debug output when using G_DBUS_DEBUG=message, e.g. in addition to
69 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
71 * maybe we can show more information about what fd 21 really is.
72 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
73 * Initial experiments on Linux 2.6 suggests that the symlink looks
78 * e.g. not of much use.
80 * - GDBus High-Level docs
81 * - Proxy: properties, signals...
82 * - Connection: IOStream based, ::close, connection setup steps
83 * mainloop integration, threading
84 * - Differences from libdbus (extend "Migrating from")
85 * - the message handling thread
86 * - Using GVariant instead of GValue
87 * - Explain why the high-level API is a good thing and what
88 * kind of pitfalls it avoids
89 * - Export objects before claiming names
90 * - Talk about auto-starting services (cf. GBusNameWatcherFlags)
92 * - use abstract sockets in test code
93 * - right now it doesn't work, dbus-daemon(1) fails with
95 * /gdbus/connection/filter: Failed to start message bus: Failed to bind
96 * socket "/tmp/g-dbus-tests-pid-28531": Address already in use
97 * ** WARNING **: Error reading address from dbus daemon, 0 bytes read
107 #include "gdbusauth.h"
108 #include "gdbusutils.h"
109 #include "gdbusaddress.h"
110 #include "gdbusmessage.h"
111 #include "gdbusconnection.h"
112 #include "gdbuserror.h"
113 #include "gioenumtypes.h"
114 #include "gdbusintrospection.h"
115 #include "gdbusmethodinvocation.h"
116 #include "gdbusprivate.h"
117 #include "gdbusauthobserver.h"
118 #include "ginitable.h"
119 #include "gasyncinitable.h"
120 #include "giostream.h"
121 #include "gasyncresult.h"
122 #include "gsimpleasyncresult.h"
125 #include "gunixconnection.h"
126 #include "gunixfdmessage.h"
129 #include "glibintl.h"
132 * SECTION:gdbusconnection
133 * @short_description: D-Bus Connections
134 * @include: gio/gio.h
136 * The #GDBusConnection type is used for D-Bus connections to remote
137 * peers such as a message buses. It is a low-level API that offers a
138 * lot of flexibility. For instance, it lets you establish a connection
139 * over any transport that can by represented as an #GIOStream.
141 * This class is rarely used directly in D-Bus clients. If you are writing
142 * an D-Bus client, it is often easier to use the g_bus_own_name(),
143 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
145 * As an exception to the usual GLib rule that a particular object must not
146 * be used by two threads at the same time, #GDBusConnection's methods may be
147 * called from any thread. This is so that g_bus_get() and g_bus_get_sync()
148 * can safely return the same #GDBusConnection when called from any thread.
150 * Most of the ways to obtain a #GDBusConnection automatically initialize it
151 * (i.e. connect to D-Bus): for instance, g_dbus_connection_new() and
152 * g_bus_get(), and the synchronous versions of those methods, give you an
153 * initialized connection. Language bindings for GIO should use
154 * g_initable_new() or g_async_initable_new_async(), which also initialize the
157 * If you construct an uninitialized #GDBusConnection, such as via
158 * g_object_new(), you must initialize it via g_initable_init() or
159 * g_async_initable_init_async() before using its methods or properties.
160 * Calling methods or accessing properties on a #GDBusConnection that has not
161 * completed initialization successfully is considered to be invalid, and leads
162 * to undefined behaviour. In particular, if initialization fails with a
163 * #GError, the only valid thing you can do with that #GDBusConnection is to
164 * free it with g_object_unref().
166 * <example id="gdbus-server"><title>D-Bus server example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-server.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
168 * <example id="gdbus-subtree-server"><title>D-Bus subtree example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-subtree.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
170 * <example id="gdbus-unix-fd-client"><title>D-Bus UNIX File Descriptor example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-unix-fd-client.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
172 * <example id="gdbus-export"><title>Exporting a GObject</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-export.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
175 /* ---------------------------------------------------------------------------------------------------- */
177 typedef struct _GDBusConnectionClass GDBusConnectionClass;
180 * GDBusConnectionClass:
181 * @closed: Signal class handler for the #GDBusConnection::closed signal.
183 * Class structure for #GDBusConnection.
187 struct _GDBusConnectionClass
190 GObjectClass parent_class;
194 void (*closed) (GDBusConnection *connection,
195 gboolean remote_peer_vanished,
199 G_LOCK_DEFINE_STATIC (message_bus_lock);
201 static GWeakRef the_session_bus;
202 static GWeakRef the_system_bus;
204 /* Extra pseudo-member of GDBusSendMessageFlags.
205 * Set by initable_init() to indicate that despite not being initialized yet,
206 * enough of the only-valid-after-init members are set that we can send a
207 * message, and we're being called from its thread, so no memory barrier is
208 * required before accessing them.
210 #define SEND_MESSAGE_FLAGS_INITIALIZING (1<<31)
212 /* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
213 #define CALL_FLAGS_INITIALIZING (1<<31)
215 /* ---------------------------------------------------------------------------------------------------- */
219 GDestroyNotify callback;
221 GMainContext *context;
222 } CallDestroyNotifyData;
225 call_destroy_notify_data_in_idle (gpointer user_data)
227 CallDestroyNotifyData *data = user_data;
228 data->callback (data->user_data);
233 call_destroy_notify_data_free (CallDestroyNotifyData *data)
235 if (data->context != NULL)
236 g_main_context_unref (data->context);
241 * call_destroy_notify: <internal>
242 * @context: (allow-none): A #GMainContext or %NULL.
243 * @callback: (allow-none): A #GDestroyNotify or %NULL.
244 * @user_data: Data to pass to @callback.
246 * Schedules @callback to run in @context.
249 call_destroy_notify (GMainContext *context,
250 GDestroyNotify callback,
253 GSource *idle_source;
254 CallDestroyNotifyData *data;
256 if (callback == NULL)
259 data = g_new0 (CallDestroyNotifyData, 1);
260 data->callback = callback;
261 data->user_data = user_data;
262 data->context = context;
263 if (data->context != NULL)
264 g_main_context_ref (data->context);
266 idle_source = g_idle_source_new ();
267 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
268 g_source_set_callback (idle_source,
269 call_destroy_notify_data_in_idle,
271 (GDestroyNotify) call_destroy_notify_data_free);
272 g_source_attach (idle_source, data->context);
273 g_source_unref (idle_source);
279 /* ---------------------------------------------------------------------------------------------------- */
282 _g_strv_has_string (const gchar* const *haystack,
287 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
289 if (g_strcmp0 (haystack[n], needle) == 0)
295 /* ---------------------------------------------------------------------------------------------------- */
298 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
300 // TODO: for some reason this doesn't work on Windows
301 #define CONNECTION_ENSURE_LOCK(obj) do { \
302 if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock))) \
304 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
305 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
310 #define CONNECTION_LOCK(obj) do { \
311 g_mutex_lock (&(obj)->lock); \
314 #define CONNECTION_UNLOCK(obj) do { \
315 g_mutex_unlock (&(obj)->lock); \
318 /* Flags in connection->atomic_flags */
320 FLAG_INITIALIZED = 1 << 0,
321 FLAG_EXIT_ON_CLOSE = 1 << 1,
328 * The #GDBusConnection structure contains only private data and
329 * should only be accessed using the provided API.
333 struct _GDBusConnection
336 GObject parent_instance;
338 /* ------------------------------------------------------------------------ */
339 /* -- General object state ------------------------------------------------ */
340 /* ------------------------------------------------------------------------ */
342 /* General-purpose lock for most fields */
345 /* A lock used in the init() method of the GInitable interface - see comments
346 * in initable_init() for why a separate lock is needed.
348 * If you need both @lock and @init_lock, you must take @init_lock first.
352 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
353 * someone calls org.freedesktop.DBus.Peer.GetMachineId(). Protected by @lock.
357 /* The underlying stream used for communication
358 * Read-only after initable_init(), so it may be read if you either
359 * hold @init_lock or check for initialization first.
363 /* The object used for authentication (if any).
364 * Read-only after initable_init(), so it may be read if you either
365 * hold @init_lock or check for initialization first.
369 /* Last serial used. Protected by @lock. */
372 /* The object used to send/receive messages.
373 * Read-only after initable_init(), so it may be read if you either
374 * hold @init_lock or check for initialization first.
378 /* If connected to a message bus, this contains the unique name assigned to
379 * us by the bus (e.g. ":1.42").
380 * Read-only after initable_init(), so it may be read if you either
381 * hold @init_lock or check for initialization first.
383 gchar *bus_unique_name;
385 /* The GUID returned by the other side if we authenticed as a client or
386 * the GUID to use if authenticating as a server.
387 * Read-only after initable_init(), so it may be read if you either
388 * hold @init_lock or check for initialization first.
392 /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
393 * Inspect @initialization_error to see whether it succeeded or failed.
395 * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
397 * FLAG_CLOSED is the closed property. It may be read at any time, but
398 * may only be written while holding @lock.
400 volatile gint atomic_flags;
402 /* If the connection could not be established during initable_init(),
403 * this GError will be set.
404 * Read-only after initable_init(), so it may be read if you either
405 * hold @init_lock or check for initialization first.
407 GError *initialization_error;
409 /* The result of g_main_context_ref_thread_default() when the object
410 * was created (the GObject _init() function) - this is used for delivery
411 * of the :closed GObject signal.
413 * Only set in the GObject init function, so no locks are needed.
415 GMainContext *main_context_at_construction;
417 /* Read-only construct properties, no locks needed */
419 GDBusConnectionFlags flags;
421 /* Map used for managing method replies, protected by @lock */
422 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
424 /* Maps used for managing signal subscription, protected by @lock */
425 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
426 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
427 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
429 /* Maps used for managing exported objects and subtrees,
432 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
433 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
434 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
435 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
437 /* Map used for storing last used serials for each thread, protected by @lock */
438 GHashTable *map_thread_to_last_serial;
440 /* Structure used for message filters, protected by @lock */
443 /* Capabilities negotiated during authentication
444 * Read-only after initable_init(), so it may be read without holding a
445 * lock, if you check for initialization first.
447 GDBusCapabilityFlags capabilities;
449 /* Protected by @init_lock */
450 GDBusAuthObserver *authentication_observer;
452 /* Read-only after initable_init(), so it may be read if you either
453 * hold @init_lock or check for initialization first.
455 GCredentials *credentials;
457 /* set to TRUE when finalizing */
461 typedef struct ExportedObject ExportedObject;
462 static void exported_object_free (ExportedObject *eo);
464 typedef struct ExportedSubtree ExportedSubtree;
465 static void exported_subtree_free (ExportedSubtree *es);
483 PROP_CAPABILITY_FLAGS,
484 PROP_AUTHENTICATION_OBSERVER,
487 static void distribute_signals (GDBusConnection *connection,
488 GDBusMessage *message);
490 static void distribute_method_call (GDBusConnection *connection,
491 GDBusMessage *message);
493 static gboolean handle_generic_unlocked (GDBusConnection *connection,
494 GDBusMessage *message);
497 static void purge_all_signal_subscriptions (GDBusConnection *connection);
498 static void purge_all_filters (GDBusConnection *connection);
500 static void schedule_method_call (GDBusConnection *connection,
501 GDBusMessage *message,
502 guint registration_id,
503 guint subtree_registration_id,
504 const GDBusInterfaceInfo *interface_info,
505 const GDBusMethodInfo *method_info,
506 const GDBusPropertyInfo *property_info,
507 GVariant *parameters,
508 const GDBusInterfaceVTable *vtable,
509 GMainContext *main_context,
512 #define _G_ENSURE_LOCK(name) do { \
513 if (G_UNLIKELY (G_TRYLOCK(name))) \
515 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
516 "_G_ENSURE_LOCK: Lock '" #name "' is not locked"); \
520 static guint signals[LAST_SIGNAL] = { 0 };
522 static void initable_iface_init (GInitableIface *initable_iface);
523 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
525 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
526 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
527 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
531 * Check that all members of @connection that can only be accessed after
532 * the connection is initialized can safely be accessed. If not,
533 * log a critical warning. This function is a memory barrier.
535 * Returns: %TRUE if initialized
538 check_initialized (GDBusConnection *connection)
540 /* The access to @atomic_flags isn't conditional, so that this function
541 * provides a memory barrier for thread-safety even if checks are disabled.
542 * (If you don't want this stricter guarantee, you can call
543 * g_return_if_fail (check_initialized (c)).)
545 * This isn't strictly necessary now that we've decided use of an
546 * uninitialized GDBusConnection is undefined behaviour, but it seems
547 * better to be as deterministic as is feasible.
549 * (Anything that could suffer a crash from seeing undefined values
550 * must have a race condition - thread A initializes the connection while
551 * thread B calls a method without initialization, hoping that thread A will
552 * win the race - so its behaviour is undefined anyway.)
554 gint flags = g_atomic_int_get (&connection->atomic_flags);
556 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
558 /* We can safely access this, due to the memory barrier above */
559 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
565 MAY_BE_UNINITIALIZED = (1<<1)
566 } CheckUnclosedFlags;
569 * Check the same thing as check_initialized(), and also that the
570 * connection is not closed. If the connection is uninitialized,
571 * raise a critical warning (it's programmer error); if it's closed,
572 * raise a recoverable GError (it's a runtime error).
574 * This function is a memory barrier.
576 * Returns: %TRUE if initialized and not closed
579 check_unclosed (GDBusConnection *connection,
580 CheckUnclosedFlags check,
583 /* check_initialized() is effectively inlined, so we don't waste time
584 * doing two memory barriers
586 gint flags = g_atomic_int_get (&connection->atomic_flags);
588 if (!(check & MAY_BE_UNINITIALIZED))
590 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
591 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
594 if (flags & FLAG_CLOSED)
596 g_set_error_literal (error,
599 _("The connection is closed"));
606 static GHashTable *alive_connections = NULL;
609 g_dbus_connection_dispose (GObject *object)
611 GDBusConnection *connection = G_DBUS_CONNECTION (object);
613 G_LOCK (message_bus_lock);
614 CONNECTION_LOCK (connection);
615 if (connection->worker != NULL)
617 _g_dbus_worker_stop (connection->worker);
618 connection->worker = NULL;
619 if (alive_connections != NULL)
620 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
624 if (alive_connections != NULL)
625 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
627 CONNECTION_UNLOCK (connection);
628 G_UNLOCK (message_bus_lock);
630 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
631 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
635 g_dbus_connection_finalize (GObject *object)
637 GDBusConnection *connection = G_DBUS_CONNECTION (object);
639 connection->finalizing = TRUE;
641 purge_all_signal_subscriptions (connection);
643 purge_all_filters (connection);
644 g_ptr_array_unref (connection->filters);
646 if (connection->authentication_observer != NULL)
647 g_object_unref (connection->authentication_observer);
649 if (connection->auth != NULL)
650 g_object_unref (connection->auth);
652 if (connection->credentials)
653 g_object_unref (connection->credentials);
655 if (connection->stream != NULL)
657 g_object_unref (connection->stream);
658 connection->stream = NULL;
661 g_free (connection->address);
663 g_free (connection->guid);
664 g_free (connection->bus_unique_name);
666 if (connection->initialization_error != NULL)
667 g_error_free (connection->initialization_error);
669 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
671 g_hash_table_unref (connection->map_rule_to_signal_data);
672 g_hash_table_unref (connection->map_id_to_signal_data);
673 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
675 g_hash_table_unref (connection->map_id_to_ei);
676 g_hash_table_unref (connection->map_object_path_to_eo);
677 g_hash_table_unref (connection->map_id_to_es);
678 g_hash_table_unref (connection->map_object_path_to_es);
680 g_hash_table_unref (connection->map_thread_to_last_serial);
682 g_main_context_unref (connection->main_context_at_construction);
684 g_free (connection->machine_id);
686 g_mutex_clear (&connection->init_lock);
687 g_mutex_clear (&connection->lock);
689 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
692 /* called in any user thread, with the connection's lock not held */
694 g_dbus_connection_get_property (GObject *object,
699 GDBusConnection *connection = G_DBUS_CONNECTION (object);
704 g_value_set_object (value, g_dbus_connection_get_stream (connection));
708 g_value_set_string (value, g_dbus_connection_get_guid (connection));
711 case PROP_UNIQUE_NAME:
712 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
716 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
719 case PROP_EXIT_ON_CLOSE:
720 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
723 case PROP_CAPABILITY_FLAGS:
724 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
728 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
733 /* called in any user thread, with the connection's lock not held */
735 g_dbus_connection_set_property (GObject *object,
740 GDBusConnection *connection = G_DBUS_CONNECTION (object);
745 connection->stream = g_value_dup_object (value);
749 connection->guid = g_value_dup_string (value);
753 connection->address = g_value_dup_string (value);
757 connection->flags = g_value_get_flags (value);
760 case PROP_EXIT_ON_CLOSE:
761 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
764 case PROP_AUTHENTICATION_OBSERVER:
765 connection->authentication_observer = g_value_dup_object (value);
769 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
774 /* Base-class implementation of GDBusConnection::closed.
776 * Called in a user thread, by the main context that was thread-default when
777 * the object was constructed.
780 g_dbus_connection_real_closed (GDBusConnection *connection,
781 gboolean remote_peer_vanished,
784 gint flags = g_atomic_int_get (&connection->atomic_flags);
786 /* Because atomic int access is a memory barrier, we can safely read
787 * initialization_error without a lock, as long as we do it afterwards.
789 if (remote_peer_vanished &&
790 (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
791 (flags & FLAG_INITIALIZED) != 0 &&
792 connection->initialization_error == NULL)
796 g_printerr ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
799 g_quark_to_string (error->domain), error->code);
803 g_printerr ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
810 g_dbus_connection_class_init (GDBusConnectionClass *klass)
812 GObjectClass *gobject_class;
814 gobject_class = G_OBJECT_CLASS (klass);
816 gobject_class->finalize = g_dbus_connection_finalize;
817 gobject_class->dispose = g_dbus_connection_dispose;
818 gobject_class->set_property = g_dbus_connection_set_property;
819 gobject_class->get_property = g_dbus_connection_get_property;
821 klass->closed = g_dbus_connection_real_closed;
824 * GDBusConnection:stream:
826 * The underlying #GIOStream used for I/O.
828 * If this is passed on construction and is a #GSocketConnection,
829 * then the corresponding #GSocket will be put into non-blocking mode.
831 * While the #GDBusConnection is active, it will interact with this
832 * stream from a worker thread, so it is not safe to interact with
833 * the stream directly.
837 g_object_class_install_property (gobject_class,
839 g_param_spec_object ("stream",
841 P_("The underlying streams used for I/O"),
845 G_PARAM_CONSTRUCT_ONLY |
846 G_PARAM_STATIC_NAME |
847 G_PARAM_STATIC_BLURB |
848 G_PARAM_STATIC_NICK));
851 * GDBusConnection:address:
853 * A D-Bus address specifying potential endpoints that can be used
854 * when establishing the connection.
858 g_object_class_install_property (gobject_class,
860 g_param_spec_string ("address",
862 P_("D-Bus address specifying potential socket endpoints"),
865 G_PARAM_CONSTRUCT_ONLY |
866 G_PARAM_STATIC_NAME |
867 G_PARAM_STATIC_BLURB |
868 G_PARAM_STATIC_NICK));
871 * GDBusConnection:flags:
873 * Flags from the #GDBusConnectionFlags enumeration.
877 g_object_class_install_property (gobject_class,
879 g_param_spec_flags ("flags",
882 G_TYPE_DBUS_CONNECTION_FLAGS,
883 G_DBUS_CONNECTION_FLAGS_NONE,
885 G_PARAM_CONSTRUCT_ONLY |
886 G_PARAM_STATIC_NAME |
887 G_PARAM_STATIC_BLURB |
888 G_PARAM_STATIC_NICK));
891 * GDBusConnection:guid:
893 * The GUID of the peer performing the role of server when
896 * If you are constructing a #GDBusConnection and pass
897 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
898 * #GDBusConnection:flags property then you MUST also set this
899 * property to a valid guid.
901 * If you are constructing a #GDBusConnection and pass
902 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
903 * #GDBusConnection:flags property you will be able to read the GUID
904 * of the other peer here after the connection has been successfully
909 g_object_class_install_property (gobject_class,
911 g_param_spec_string ("guid",
913 P_("GUID of the server peer"),
917 G_PARAM_CONSTRUCT_ONLY |
918 G_PARAM_STATIC_NAME |
919 G_PARAM_STATIC_BLURB |
920 G_PARAM_STATIC_NICK));
923 * GDBusConnection:unique-name:
925 * The unique name as assigned by the message bus or %NULL if the
926 * connection is not open or not a message bus connection.
930 g_object_class_install_property (gobject_class,
932 g_param_spec_string ("unique-name",
934 P_("Unique name of bus connection"),
937 G_PARAM_STATIC_NAME |
938 G_PARAM_STATIC_BLURB |
939 G_PARAM_STATIC_NICK));
942 * GDBusConnection:closed:
944 * A boolean specifying whether the connection has been closed.
948 g_object_class_install_property (gobject_class,
950 g_param_spec_boolean ("closed",
952 P_("Whether the connection is closed"),
955 G_PARAM_STATIC_NAME |
956 G_PARAM_STATIC_BLURB |
957 G_PARAM_STATIC_NICK));
960 * GDBusConnection:exit-on-close:
962 * A boolean specifying whether the process will be terminated (by
963 * calling <literal>raise(SIGTERM)</literal>) if the connection
964 * is closed by the remote peer.
966 * Note that #GDBusConnection objects returned by g_bus_get_finish() and
967 * g_bus_get_sync() will (usually) have this property set to %TRUE.
971 g_object_class_install_property (gobject_class,
973 g_param_spec_boolean ("exit-on-close",
975 P_("Whether the process is terminated when the connection is closed"),
979 G_PARAM_STATIC_NAME |
980 G_PARAM_STATIC_BLURB |
981 G_PARAM_STATIC_NICK));
984 * GDBusConnection:capabilities:
986 * Flags from the #GDBusCapabilityFlags enumeration
987 * representing connection features negotiated with the other peer.
991 g_object_class_install_property (gobject_class,
992 PROP_CAPABILITY_FLAGS,
993 g_param_spec_flags ("capabilities",
996 G_TYPE_DBUS_CAPABILITY_FLAGS,
997 G_DBUS_CAPABILITY_FLAGS_NONE,
999 G_PARAM_STATIC_NAME |
1000 G_PARAM_STATIC_BLURB |
1001 G_PARAM_STATIC_NICK));
1004 * GDBusConnection:authentication-observer:
1006 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
1010 g_object_class_install_property (gobject_class,
1011 PROP_AUTHENTICATION_OBSERVER,
1012 g_param_spec_object ("authentication-observer",
1013 P_("Authentication Observer"),
1014 P_("Object used to assist in the authentication process"),
1015 G_TYPE_DBUS_AUTH_OBSERVER,
1017 G_PARAM_CONSTRUCT_ONLY |
1018 G_PARAM_STATIC_NAME |
1019 G_PARAM_STATIC_BLURB |
1020 G_PARAM_STATIC_NICK));
1023 * GDBusConnection::closed:
1024 * @connection: the #GDBusConnection emitting the signal
1025 * @remote_peer_vanished: %TRUE if @connection is closed because the
1026 * remote peer closed its end of the connection
1027 * @error: (allow-none): a #GError with more details about the event or %NULL
1029 * Emitted when the connection is closed.
1031 * The cause of this event can be
1033 * - If g_dbus_connection_close() is called. In this case
1034 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
1036 * - If the remote peer closes the connection. In this case
1037 * @remote_peer_vanished is set to %TRUE and @error is set.
1039 * - If the remote peer sends invalid or malformed data. In this
1040 * case @remote_peer_vanished is set to %FALSE and @error is set.
1042 * Upon receiving this signal, you should give up your reference to
1043 * @connection. You are guaranteed that this signal is emitted only
1048 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
1049 G_TYPE_DBUS_CONNECTION,
1051 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1062 g_dbus_connection_init (GDBusConnection *connection)
1064 g_mutex_init (&connection->lock);
1065 g_mutex_init (&connection->init_lock);
1067 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
1069 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1071 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1073 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1076 (GDestroyNotify) g_ptr_array_unref);
1078 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1081 (GDestroyNotify) exported_object_free);
1083 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1086 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1089 (GDestroyNotify) exported_subtree_free);
1091 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1094 connection->map_thread_to_last_serial = g_hash_table_new (g_direct_hash,
1097 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1099 connection->filters = g_ptr_array_new ();
1103 * g_dbus_connection_get_stream:
1104 * @connection: a #GDBusConnection
1106 * Gets the underlying stream used for IO.
1108 * While the #GDBusConnection is active, it will interact with this
1109 * stream from a worker thread, so it is not safe to interact with
1110 * the stream directly.
1112 * Returns: (transfer none): the stream used for IO
1117 g_dbus_connection_get_stream (GDBusConnection *connection)
1119 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1121 /* do not use g_return_val_if_fail(), we want the memory barrier */
1122 if (!check_initialized (connection))
1125 return connection->stream;
1129 * g_dbus_connection_start_message_processing:
1130 * @connection: a #GDBusConnection
1132 * If @connection was created with
1133 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1134 * starts processing messages. Does nothing on if @connection wasn't
1135 * created with this flag or if the method has already been called.
1140 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1142 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1144 /* do not use g_return_val_if_fail(), we want the memory barrier */
1145 if (!check_initialized (connection))
1148 g_assert (connection->worker != NULL);
1149 _g_dbus_worker_unfreeze (connection->worker);
1153 * g_dbus_connection_is_closed:
1154 * @connection: a #GDBusConnection
1156 * Gets whether @connection is closed.
1158 * Returns: %TRUE if the connection is closed, %FALSE otherwise
1163 g_dbus_connection_is_closed (GDBusConnection *connection)
1167 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1169 flags = g_atomic_int_get (&connection->atomic_flags);
1171 return (flags & FLAG_CLOSED) ? TRUE : FALSE;
1175 * g_dbus_connection_get_capabilities:
1176 * @connection: a #GDBusConnection
1178 * Gets the capabilities negotiated with the remote peer
1180 * Returns: zero or more flags from the #GDBusCapabilityFlags enumeration
1184 GDBusCapabilityFlags
1185 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1187 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1189 /* do not use g_return_val_if_fail(), we want the memory barrier */
1190 if (!check_initialized (connection))
1191 return G_DBUS_CAPABILITY_FLAGS_NONE;
1193 return connection->capabilities;
1196 /* ---------------------------------------------------------------------------------------------------- */
1198 /* Called in a temporary thread without holding locks. */
1200 flush_in_thread_func (GSimpleAsyncResult *res,
1202 GCancellable *cancellable)
1207 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1210 g_simple_async_result_take_error (res, error);
1214 * g_dbus_connection_flush:
1215 * @connection: a #GDBusConnection
1216 * @cancellable: (allow-none): a #GCancellable or %NULL
1217 * @callback: (allow-none): a #GAsyncReadyCallback to call when the
1218 * request is satisfied or %NULL if you don't care about the result
1219 * @user_data: The data to pass to @callback
1221 * Asynchronously flushes @connection, that is, writes all queued
1222 * outgoing message to the transport and then flushes the transport
1223 * (using g_output_stream_flush_async()). This is useful in programs
1224 * that wants to emit a D-Bus signal and then exit immediately. Without
1225 * flushing the connection, there is no guaranteed that the message has
1226 * been sent to the networking buffers in the OS kernel.
1228 * This is an asynchronous method. When the operation is finished,
1229 * @callback will be invoked in the <link
1230 * linkend="g-main-context-push-thread-default">thread-default main
1231 * loop</link> of the thread you are calling this method from. You can
1232 * then call g_dbus_connection_flush_finish() to get the result of the
1233 * operation. See g_dbus_connection_flush_sync() for the synchronous
1239 g_dbus_connection_flush (GDBusConnection *connection,
1240 GCancellable *cancellable,
1241 GAsyncReadyCallback callback,
1244 GSimpleAsyncResult *simple;
1246 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1248 simple = g_simple_async_result_new (G_OBJECT (connection),
1251 g_dbus_connection_flush);
1252 g_simple_async_result_set_check_cancellable (simple, cancellable);
1253 g_simple_async_result_run_in_thread (simple,
1254 flush_in_thread_func,
1257 g_object_unref (simple);
1261 * g_dbus_connection_flush_finish:
1262 * @connection: a #GDBusConnection
1263 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1264 * to g_dbus_connection_flush()
1265 * @error: return location for error or %NULL
1267 * Finishes an operation started with g_dbus_connection_flush().
1269 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1274 g_dbus_connection_flush_finish (GDBusConnection *connection,
1278 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1283 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1284 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1285 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1287 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1289 if (g_simple_async_result_propagate_error (simple, error))
1299 * g_dbus_connection_flush_sync:
1300 * @connection: a #GDBusConnection
1301 * @cancellable: (allow-none): a #GCancellable or %NULL
1302 * @error: return location for error or %NULL
1304 * Synchronously flushes @connection. The calling thread is blocked
1305 * until this is done. See g_dbus_connection_flush() for the
1306 * asynchronous version of this method and more details about what it
1309 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1314 g_dbus_connection_flush_sync (GDBusConnection *connection,
1315 GCancellable *cancellable,
1320 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1321 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1325 /* This is only a best-effort attempt to see whether the connection is
1326 * closed, so it doesn't need the lock. If the connection closes just
1327 * after this check, but before scheduling the flush operation, the
1328 * result will be more or less the same as if the connection closed while
1329 * the flush operation was pending - it'll fail with either CLOSED or
1332 if (!check_unclosed (connection, 0, error))
1335 g_assert (connection->worker != NULL);
1337 ret = _g_dbus_worker_flush_sync (connection->worker,
1345 /* ---------------------------------------------------------------------------------------------------- */
1349 GDBusConnection *connection;
1351 gboolean remote_peer_vanished;
1355 emit_closed_data_free (EmitClosedData *data)
1357 g_object_unref (data->connection);
1358 if (data->error != NULL)
1359 g_error_free (data->error);
1363 /* Called in a user thread that has acquired the main context that was
1364 * thread-default when the object was constructed
1367 emit_closed_in_idle (gpointer user_data)
1369 EmitClosedData *data = user_data;
1372 g_object_notify (G_OBJECT (data->connection), "closed");
1373 g_signal_emit (data->connection,
1374 signals[CLOSED_SIGNAL],
1376 data->remote_peer_vanished,
1382 /* Can be called from any thread, must hold lock.
1383 * FLAG_CLOSED must already have been set.
1386 schedule_closed_unlocked (GDBusConnection *connection,
1387 gboolean remote_peer_vanished,
1390 GSource *idle_source;
1391 EmitClosedData *data;
1393 CONNECTION_ENSURE_LOCK (connection);
1395 data = g_new0 (EmitClosedData, 1);
1396 data->connection = g_object_ref (connection);
1397 data->remote_peer_vanished = remote_peer_vanished;
1398 data->error = error != NULL ? g_error_copy (error) : NULL;
1400 idle_source = g_idle_source_new ();
1401 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1402 g_source_set_callback (idle_source,
1403 emit_closed_in_idle,
1405 (GDestroyNotify) emit_closed_data_free);
1406 g_source_attach (idle_source, connection->main_context_at_construction);
1407 g_source_unref (idle_source);
1410 /* ---------------------------------------------------------------------------------------------------- */
1413 * g_dbus_connection_close:
1414 * @connection: a #GDBusConnection
1415 * @cancellable: (allow-none): a #GCancellable or %NULL
1416 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request is
1417 * satisfied or %NULL if you don't care about the result
1418 * @user_data: The data to pass to @callback
1420 * Closes @connection. Note that this never causes the process to
1421 * exit (this might only happen if the other end of a shared message
1422 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1424 * Once the connection is closed, operations such as sending a message
1425 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1426 * will not automatically flush the connection so queued messages may
1427 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1429 * If @connection is already closed, this method fails with
1430 * %G_IO_ERROR_CLOSED.
1432 * When @connection has been closed, the #GDBusConnection::closed
1433 * signal is emitted in the <link
1434 * linkend="g-main-context-push-thread-default">thread-default main
1435 * loop</link> of the thread that @connection was constructed in.
1437 * This is an asynchronous method. When the operation is finished,
1438 * @callback will be invoked in the <link
1439 * linkend="g-main-context-push-thread-default">thread-default main
1440 * loop</link> of the thread you are calling this method from. You can
1441 * then call g_dbus_connection_close_finish() to get the result of the
1442 * operation. See g_dbus_connection_close_sync() for the synchronous
1448 g_dbus_connection_close (GDBusConnection *connection,
1449 GCancellable *cancellable,
1450 GAsyncReadyCallback callback,
1453 GSimpleAsyncResult *simple;
1455 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1457 /* do not use g_return_val_if_fail(), we want the memory barrier */
1458 if (!check_initialized (connection))
1461 g_assert (connection->worker != NULL);
1463 simple = g_simple_async_result_new (G_OBJECT (connection),
1466 g_dbus_connection_close);
1467 g_simple_async_result_set_check_cancellable (simple, cancellable);
1468 _g_dbus_worker_close (connection->worker, cancellable, simple);
1469 g_object_unref (simple);
1473 * g_dbus_connection_close_finish:
1474 * @connection: a #GDBusConnection
1475 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1476 * to g_dbus_connection_close()
1477 * @error: return location for error or %NULL
1479 * Finishes an operation started with g_dbus_connection_close().
1481 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1486 g_dbus_connection_close_finish (GDBusConnection *connection,
1490 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1495 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1496 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1497 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1499 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1501 if (g_simple_async_result_propagate_error (simple, error))
1512 GAsyncResult *result;
1515 /* Can be called by any thread, without the connection lock */
1517 sync_close_cb (GObject *source_object,
1521 SyncCloseData *data = user_data;
1523 data->result = g_object_ref (res);
1524 g_main_loop_quit (data->loop);
1528 * g_dbus_connection_close_sync:
1529 * @connection: a #GDBusConnection
1530 * @cancellable: (allow-none): a #GCancellable or %NULL
1531 * @error: return location for error or %NULL
1533 * Synchronously closees @connection. The calling thread is blocked
1534 * until this is done. See g_dbus_connection_close() for the
1535 * asynchronous version of this method and more details about what it
1538 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1543 g_dbus_connection_close_sync (GDBusConnection *connection,
1544 GCancellable *cancellable,
1549 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1550 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1554 if (check_unclosed (connection, 0, error))
1556 GMainContext *context;
1559 context = g_main_context_new ();
1560 g_main_context_push_thread_default (context);
1561 data.loop = g_main_loop_new (context, TRUE);
1564 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1565 g_main_loop_run (data.loop);
1566 ret = g_dbus_connection_close_finish (connection, data.result, error);
1568 g_object_unref (data.result);
1569 g_main_loop_unref (data.loop);
1570 g_main_context_pop_thread_default (context);
1571 g_main_context_unref (context);
1577 /* ---------------------------------------------------------------------------------------------------- */
1580 * g_dbus_connection_get_last_serial:
1581 * @connection: a #GDBusConnection
1583 * Retrieves the last serial number assigned to a #GDBusMessage on
1584 * the current thread. This includes messages sent via both low-level
1585 * API such as g_dbus_connection_send_message() as well as
1586 * high-level API such as g_dbus_connection_emit_signal(),
1587 * g_dbus_connection_call() or g_dbus_proxy_call().
1589 * Returns: the last used serial or zero when no message has been sent
1590 * within the current thread
1595 g_dbus_connection_get_last_serial (GDBusConnection *connection)
1599 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
1601 CONNECTION_LOCK (connection);
1602 ret = GPOINTER_TO_UINT (g_hash_table_lookup (connection->map_thread_to_last_serial,
1604 CONNECTION_UNLOCK (connection);
1609 /* ---------------------------------------------------------------------------------------------------- */
1611 /* Can be called by any thread, with the connection lock held */
1613 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1614 GDBusMessage *message,
1615 GDBusSendMessageFlags flags,
1616 volatile guint32 *out_serial,
1621 guint32 serial_to_use;
1624 CONNECTION_ENSURE_LOCK (connection);
1626 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1627 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1629 /* TODO: check all necessary headers are present */
1634 if (out_serial != NULL)
1637 /* If we're in initable_init(), don't check for being initialized, to avoid
1638 * chicken-and-egg problems. initable_init() is responsible for setting up
1639 * our prerequisites (mainly connection->worker), and only calling us
1640 * from its own thread (so no memory barrier is needed).
1642 if (!check_unclosed (connection,
1643 (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
1647 blob = g_dbus_message_to_blob (message,
1649 connection->capabilities,
1654 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1655 serial_to_use = g_dbus_message_get_serial (message);
1657 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1662 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1665 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1668 g_assert_not_reached ();
1673 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1674 blob_size, serial_to_use, connection);
1675 g_printerr ("----\n");
1676 hexdump (blob, blob_size);
1677 g_printerr ("----\n");
1680 /* TODO: use connection->auth to encode the blob */
1682 if (out_serial != NULL)
1683 *out_serial = serial_to_use;
1685 /* store used serial for the current thread */
1686 /* TODO: watch the thread disposal and remove associated record
1688 * - see https://bugzilla.gnome.org/show_bug.cgi?id=676825#c7
1690 g_hash_table_replace (connection->map_thread_to_last_serial,
1692 GUINT_TO_POINTER (serial_to_use));
1694 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
1695 g_dbus_message_set_serial (message, serial_to_use);
1697 g_dbus_message_lock (message);
1698 _g_dbus_worker_send_message (connection->worker,
1702 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1713 * g_dbus_connection_send_message:
1714 * @connection: a #GDBusConnection
1715 * @message: a #GDBusMessage
1716 * @flags: flags affecting how the message is sent
1717 * @out_serial: (out) (allow-none): return location for serial number assigned
1718 * to @message when sending it or %NULL
1719 * @error: Return location for error or %NULL
1721 * Asynchronously sends @message to the peer represented by @connection.
1723 * Unless @flags contain the
1724 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1725 * will be assigned by @connection and set on @message via
1726 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1727 * serial number used will be written to this location prior to
1728 * submitting the message to the underlying transport.
1730 * If @connection is closed then the operation will fail with
1731 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1732 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1734 * See <xref linkend="gdbus-server"/> and <xref
1735 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1736 * low-level API to send and receive UNIX file descriptors.
1738 * Note that @message must be unlocked, unless @flags contain the
1739 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1741 * Returns: %TRUE if the message was well-formed and queued for
1742 * transmission, %FALSE if @error is set
1747 g_dbus_connection_send_message (GDBusConnection *connection,
1748 GDBusMessage *message,
1749 GDBusSendMessageFlags flags,
1750 volatile guint32 *out_serial,
1755 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1756 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1757 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1758 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1760 CONNECTION_LOCK (connection);
1761 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1762 CONNECTION_UNLOCK (connection);
1766 /* ---------------------------------------------------------------------------------------------------- */
1770 volatile gint ref_count;
1771 GDBusConnection *connection;
1773 GSimpleAsyncResult *simple;
1775 GMainContext *main_context;
1777 GCancellable *cancellable;
1779 gulong cancellable_handler_id;
1781 GSource *timeout_source;
1786 /* Can be called from any thread with or without lock held */
1787 static SendMessageData *
1788 send_message_data_ref (SendMessageData *data)
1790 g_atomic_int_inc (&data->ref_count);
1794 /* Can be called from any thread with or without lock held */
1796 send_message_data_unref (SendMessageData *data)
1798 if (g_atomic_int_dec_and_test (&data->ref_count))
1800 g_assert (data->timeout_source == NULL);
1801 g_assert (data->simple == NULL);
1802 g_assert (data->cancellable_handler_id == 0);
1803 g_object_unref (data->connection);
1804 if (data->cancellable != NULL)
1805 g_object_unref (data->cancellable);
1806 g_main_context_unref (data->main_context);
1811 /* ---------------------------------------------------------------------------------------------------- */
1813 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1815 send_message_with_reply_deliver (SendMessageData *data, gboolean remove)
1817 CONNECTION_ENSURE_LOCK (data->connection);
1819 g_assert (!data->delivered);
1821 data->delivered = TRUE;
1823 g_simple_async_result_complete_in_idle (data->simple);
1824 g_object_unref (data->simple);
1825 data->simple = NULL;
1827 if (data->timeout_source != NULL)
1829 g_source_destroy (data->timeout_source);
1830 data->timeout_source = NULL;
1832 if (data->cancellable_handler_id > 0)
1834 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1835 data->cancellable_handler_id = 0;
1840 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
1841 GUINT_TO_POINTER (data->serial)));
1844 send_message_data_unref (data);
1847 /* ---------------------------------------------------------------------------------------------------- */
1849 /* Can be called from any thread with lock held */
1851 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1852 GDBusMessage *reply)
1854 if (data->delivered)
1857 g_simple_async_result_set_op_res_gpointer (data->simple,
1858 g_object_ref (reply),
1861 send_message_with_reply_deliver (data, TRUE);
1867 /* ---------------------------------------------------------------------------------------------------- */
1869 /* Called from a user thread, lock is not held */
1871 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1873 SendMessageData *data = user_data;
1875 CONNECTION_LOCK (data->connection);
1876 if (data->delivered)
1879 g_simple_async_result_set_error (data->simple,
1881 G_IO_ERROR_CANCELLED,
1882 _("Operation was cancelled"));
1884 send_message_with_reply_deliver (data, TRUE);
1887 CONNECTION_UNLOCK (data->connection);
1891 /* Can be called from any thread with or without lock held */
1893 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1896 SendMessageData *data = user_data;
1897 GSource *idle_source;
1899 /* postpone cancellation to idle handler since we may be called directly
1900 * via g_cancellable_connect() (e.g. holding lock)
1902 idle_source = g_idle_source_new ();
1903 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1904 g_source_set_callback (idle_source,
1905 send_message_with_reply_cancelled_idle_cb,
1906 send_message_data_ref (data),
1907 (GDestroyNotify) send_message_data_unref);
1908 g_source_attach (idle_source, data->main_context);
1909 g_source_unref (idle_source);
1912 /* ---------------------------------------------------------------------------------------------------- */
1914 /* Called from a user thread, lock is not held */
1916 send_message_with_reply_timeout_cb (gpointer user_data)
1918 SendMessageData *data = user_data;
1920 CONNECTION_LOCK (data->connection);
1921 if (data->delivered)
1924 g_simple_async_result_set_error (data->simple,
1926 G_IO_ERROR_TIMED_OUT,
1927 _("Timeout was reached"));
1929 send_message_with_reply_deliver (data, TRUE);
1932 CONNECTION_UNLOCK (data->connection);
1937 /* ---------------------------------------------------------------------------------------------------- */
1939 /* Called from a user thread, connection's lock is held */
1941 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1942 GDBusMessage *message,
1943 GDBusSendMessageFlags flags,
1945 volatile guint32 *out_serial,
1946 GCancellable *cancellable,
1947 GAsyncReadyCallback callback,
1950 GSimpleAsyncResult *simple;
1951 SendMessageData *data;
1953 volatile guint32 serial;
1957 if (out_serial == NULL)
1958 out_serial = &serial;
1960 if (timeout_msec == -1)
1961 timeout_msec = 25 * 1000;
1963 simple = g_simple_async_result_new (G_OBJECT (connection),
1966 g_dbus_connection_send_message_with_reply);
1967 g_simple_async_result_set_check_cancellable (simple, cancellable);
1969 if (g_cancellable_is_cancelled (cancellable))
1971 g_simple_async_result_set_error (simple,
1973 G_IO_ERROR_CANCELLED,
1974 _("Operation was cancelled"));
1975 g_simple_async_result_complete_in_idle (simple);
1976 g_object_unref (simple);
1981 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1983 g_simple_async_result_take_error (simple, error);
1984 g_simple_async_result_complete_in_idle (simple);
1985 g_object_unref (simple);
1989 data = g_new0 (SendMessageData, 1);
1990 data->ref_count = 1;
1991 data->connection = g_object_ref (connection);
1992 data->simple = simple;
1993 data->serial = *out_serial;
1994 data->main_context = g_main_context_ref_thread_default ();
1996 if (cancellable != NULL)
1998 data->cancellable = g_object_ref (cancellable);
1999 data->cancellable_handler_id = g_cancellable_connect (cancellable,
2000 G_CALLBACK (send_message_with_reply_cancelled_cb),
2001 send_message_data_ref (data),
2002 (GDestroyNotify) send_message_data_unref);
2005 if (timeout_msec != G_MAXINT)
2007 data->timeout_source = g_timeout_source_new (timeout_msec);
2008 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
2009 g_source_set_callback (data->timeout_source,
2010 send_message_with_reply_timeout_cb,
2011 send_message_data_ref (data),
2012 (GDestroyNotify) send_message_data_unref);
2013 g_source_attach (data->timeout_source, data->main_context);
2014 g_source_unref (data->timeout_source);
2017 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
2018 GUINT_TO_POINTER (*out_serial),
2026 * g_dbus_connection_send_message_with_reply:
2027 * @connection: a #GDBusConnection
2028 * @message: a #GDBusMessage
2029 * @flags: flags affecting how the message is sent
2030 * @timeout_msec: the timeout in milliseconds, -1 to use the default
2031 * timeout or %G_MAXINT for no timeout
2032 * @out_serial: (out) (allow-none): return location for serial number assigned
2033 * to @message when sending it or %NULL
2034 * @cancellable: (allow-none): a #GCancellable or %NULL
2035 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request
2036 * is satisfied or %NULL if you don't care about the result
2037 * @user_data: The data to pass to @callback
2039 * Asynchronously sends @message to the peer represented by @connection.
2041 * Unless @flags contain the
2042 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2043 * will be assigned by @connection and set on @message via
2044 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2045 * serial number used will be written to this location prior to
2046 * submitting the message to the underlying transport.
2048 * If @connection is closed then the operation will fail with
2049 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2050 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2051 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2053 * This is an asynchronous method. When the operation is finished, @callback will be invoked
2054 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
2055 * of the thread you are calling this method from. You can then call
2056 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
2057 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
2059 * Note that @message must be unlocked, unless @flags contain the
2060 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2062 * See <xref linkend="gdbus-server"/> and <xref
2063 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2064 * low-level API to send and receive UNIX file descriptors.
2069 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
2070 GDBusMessage *message,
2071 GDBusSendMessageFlags flags,
2073 volatile guint32 *out_serial,
2074 GCancellable *cancellable,
2075 GAsyncReadyCallback callback,
2078 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2079 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2080 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2081 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2083 CONNECTION_LOCK (connection);
2084 g_dbus_connection_send_message_with_reply_unlocked (connection,
2092 CONNECTION_UNLOCK (connection);
2096 * g_dbus_connection_send_message_with_reply_finish:
2097 * @connection: a #GDBusConnection
2098 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
2099 * g_dbus_connection_send_message_with_reply()
2100 * @error: teturn location for error or %NULL
2102 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2104 * Note that @error is only set if a local in-process error
2105 * occurred. That is to say that the returned #GDBusMessage object may
2106 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2107 * g_dbus_message_to_gerror() to transcode this to a #GError.
2109 * See <xref linkend="gdbus-server"/> and <xref
2110 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2111 * low-level API to send and receive UNIX file descriptors.
2113 * Returns: (transfer full): a locked #GDBusMessage or %NULL if @error is set
2118 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2122 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2123 GDBusMessage *reply;
2125 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2126 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2130 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
2132 if (g_simple_async_result_propagate_error (simple, error))
2135 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
2141 /* ---------------------------------------------------------------------------------------------------- */
2146 GMainContext *context;
2148 } SendMessageSyncData;
2150 /* Called from a user thread, lock is not held */
2152 send_message_with_reply_sync_cb (GDBusConnection *connection,
2156 SendMessageSyncData *data = user_data;
2157 data->res = g_object_ref (res);
2158 g_main_loop_quit (data->loop);
2162 * g_dbus_connection_send_message_with_reply_sync:
2163 * @connection: a #GDBusConnection
2164 * @message: a #GDBusMessage
2165 * @flags: flags affecting how the message is sent.
2166 * @timeout_msec: the timeout in milliseconds, -1 to use the default
2167 * timeout or %G_MAXINT for no timeout
2168 * @out_serial: (out) (allow-none): return location for serial number
2169 * assigned to @message when sending it or %NULL
2170 * @cancellable: (allow-none): a #GCancellable or %NULL
2171 * @error: return location for error or %NULL
2173 * Synchronously sends @message to the peer represented by @connection
2174 * and blocks the calling thread until a reply is received or the
2175 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2176 * for the asynchronous version of this method.
2178 * Unless @flags contain the
2179 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2180 * will be assigned by @connection and set on @message via
2181 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2182 * serial number used will be written to this location prior to
2183 * submitting the message to the underlying transport.
2185 * If @connection is closed then the operation will fail with
2186 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2187 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2188 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2190 * Note that @error is only set if a local in-process error
2191 * occurred. That is to say that the returned #GDBusMessage object may
2192 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2193 * g_dbus_message_to_gerror() to transcode this to a #GError.
2195 * See <xref linkend="gdbus-server"/> and <xref
2196 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2197 * low-level API to send and receive UNIX file descriptors.
2199 * Note that @message must be unlocked, unless @flags contain the
2200 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2202 * Returns: (transfer full): a locked #GDBusMessage that is the reply
2203 * to @message or %NULL if @error is set
2208 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2209 GDBusMessage *message,
2210 GDBusSendMessageFlags flags,
2212 volatile guint32 *out_serial,
2213 GCancellable *cancellable,
2216 SendMessageSyncData *data;
2217 GDBusMessage *reply;
2219 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2220 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2221 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2222 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2223 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2225 data = g_new0 (SendMessageSyncData, 1);
2226 data->context = g_main_context_new ();
2227 data->loop = g_main_loop_new (data->context, FALSE);
2229 g_main_context_push_thread_default (data->context);
2231 g_dbus_connection_send_message_with_reply (connection,
2237 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2239 g_main_loop_run (data->loop);
2240 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2244 g_main_context_pop_thread_default (data->context);
2246 g_main_context_unref (data->context);
2247 g_main_loop_unref (data->loop);
2248 g_object_unref (data->res);
2254 /* ---------------------------------------------------------------------------------------------------- */
2258 GDBusMessageFilterFunction func;
2265 GDBusMessageFilterFunction filter_function;
2267 GDestroyNotify user_data_free_func;
2270 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2272 on_worker_message_received (GDBusWorker *worker,
2273 GDBusMessage *message,
2276 GDBusConnection *connection;
2277 FilterCallback *filters;
2282 G_LOCK (message_bus_lock);
2283 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2286 G_UNLOCK (message_bus_lock);
2289 connection = G_DBUS_CONNECTION (user_data);
2290 g_object_ref (connection);
2291 G_UNLOCK (message_bus_lock);
2293 //g_debug ("in on_worker_message_received");
2295 g_object_ref (message);
2296 g_dbus_message_lock (message);
2298 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2300 /* First collect the set of callback functions */
2301 CONNECTION_LOCK (connection);
2302 num_filters = connection->filters->len;
2303 filters = g_new0 (FilterCallback, num_filters);
2304 for (n = 0; n < num_filters; n++)
2306 FilterData *data = connection->filters->pdata[n];
2307 filters[n].func = data->filter_function;
2308 filters[n].user_data = data->user_data;
2310 CONNECTION_UNLOCK (connection);
2312 /* then call the filters in order (without holding the lock) */
2313 for (n = 0; n < num_filters; n++)
2315 message = filters[n].func (connection,
2318 filters[n].user_data);
2319 if (message == NULL)
2321 g_dbus_message_lock (message);
2324 /* Standard dispatch unless the filter ate the message - no need to
2325 * do anything if the message was altered
2327 if (message != NULL)
2329 GDBusMessageType message_type;
2331 message_type = g_dbus_message_get_message_type (message);
2332 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2334 guint32 reply_serial;
2335 SendMessageData *send_message_data;
2337 reply_serial = g_dbus_message_get_reply_serial (message);
2338 CONNECTION_LOCK (connection);
2339 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2340 GUINT_TO_POINTER (reply_serial));
2341 if (send_message_data != NULL)
2343 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2344 send_message_data_deliver_reply_unlocked (send_message_data, message);
2348 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2350 CONNECTION_UNLOCK (connection);
2352 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2354 CONNECTION_LOCK (connection);
2355 distribute_signals (connection, message);
2356 CONNECTION_UNLOCK (connection);
2358 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2360 CONNECTION_LOCK (connection);
2361 distribute_method_call (connection, message);
2362 CONNECTION_UNLOCK (connection);
2366 if (message != NULL)
2367 g_object_unref (message);
2368 g_object_unref (connection);
2372 /* Called in GDBusWorker's thread, lock is not held */
2373 static GDBusMessage *
2374 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2375 GDBusMessage *message,
2378 GDBusConnection *connection;
2379 FilterCallback *filters;
2384 G_LOCK (message_bus_lock);
2385 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2388 G_UNLOCK (message_bus_lock);
2391 connection = G_DBUS_CONNECTION (user_data);
2392 g_object_ref (connection);
2393 G_UNLOCK (message_bus_lock);
2395 //g_debug ("in on_worker_message_about_to_be_sent");
2397 /* First collect the set of callback functions */
2398 CONNECTION_LOCK (connection);
2399 num_filters = connection->filters->len;
2400 filters = g_new0 (FilterCallback, num_filters);
2401 for (n = 0; n < num_filters; n++)
2403 FilterData *data = connection->filters->pdata[n];
2404 filters[n].func = data->filter_function;
2405 filters[n].user_data = data->user_data;
2407 CONNECTION_UNLOCK (connection);
2409 /* then call the filters in order (without holding the lock) */
2410 for (n = 0; n < num_filters; n++)
2412 g_dbus_message_lock (message);
2413 message = filters[n].func (connection,
2416 filters[n].user_data);
2417 if (message == NULL)
2421 g_object_unref (connection);
2427 /* called with connection lock held, in GDBusWorker thread */
2429 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2431 SendMessageData *data = value;
2433 if (data->delivered)
2436 g_simple_async_result_set_error (data->simple,
2439 _("The connection is closed"));
2441 /* Ask send_message_with_reply_deliver not to remove the element from the
2442 * hash table - we're in the middle of a foreach; that would be unsafe.
2443 * Instead, return TRUE from this function so that it gets removed safely.
2445 send_message_with_reply_deliver (data, FALSE);
2449 /* Called in GDBusWorker's thread - we must not block - without lock held */
2451 on_worker_closed (GDBusWorker *worker,
2452 gboolean remote_peer_vanished,
2456 GDBusConnection *connection;
2458 guint old_atomic_flags;
2460 G_LOCK (message_bus_lock);
2461 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2464 G_UNLOCK (message_bus_lock);
2467 connection = G_DBUS_CONNECTION (user_data);
2468 g_object_ref (connection);
2469 G_UNLOCK (message_bus_lock);
2471 //g_debug ("in on_worker_closed: %s", error->message);
2473 CONNECTION_LOCK (connection);
2474 /* Even though this is atomic, we do it inside the lock to avoid breaking
2475 * assumptions in remove_match_rule(). We'd need the lock in a moment
2476 * anyway, so, no loss.
2478 old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
2480 if (!(old_atomic_flags & FLAG_CLOSED))
2482 g_hash_table_foreach_remove (connection->map_method_serial_to_send_message_data, cancel_method_on_close, NULL);
2483 schedule_closed_unlocked (connection, remote_peer_vanished, error);
2485 CONNECTION_UNLOCK (connection);
2487 g_object_unref (connection);
2490 /* ---------------------------------------------------------------------------------------------------- */
2492 /* Determines the biggest set of capabilities we can support on this
2495 * Called with the init_lock held.
2497 static GDBusCapabilityFlags
2498 get_offered_capabilities_max (GDBusConnection *connection)
2500 GDBusCapabilityFlags ret;
2501 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2503 if (G_IS_UNIX_CONNECTION (connection->stream))
2504 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2509 /* Called in a user thread, lock is not held */
2511 initable_init (GInitable *initable,
2512 GCancellable *cancellable,
2515 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2518 /* This method needs to be idempotent to work with the singleton
2519 * pattern. See the docs for g_initable_init(). We implement this by
2522 * Unfortunately we can't use the main lock since the on_worker_*()
2523 * callbacks above needs the lock during initialization (for message
2524 * bus connections we do a synchronous Hello() call on the bus).
2526 g_mutex_lock (&connection->init_lock);
2530 /* Make this a no-op if we're already initialized (successfully or
2533 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
2535 ret = (connection->initialization_error == NULL);
2539 /* Because of init_lock, we can't get here twice in different threads */
2540 g_assert (connection->initialization_error == NULL);
2542 /* The user can pass multiple (but mutally exclusive) construct
2545 * - stream (of type GIOStream)
2546 * - address (of type gchar*)
2548 * At the end of the day we end up with a non-NULL GIOStream
2549 * object in connection->stream.
2551 if (connection->address != NULL)
2553 g_assert (connection->stream == NULL);
2555 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2556 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2558 g_set_error_literal (&connection->initialization_error,
2560 G_IO_ERROR_INVALID_ARGUMENT,
2561 _("Unsupported flags encountered when constructing a client-side connection"));
2565 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2566 NULL, /* TODO: out_guid */
2568 &connection->initialization_error);
2569 if (connection->stream == NULL)
2572 else if (connection->stream != NULL)
2578 g_assert_not_reached ();
2581 /* Authenticate the connection */
2582 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2584 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2585 g_assert (connection->guid != NULL);
2586 connection->auth = _g_dbus_auth_new (connection->stream);
2587 if (!_g_dbus_auth_run_server (connection->auth,
2588 connection->authentication_observer,
2590 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2591 get_offered_capabilities_max (connection),
2592 &connection->capabilities,
2593 &connection->credentials,
2595 &connection->initialization_error))
2598 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2600 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2601 g_assert (connection->guid == NULL);
2602 connection->auth = _g_dbus_auth_new (connection->stream);
2603 connection->guid = _g_dbus_auth_run_client (connection->auth,
2604 connection->authentication_observer,
2605 get_offered_capabilities_max (connection),
2606 &connection->capabilities,
2608 &connection->initialization_error);
2609 if (connection->guid == NULL)
2613 if (connection->authentication_observer != NULL)
2615 g_object_unref (connection->authentication_observer);
2616 connection->authentication_observer = NULL;
2619 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2621 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2624 /* We want all IO operations to be non-blocking since they happen in
2625 * the worker thread which is shared by _all_ connections.
2627 if (G_IS_SOCKET_CONNECTION (connection->stream))
2629 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2633 G_LOCK (message_bus_lock);
2634 if (alive_connections == NULL)
2635 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2636 g_hash_table_insert (alive_connections, connection, connection);
2637 G_UNLOCK (message_bus_lock);
2639 connection->worker = _g_dbus_worker_new (connection->stream,
2640 connection->capabilities,
2641 ((connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) != 0),
2642 on_worker_message_received,
2643 on_worker_message_about_to_be_sent,
2647 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2648 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2650 GVariant *hello_result;
2652 /* we could lift this restriction by adding code in gdbusprivate.c */
2653 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2655 g_set_error_literal (&connection->initialization_error,
2658 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2662 hello_result = g_dbus_connection_call_sync (connection,
2663 "org.freedesktop.DBus", /* name */
2664 "/org/freedesktop/DBus", /* path */
2665 "org.freedesktop.DBus", /* interface */
2667 NULL, /* parameters */
2668 G_VARIANT_TYPE ("(s)"),
2669 CALL_FLAGS_INITIALIZING,
2671 NULL, /* TODO: cancellable */
2672 &connection->initialization_error);
2673 if (hello_result == NULL)
2676 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2677 g_variant_unref (hello_result);
2678 //g_debug ("unique name is '%s'", connection->bus_unique_name);
2685 g_assert (connection->initialization_error != NULL);
2686 g_propagate_error (error, g_error_copy (connection->initialization_error));
2689 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
2690 g_mutex_unlock (&connection->init_lock);
2696 initable_iface_init (GInitableIface *initable_iface)
2698 initable_iface->init = initable_init;
2701 /* ---------------------------------------------------------------------------------------------------- */
2704 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2709 /* ---------------------------------------------------------------------------------------------------- */
2712 * g_dbus_connection_new:
2713 * @stream: a #GIOStream
2714 * @guid: (allow-none): the GUID to use if a authenticating as a server or %NULL
2715 * @flags: flags describing how to make the connection
2716 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
2717 * @cancellable: (allow-none): a #GCancellable or %NULL
2718 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
2719 * @user_data: the data to pass to @callback
2721 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2722 * with the end represented by @stream.
2724 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2725 * will be put into non-blocking mode.
2727 * The D-Bus connection will interact with @stream from a worker thread.
2728 * As a result, the caller should not interact with @stream after this
2729 * method has been called, except by calling g_object_unref() on it.
2731 * If @observer is not %NULL it may be used to control the
2732 * authentication process.
2734 * When the operation is finished, @callback will be invoked. You can
2735 * then call g_dbus_connection_new_finish() to get the result of the
2738 * This is a asynchronous failable constructor. See
2739 * g_dbus_connection_new_sync() for the synchronous
2745 g_dbus_connection_new (GIOStream *stream,
2747 GDBusConnectionFlags flags,
2748 GDBusAuthObserver *observer,
2749 GCancellable *cancellable,
2750 GAsyncReadyCallback callback,
2753 g_return_if_fail (G_IS_IO_STREAM (stream));
2754 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2762 "authentication-observer", observer,
2767 * g_dbus_connection_new_finish:
2768 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback
2769 * passed to g_dbus_connection_new().
2770 * @error: return location for error or %NULL
2772 * Finishes an operation started with g_dbus_connection_new().
2774 * Returns: a #GDBusConnection or %NULL if @error is set. Free
2775 * with g_object_unref().
2780 g_dbus_connection_new_finish (GAsyncResult *res,
2784 GObject *source_object;
2786 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2787 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2789 source_object = g_async_result_get_source_object (res);
2790 g_assert (source_object != NULL);
2791 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2794 g_object_unref (source_object);
2796 return G_DBUS_CONNECTION (object);
2802 * g_dbus_connection_new_sync:
2803 * @stream: a #GIOStream
2804 * @guid: (allow-none): the GUID to use if a authenticating as a server or %NULL
2805 * @flags: flags describing how to make the connection
2806 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
2807 * @cancellable: (allow-none): a #GCancellable or %NULL
2808 * @error: return location for error or %NULL
2810 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2811 * with the end represented by @stream.
2813 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2814 * will be put into non-blocking mode.
2816 * The D-Bus connection will interact with @stream from a worker thread.
2817 * As a result, the caller should not interact with @stream after this
2818 * method has been called, except by calling g_object_unref() on it.
2820 * If @observer is not %NULL it may be used to control the
2821 * authentication process.
2823 * This is a synchronous failable constructor. See
2824 * g_dbus_connection_new() for the asynchronous version.
2826 * Returns: a #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2831 g_dbus_connection_new_sync (GIOStream *stream,
2833 GDBusConnectionFlags flags,
2834 GDBusAuthObserver *observer,
2835 GCancellable *cancellable,
2838 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2839 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2840 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2846 "authentication-observer", observer,
2850 /* ---------------------------------------------------------------------------------------------------- */
2853 * g_dbus_connection_new_for_address:
2854 * @address: a D-Bus address
2855 * @flags: flags describing how to make the connection
2856 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
2857 * @cancellable: (allow-none): a #GCancellable or %NULL
2858 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
2859 * @user_data: the data to pass to @callback
2861 * Asynchronously connects and sets up a D-Bus client connection for
2862 * exchanging D-Bus messages with an endpoint specified by @address
2863 * which must be in the D-Bus address format.
2865 * This constructor can only be used to initiate client-side
2866 * connections - use g_dbus_connection_new() if you need to act as the
2867 * server. In particular, @flags cannot contain the
2868 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2869 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2871 * When the operation is finished, @callback will be invoked. You can
2872 * then call g_dbus_connection_new_finish() to get the result of the
2875 * If @observer is not %NULL it may be used to control the
2876 * authentication process.
2878 * This is a asynchronous failable constructor. See
2879 * g_dbus_connection_new_for_address_sync() for the synchronous
2885 g_dbus_connection_new_for_address (const gchar *address,
2886 GDBusConnectionFlags flags,
2887 GDBusAuthObserver *observer,
2888 GCancellable *cancellable,
2889 GAsyncReadyCallback callback,
2892 g_return_if_fail (address != NULL);
2893 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2900 "authentication-observer", observer,
2905 * g_dbus_connection_new_for_address_finish:
2906 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
2907 * to g_dbus_connection_new()
2908 * @error: return location for error or %NULL
2910 * Finishes an operation started with g_dbus_connection_new_for_address().
2912 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
2918 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2922 GObject *source_object;
2924 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2925 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2927 source_object = g_async_result_get_source_object (res);
2928 g_assert (source_object != NULL);
2929 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2932 g_object_unref (source_object);
2934 return G_DBUS_CONNECTION (object);
2940 * g_dbus_connection_new_for_address_sync:
2941 * @address: a D-Bus address
2942 * @flags: flags describing how to make the connection
2943 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
2944 * @cancellable: (allow-none): a #GCancellable or %NULL
2945 * @error: return location for error or %NULL
2947 * Synchronously connects and sets up a D-Bus client connection for
2948 * exchanging D-Bus messages with an endpoint specified by @address
2949 * which must be in the D-Bus address format.
2951 * This constructor can only be used to initiate client-side
2952 * connections - use g_dbus_connection_new_sync() if you need to act
2953 * as the server. In particular, @flags cannot contain the
2954 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2955 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2957 * This is a synchronous failable constructor. See
2958 * g_dbus_connection_new_for_address() for the asynchronous version.
2960 * If @observer is not %NULL it may be used to control the
2961 * authentication process.
2963 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
2969 g_dbus_connection_new_for_address_sync (const gchar *address,
2970 GDBusConnectionFlags flags,
2971 GDBusAuthObserver *observer,
2972 GCancellable *cancellable,
2975 g_return_val_if_fail (address != NULL, NULL);
2976 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2977 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2982 "authentication-observer", observer,
2986 /* ---------------------------------------------------------------------------------------------------- */
2989 * g_dbus_connection_set_exit_on_close:
2990 * @connection: a #GDBusConnection
2991 * @exit_on_close: whether the process should be terminated
2992 * when @connection is closed by the remote peer
2994 * Sets whether the process should be terminated when @connection is
2995 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2998 * Note that this function should be used with care. Most modern UNIX
2999 * desktops tie the notion of a user session the session bus, and expect
3000 * all of a users applications to quit when their bus connection goes away.
3001 * If you are setting @exit_on_close to %FALSE for the shared session
3002 * bus connection, you should make sure that your application exits
3003 * when the user session ends.
3008 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
3009 gboolean exit_on_close)
3011 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3014 g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
3016 g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
3021 * g_dbus_connection_get_exit_on_close:
3022 * @connection: a #GDBusConnection
3024 * Gets whether the process is terminated when @connection is
3025 * closed by the remote peer. See
3026 * #GDBusConnection:exit-on-close for more details.
3028 * Returns: whether the process is terminated when @connection is
3029 * closed by the remote peer
3034 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
3036 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3038 if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
3045 * g_dbus_connection_get_guid:
3046 * @connection: a #GDBusConnection
3048 * The GUID of the peer performing the role of server when
3049 * authenticating. See #GDBusConnection:guid for more details.
3051 * Returns: The GUID. Do not free this string, it is owned by
3057 g_dbus_connection_get_guid (GDBusConnection *connection)
3059 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3060 return connection->guid;
3064 * g_dbus_connection_get_unique_name:
3065 * @connection: a #GDBusConnection
3067 * Gets the unique name of @connection as assigned by the message
3068 * bus. This can also be used to figure out if @connection is a
3069 * message bus connection.
3071 * Returns: the unique name or %NULL if @connection is not a message
3072 * bus connection. Do not free this string, it is owned by
3078 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3080 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3082 /* do not use g_return_val_if_fail(), we want the memory barrier */
3083 if (!check_initialized (connection))
3086 return connection->bus_unique_name;
3090 * g_dbus_connection_get_peer_credentials:
3091 * @connection: a #GDBusConnection
3093 * Gets the credentials of the authenticated peer. This will always
3094 * return %NULL unless @connection acted as a server
3095 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3096 * when set up and the client passed credentials as part of the
3097 * authentication process.
3099 * In a message bus setup, the message bus is always the server and
3100 * each application is a client. So this method will always return
3101 * %NULL for message bus clients.
3103 * Returns: (transfer none): a #GCredentials or %NULL if not available.
3104 * Do not free this object, it is owned by @connection.
3109 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3111 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3113 /* do not use g_return_val_if_fail(), we want the memory barrier */
3114 if (!check_initialized (connection))
3117 return connection->credentials;
3120 /* ---------------------------------------------------------------------------------------------------- */
3122 static guint _global_filter_id = 1;
3125 * g_dbus_connection_add_filter:
3126 * @connection: a #GDBusConnection
3127 * @filter_function: a filter function
3128 * @user_data: user data to pass to @filter_function
3129 * @user_data_free_func: function to free @user_data with when filter
3130 * is removed or %NULL
3132 * Adds a message filter. Filters are handlers that are run on all
3133 * incoming and outgoing messages, prior to standard dispatch. Filters
3134 * are run in the order that they were added. The same handler can be
3135 * added as a filter more than once, in which case it will be run more
3136 * than once. Filters added during a filter callback won't be run on
3137 * the message being processed. Filter functions are allowed to modify
3138 * and even drop messages.
3140 * Note that filters are run in a dedicated message handling thread so
3141 * they can't block and, generally, can't do anything but signal a
3142 * worker thread. Also note that filters are rarely needed - use API
3143 * such as g_dbus_connection_send_message_with_reply(),
3144 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3146 * If a filter consumes an incoming message the message is not
3147 * dispatched anywhere else - not even the standard dispatch machinery
3148 * (that API such as g_dbus_connection_signal_subscribe() and
3149 * g_dbus_connection_send_message_with_reply() relies on) will see the
3150 * message. Similary, if a filter consumes an outgoing message, the
3151 * message will not be sent to the other peer.
3153 * Returns: a filter identifier that can be used with
3154 * g_dbus_connection_remove_filter()
3159 g_dbus_connection_add_filter (GDBusConnection *connection,
3160 GDBusMessageFilterFunction filter_function,
3162 GDestroyNotify user_data_free_func)
3166 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3167 g_return_val_if_fail (filter_function != NULL, 0);
3168 g_return_val_if_fail (check_initialized (connection), 0);
3170 CONNECTION_LOCK (connection);
3171 data = g_new0 (FilterData, 1);
3172 data->id = _global_filter_id++; /* TODO: overflow etc. */
3173 data->filter_function = filter_function;
3174 data->user_data = user_data;
3175 data->user_data_free_func = user_data_free_func;
3176 g_ptr_array_add (connection->filters, data);
3177 CONNECTION_UNLOCK (connection);
3182 /* only called from finalize(), removes all filters */
3184 purge_all_filters (GDBusConnection *connection)
3187 for (n = 0; n < connection->filters->len; n++)
3189 FilterData *data = connection->filters->pdata[n];
3190 if (data->user_data_free_func != NULL)
3191 data->user_data_free_func (data->user_data);
3197 * g_dbus_connection_remove_filter:
3198 * @connection: a #GDBusConnection
3199 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3206 g_dbus_connection_remove_filter (GDBusConnection *connection,
3210 FilterData *to_destroy;
3212 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3213 g_return_if_fail (check_initialized (connection));
3215 CONNECTION_LOCK (connection);
3217 for (n = 0; n < connection->filters->len; n++)
3219 FilterData *data = connection->filters->pdata[n];
3220 if (data->id == filter_id)
3222 g_ptr_array_remove_index (connection->filters, n);
3227 CONNECTION_UNLOCK (connection);
3229 /* do free without holding lock */
3230 if (to_destroy != NULL)
3232 if (to_destroy->user_data_free_func != NULL)
3233 to_destroy->user_data_free_func (to_destroy->user_data);
3234 g_free (to_destroy);
3238 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3242 /* ---------------------------------------------------------------------------------------------------- */
3248 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3249 gchar *interface_name;
3253 GDBusSignalFlags flags;
3254 GArray *subscribers;
3259 GDBusSignalCallback callback;
3261 GDestroyNotify user_data_free_func;
3263 GMainContext *context;
3267 signal_data_free (SignalData *signal_data)
3269 g_free (signal_data->rule);
3270 g_free (signal_data->sender);
3271 g_free (signal_data->sender_unique_name);
3272 g_free (signal_data->interface_name);
3273 g_free (signal_data->member);
3274 g_free (signal_data->object_path);
3275 g_free (signal_data->arg0);
3276 g_array_free (signal_data->subscribers, TRUE);
3277 g_free (signal_data);
3281 args_to_rule (const gchar *sender,
3282 const gchar *interface_name,
3283 const gchar *member,
3284 const gchar *object_path,
3286 GDBusSignalFlags flags)
3290 rule = g_string_new ("type='signal'");
3291 if (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE)
3292 g_string_prepend_c (rule, '-');
3294 g_string_append_printf (rule, ",sender='%s'", sender);
3295 if (interface_name != NULL)
3296 g_string_append_printf (rule, ",interface='%s'", interface_name);
3298 g_string_append_printf (rule, ",member='%s'", member);
3299 if (object_path != NULL)
3300 g_string_append_printf (rule, ",path='%s'", object_path);
3304 if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3305 g_string_append_printf (rule, ",arg0path='%s'", arg0);
3306 else if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3307 g_string_append_printf (rule, ",arg0namespace='%s'", arg0);
3309 g_string_append_printf (rule, ",arg0='%s'", arg0);
3312 return g_string_free (rule, FALSE);
3315 static guint _global_subscriber_id = 1;
3316 static guint _global_registration_id = 1;
3317 static guint _global_subtree_registration_id = 1;
3319 /* ---------------------------------------------------------------------------------------------------- */
3321 /* Called in a user thread, lock is held */
3323 add_match_rule (GDBusConnection *connection,
3324 const gchar *match_rule)
3327 GDBusMessage *message;
3329 if (match_rule[0] == '-')
3332 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3333 "/org/freedesktop/DBus", /* path */
3334 "org.freedesktop.DBus", /* interface */
3336 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3338 if (!g_dbus_connection_send_message_unlocked (connection,
3340 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3344 g_critical ("Error while sending AddMatch() message: %s", error->message);
3345 g_error_free (error);
3347 g_object_unref (message);
3350 /* ---------------------------------------------------------------------------------------------------- */
3352 /* Called in a user thread, lock is held */
3354 remove_match_rule (GDBusConnection *connection,
3355 const gchar *match_rule)
3358 GDBusMessage *message;
3360 if (match_rule[0] == '-')
3363 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3364 "/org/freedesktop/DBus", /* path */
3365 "org.freedesktop.DBus", /* interface */
3367 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3370 if (!g_dbus_connection_send_message_unlocked (connection,
3372 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3376 /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
3377 * critical; but we're holding the lock, and our caller checked whether
3378 * we were already closed, so we can't get that error.
3380 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3381 g_error_free (error);
3383 g_object_unref (message);
3386 /* ---------------------------------------------------------------------------------------------------- */
3389 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3391 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3392 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3393 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3394 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3395 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3398 /* ---------------------------------------------------------------------------------------------------- */
3401 * g_dbus_connection_signal_subscribe:
3402 * @connection: a #GDBusConnection
3403 * @sender: (allow-none): sender name to match on (unique or well-known name)
3404 * or %NULL to listen from all senders
3405 * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3406 * match on all interfaces
3407 * @member: (allow-none): D-Bus signal name to match on or %NULL to match on
3409 * @object_path: (allow-none): object path to match on or %NULL to match on
3411 * @arg0: (allow-none): contents of first string argument to match on or %NULL
3412 * to match on all kinds of arguments
3413 * @flags: flags describing how to subscribe to the signal (currently unused)
3414 * @callback: callback to invoke when there is a signal matching the requested data
3415 * @user_data: user data to pass to @callback
3416 * @user_data_free_func: (allow-none): function to free @user_data with when
3417 * subscription is removed or %NULL
3419 * Subscribes to signals on @connection and invokes @callback with a
3420 * whenever the signal is received. Note that @callback will be invoked
3422 * linkend="g-main-context-push-thread-default">thread-default main
3423 * loop</link> of the thread you are calling this method from.
3425 * If @connection is not a message bus connection, @sender must be
3428 * If @sender is a well-known name note that @callback is invoked with
3429 * the unique name for the owner of @sender, not the well-known name
3430 * as one would expect. This is because the message bus rewrites the
3431 * name. As such, to avoid certain race conditions, users should be
3432 * tracking the name owner of the well-known name and use that when
3433 * processing the received signal.
3435 * If one of %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE or
3436 * %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH are given, @arg0 is
3437 * interpreted as part of a namespace or path. The first argument
3438 * of a signal is matched against that part as specified by D-Bus.
3440 * Returns: a subscription identifier that can be used with g_dbus_connection_signal_unsubscribe()
3445 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3446 const gchar *sender,
3447 const gchar *interface_name,
3448 const gchar *member,
3449 const gchar *object_path,
3451 GDBusSignalFlags flags,
3452 GDBusSignalCallback callback,
3454 GDestroyNotify user_data_free_func)
3457 SignalData *signal_data;
3458 SignalSubscriber subscriber;
3459 GPtrArray *signal_data_array;
3460 const gchar *sender_unique_name;
3462 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3463 * an OOM condition. We might want to change that but that would involve making
3464 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3465 * handle that. And there's really no sensible way of handling this short of retrying
3466 * to add the match rule... and then there's the little thing that, hey, maybe there's
3467 * a reason the bus in an OOM condition.
3469 * Doable, but not really sure it's worth it...
3472 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3473 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3474 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3475 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3476 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3477 g_return_val_if_fail (callback != NULL, 0);
3478 g_return_val_if_fail (check_initialized (connection), 0);
3479 g_return_val_if_fail (!((flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH) && (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)), 0);
3480 g_return_val_if_fail (!(arg0 == NULL && (flags & (G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH | G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE))), 0);
3482 CONNECTION_LOCK (connection);
3484 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3485 * with a '-' character to prefix the rule (which will otherwise be
3488 * This allows us to hash the rule and do our lifecycle tracking in
3489 * the usual way, but the '-' prevents the match rule from ever
3490 * actually being send to the bus (either for add or remove).
3492 rule = args_to_rule (sender, interface_name, member, object_path, arg0, flags);
3494 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3495 sender_unique_name = sender;
3497 sender_unique_name = "";
3499 subscriber.callback = callback;
3500 subscriber.user_data = user_data;
3501 subscriber.user_data_free_func = user_data_free_func;
3502 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3503 subscriber.context = g_main_context_ref_thread_default ();
3505 /* see if we've already have this rule */
3506 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3507 if (signal_data != NULL)
3509 g_array_append_val (signal_data->subscribers, subscriber);
3514 signal_data = g_new0 (SignalData, 1);
3515 signal_data->rule = rule;
3516 signal_data->sender = g_strdup (sender);
3517 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3518 signal_data->interface_name = g_strdup (interface_name);
3519 signal_data->member = g_strdup (member);
3520 signal_data->object_path = g_strdup (object_path);
3521 signal_data->arg0 = g_strdup (arg0);
3522 signal_data->flags = flags;
3523 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3524 g_array_append_val (signal_data->subscribers, subscriber);
3526 g_hash_table_insert (connection->map_rule_to_signal_data,
3530 /* Add the match rule to the bus...
3532 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3533 * always send such messages to us.
3535 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3537 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3538 add_match_rule (connection, signal_data->rule);
3541 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3542 signal_data->sender_unique_name);
3543 if (signal_data_array == NULL)
3545 signal_data_array = g_ptr_array_new ();
3546 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3547 g_strdup (signal_data->sender_unique_name),
3550 g_ptr_array_add (signal_data_array, signal_data);
3553 g_hash_table_insert (connection->map_id_to_signal_data,
3554 GUINT_TO_POINTER (subscriber.id),
3557 CONNECTION_UNLOCK (connection);
3559 return subscriber.id;
3562 /* ---------------------------------------------------------------------------------------------------- */
3564 /* called in any thread */
3565 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3567 unsubscribe_id_internal (GDBusConnection *connection,
3568 guint subscription_id,
3569 GArray *out_removed_subscribers)
3571 SignalData *signal_data;
3572 GPtrArray *signal_data_array;
3575 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3576 GUINT_TO_POINTER (subscription_id));
3577 if (signal_data == NULL)
3579 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3583 for (n = 0; n < signal_data->subscribers->len; n++)
3585 SignalSubscriber *subscriber;
3587 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3588 if (subscriber->id != subscription_id)
3591 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3592 GUINT_TO_POINTER (subscription_id)));
3593 g_array_append_val (out_removed_subscribers, *subscriber);
3594 g_array_remove_index (signal_data->subscribers, n);
3596 if (signal_data->subscribers->len == 0)
3598 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3600 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3601 signal_data->sender_unique_name);
3602 g_warn_if_fail (signal_data_array != NULL);
3603 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3605 if (signal_data_array->len == 0)
3607 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3608 signal_data->sender_unique_name));
3611 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3612 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
3613 !is_signal_data_for_name_lost_or_acquired (signal_data) &&
3614 !g_dbus_connection_is_closed (connection) &&
3615 !connection->finalizing)
3617 /* The check for g_dbus_connection_is_closed() means that
3618 * sending the RemoveMatch message can't fail with
3619 * G_IO_ERROR_CLOSED, because we're holding the lock,
3620 * so on_worker_closed() can't happen between the check we just
3621 * did, and releasing the lock later.
3623 remove_match_rule (connection, signal_data->rule);
3626 signal_data_free (signal_data);
3632 g_assert_not_reached ();
3639 * g_dbus_connection_signal_unsubscribe:
3640 * @connection: a #GDBusConnection
3641 * @subscription_id: a subscription id obtained from
3642 * g_dbus_connection_signal_subscribe()
3644 * Unsubscribes from signals.
3649 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3650 guint subscription_id)
3652 GArray *subscribers;
3655 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3656 g_return_if_fail (check_initialized (connection));
3658 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3660 CONNECTION_LOCK (connection);
3661 unsubscribe_id_internal (connection,
3664 CONNECTION_UNLOCK (connection);
3667 g_assert (subscribers->len == 0 || subscribers->len == 1);
3669 /* call GDestroyNotify without lock held */
3670 for (n = 0; n < subscribers->len; n++)
3672 SignalSubscriber *subscriber;
3673 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3674 call_destroy_notify (subscriber->context,
3675 subscriber->user_data_free_func,
3676 subscriber->user_data);
3677 g_main_context_unref (subscriber->context);
3680 g_array_free (subscribers, TRUE);
3683 /* ---------------------------------------------------------------------------------------------------- */
3687 guint subscription_id;
3688 GDBusSignalCallback callback;
3690 GDBusMessage *message;
3691 GDBusConnection *connection;
3692 const gchar *sender;
3694 const gchar *interface;
3695 const gchar *member;
3698 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3702 emit_signal_instance_in_idle_cb (gpointer data)
3704 SignalInstance *signal_instance = data;
3705 GVariant *parameters;
3706 gboolean has_subscription;
3708 parameters = g_dbus_message_get_body (signal_instance->message);
3709 if (parameters == NULL)
3711 parameters = g_variant_new ("()");
3712 g_variant_ref_sink (parameters);
3716 g_variant_ref_sink (parameters);
3720 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3721 signal_instance->subscription_id,
3722 signal_instance->sender,
3723 signal_instance->path,
3724 signal_instance->interface,
3725 signal_instance->member,
3726 g_variant_print (parameters, TRUE));
3729 /* Careful here, don't do the callback if we no longer has the subscription */
3730 CONNECTION_LOCK (signal_instance->connection);
3731 has_subscription = FALSE;
3732 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3733 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3734 has_subscription = TRUE;
3735 CONNECTION_UNLOCK (signal_instance->connection);
3737 if (has_subscription)
3738 signal_instance->callback (signal_instance->connection,
3739 signal_instance->sender,
3740 signal_instance->path,
3741 signal_instance->interface,
3742 signal_instance->member,
3744 signal_instance->user_data);
3746 g_variant_unref (parameters);
3752 signal_instance_free (SignalInstance *signal_instance)
3754 g_object_unref (signal_instance->message);
3755 g_object_unref (signal_instance->connection);
3756 g_free (signal_instance);
3760 namespace_rule_matches (const gchar *namespace,
3766 len_namespace = strlen (namespace);
3767 len_name = strlen (name);
3769 if (len_name < len_namespace)
3772 if (memcmp (namespace, name, len_namespace) != 0)
3775 return len_namespace == len_name || name[len_namespace] == '.';
3779 path_rule_matches (const gchar *path_a,
3780 const gchar *path_b)
3784 len_a = strlen (path_a);
3785 len_b = strlen (path_b);
3787 if (len_a < len_b && path_a[len_a - 1] != '/')
3790 if (len_b < len_a && path_b[len_b - 1] != '/')
3793 return memcmp (path_a, path_b, MIN (len_a, len_b)) == 0;
3796 /* called in GDBusWorker thread WITH lock held */
3798 schedule_callbacks (GDBusConnection *connection,
3799 GPtrArray *signal_data_array,
3800 GDBusMessage *message,
3801 const gchar *sender)
3804 const gchar *interface;
3805 const gchar *member;
3814 interface = g_dbus_message_get_interface (message);
3815 member = g_dbus_message_get_member (message);
3816 path = g_dbus_message_get_path (message);
3817 arg0 = g_dbus_message_get_arg0 (message);
3820 g_print ("In schedule_callbacks:\n"
3822 " interface = '%s'\n"
3833 /* TODO: if this is slow, then we can change signal_data_array into
3834 * map_object_path_to_signal_data_array or something.
3836 for (n = 0; n < signal_data_array->len; n++)
3838 SignalData *signal_data = signal_data_array->pdata[n];
3840 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3843 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3846 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3849 if (signal_data->arg0 != NULL)
3854 if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3856 if (!namespace_rule_matches (signal_data->arg0, arg0))
3859 else if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3861 if (!path_rule_matches (signal_data->arg0, arg0))
3864 else if (!g_str_equal (signal_data->arg0, arg0))
3868 for (m = 0; m < signal_data->subscribers->len; m++)
3870 SignalSubscriber *subscriber;
3871 GSource *idle_source;
3872 SignalInstance *signal_instance;
3874 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3876 signal_instance = g_new0 (SignalInstance, 1);
3877 signal_instance->subscription_id = subscriber->id;
3878 signal_instance->callback = subscriber->callback;
3879 signal_instance->user_data = subscriber->user_data;
3880 signal_instance->message = g_object_ref (message);
3881 signal_instance->connection = g_object_ref (connection);
3882 signal_instance->sender = sender;
3883 signal_instance->path = path;
3884 signal_instance->interface = interface;
3885 signal_instance->member = member;
3887 idle_source = g_idle_source_new ();
3888 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3889 g_source_set_callback (idle_source,
3890 emit_signal_instance_in_idle_cb,
3892 (GDestroyNotify) signal_instance_free);
3893 g_source_attach (idle_source, subscriber->context);
3894 g_source_unref (idle_source);
3899 /* called in GDBusWorker thread with lock held */
3901 distribute_signals (GDBusConnection *connection,
3902 GDBusMessage *message)
3904 GPtrArray *signal_data_array;
3905 const gchar *sender;
3907 sender = g_dbus_message_get_sender (message);
3909 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3911 _g_dbus_debug_print_lock ();
3912 g_print ("========================================================================\n"
3913 "GDBus-debug:Signal:\n"
3914 " <<<< RECEIVED SIGNAL %s.%s\n"
3916 " sent by name %s\n",
3917 g_dbus_message_get_interface (message),
3918 g_dbus_message_get_member (message),
3919 g_dbus_message_get_path (message),
3920 sender != NULL ? sender : "(none)");
3921 _g_dbus_debug_print_unlock ();
3924 /* collect subscribers that match on sender */
3927 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3928 if (signal_data_array != NULL)
3929 schedule_callbacks (connection, signal_data_array, message, sender);
3932 /* collect subscribers not matching on sender */
3933 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3934 if (signal_data_array != NULL)
3935 schedule_callbacks (connection, signal_data_array, message, sender);
3938 /* ---------------------------------------------------------------------------------------------------- */
3940 /* only called from finalize(), removes all subscriptions */
3942 purge_all_signal_subscriptions (GDBusConnection *connection)
3944 GHashTableIter iter;
3947 GArray *subscribers;
3950 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3951 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3952 while (g_hash_table_iter_next (&iter, &key, NULL))
3954 guint subscription_id = GPOINTER_TO_UINT (key);
3955 g_array_append_val (ids, subscription_id);
3958 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3959 for (n = 0; n < ids->len; n++)
3961 guint subscription_id = g_array_index (ids, guint, n);
3962 unsubscribe_id_internal (connection,
3966 g_array_free (ids, TRUE);
3968 /* call GDestroyNotify without lock held */
3969 for (n = 0; n < subscribers->len; n++)
3971 SignalSubscriber *subscriber;
3972 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3973 call_destroy_notify (subscriber->context,
3974 subscriber->user_data_free_func,
3975 subscriber->user_data);
3976 g_main_context_unref (subscriber->context);
3979 g_array_free (subscribers, TRUE);
3982 /* ---------------------------------------------------------------------------------------------------- */
3984 static GDBusInterfaceVTable *
3985 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3987 /* Don't waste memory by copying padding - remember to update this
3988 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3990 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3994 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
3999 /* ---------------------------------------------------------------------------------------------------- */
4001 static GDBusSubtreeVTable *
4002 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
4004 /* Don't waste memory by copying padding - remember to update this
4005 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
4007 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4011 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
4016 /* ---------------------------------------------------------------------------------------------------- */
4018 struct ExportedObject
4021 GDBusConnection *connection;
4023 /* maps gchar* -> ExportedInterface* */
4024 GHashTable *map_if_name_to_ei;
4027 /* only called with lock held */
4029 exported_object_free (ExportedObject *eo)
4031 g_free (eo->object_path);
4032 g_hash_table_unref (eo->map_if_name_to_ei);
4041 gchar *interface_name;
4042 GDBusInterfaceVTable *vtable;
4043 GDBusInterfaceInfo *interface_info;
4045 GMainContext *context;
4047 GDestroyNotify user_data_free_func;
4048 } ExportedInterface;
4050 /* called with lock held */
4052 exported_interface_free (ExportedInterface *ei)
4054 g_dbus_interface_info_cache_release (ei->interface_info);
4055 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
4057 call_destroy_notify (ei->context,
4058 ei->user_data_free_func,
4061 g_main_context_unref (ei->context);
4063 g_free (ei->interface_name);
4064 _g_dbus_interface_vtable_free (ei->vtable);
4068 /* ---------------------------------------------------------------------------------------------------- */
4070 /* Convenience function to check if @registration_id (if not zero) or
4071 * @subtree_registration_id (if not zero) has been unregistered. If
4072 * so, returns %TRUE.
4074 * May be called by any thread. Caller must *not* hold lock.
4077 has_object_been_unregistered (GDBusConnection *connection,
4078 guint registration_id,
4079 guint subtree_registration_id)
4083 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4087 CONNECTION_LOCK (connection);
4088 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
4089 GUINT_TO_POINTER (registration_id)) == NULL)
4093 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
4094 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
4098 CONNECTION_UNLOCK (connection);
4103 /* ---------------------------------------------------------------------------------------------------- */
4107 GDBusConnection *connection;
4108 GDBusMessage *message;
4110 const gchar *property_name;
4111 const GDBusInterfaceVTable *vtable;
4112 GDBusInterfaceInfo *interface_info;
4113 const GDBusPropertyInfo *property_info;
4114 guint registration_id;
4115 guint subtree_registration_id;
4119 property_data_free (PropertyData *data)
4121 g_object_unref (data->connection);
4122 g_object_unref (data->message);
4126 /* called in thread where object was registered - no locks held */
4128 invoke_get_property_in_idle_cb (gpointer _data)
4130 PropertyData *data = _data;
4133 GDBusMessage *reply;
4135 if (has_object_been_unregistered (data->connection,
4136 data->registration_id,
4137 data->subtree_registration_id))
4139 reply = g_dbus_message_new_method_error (data->message,
4140 "org.freedesktop.DBus.Error.UnknownMethod",
4141 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4142 g_dbus_message_get_path (data->message));
4143 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4144 g_object_unref (reply);
4149 value = data->vtable->get_property (data->connection,
4150 g_dbus_message_get_sender (data->message),
4151 g_dbus_message_get_path (data->message),
4152 data->interface_info->name,
4153 data->property_name,
4160 g_assert_no_error (error);
4162 g_variant_take_ref (value);
4163 reply = g_dbus_message_new_method_reply (data->message);
4164 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4165 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4166 g_variant_unref (value);
4167 g_object_unref (reply);
4171 gchar *dbus_error_name;
4172 g_assert (error != NULL);
4173 dbus_error_name = g_dbus_error_encode_gerror (error);
4174 reply = g_dbus_message_new_method_error_literal (data->message,
4177 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4178 g_free (dbus_error_name);
4179 g_error_free (error);
4180 g_object_unref (reply);
4187 /* called in thread where object was registered - no locks held */
4189 invoke_set_property_in_idle_cb (gpointer _data)
4191 PropertyData *data = _data;
4193 GDBusMessage *reply;
4199 g_variant_get (g_dbus_message_get_body (data->message),
4205 if (!data->vtable->set_property (data->connection,
4206 g_dbus_message_get_sender (data->message),
4207 g_dbus_message_get_path (data->message),
4208 data->interface_info->name,
4209 data->property_name,
4214 gchar *dbus_error_name;
4215 g_assert (error != NULL);
4216 dbus_error_name = g_dbus_error_encode_gerror (error);
4217 reply = g_dbus_message_new_method_error_literal (data->message,
4220 g_free (dbus_error_name);
4221 g_error_free (error);
4225 reply = g_dbus_message_new_method_reply (data->message);
4228 g_assert (reply != NULL);
4229 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4230 g_object_unref (reply);
4231 g_variant_unref (value);
4236 /* called in any thread with connection's lock held */
4238 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4239 GDBusMessage *message,
4240 guint registration_id,
4241 guint subtree_registration_id,
4243 GDBusInterfaceInfo *interface_info,
4244 const GDBusInterfaceVTable *vtable,
4245 GMainContext *main_context,
4249 const char *interface_name;
4250 const char *property_name;
4251 const GDBusPropertyInfo *property_info;
4252 GSource *idle_source;
4253 PropertyData *property_data;
4254 GDBusMessage *reply;
4259 g_variant_get (g_dbus_message_get_body (message),
4264 g_variant_get (g_dbus_message_get_body (message),
4273 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4275 property_info = NULL;
4277 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4278 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4279 if (property_info == NULL)
4281 reply = g_dbus_message_new_method_error (message,
4282 "org.freedesktop.DBus.Error.InvalidArgs",
4283 _("No such property '%s'"),
4285 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4286 g_object_unref (reply);
4291 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4293 reply = g_dbus_message_new_method_error (message,
4294 "org.freedesktop.DBus.Error.InvalidArgs",
4295 _("Property '%s' is not readable"),
4297 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4298 g_object_unref (reply);
4302 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4304 reply = g_dbus_message_new_method_error (message,
4305 "org.freedesktop.DBus.Error.InvalidArgs",
4306 _("Property '%s' is not writable"),
4308 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4309 g_object_unref (reply);
4318 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4319 * of the given value is wrong
4321 g_variant_get_child (g_dbus_message_get_body (message), 2, "v", &value);
4322 if (g_strcmp0 (g_variant_get_type_string (value), property_info->signature) != 0)
4324 reply = g_dbus_message_new_method_error (message,
4325 "org.freedesktop.DBus.Error.InvalidArgs",
4326 _("Error setting property '%s': Expected type '%s' but got '%s'"),
4327 property_name, property_info->signature,
4328 g_variant_get_type_string (value));
4329 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4330 g_variant_unref (value);
4331 g_object_unref (reply);
4336 g_variant_unref (value);
4339 /* If the vtable pointer for get_property() resp. set_property() is
4340 * NULL then dispatch the call via the method_call() handler.
4344 if (vtable->get_property == NULL)
4346 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4347 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4348 vtable, main_context, user_data);
4355 if (vtable->set_property == NULL)
4357 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4358 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4359 vtable, main_context, user_data);
4365 /* ok, got the property info - call user code in an idle handler */
4366 property_data = g_new0 (PropertyData, 1);
4367 property_data->connection = g_object_ref (connection);
4368 property_data->message = g_object_ref (message);
4369 property_data->user_data = user_data;
4370 property_data->property_name = property_name;
4371 property_data->vtable = vtable;
4372 property_data->interface_info = interface_info;
4373 property_data->property_info = property_info;
4374 property_data->registration_id = registration_id;
4375 property_data->subtree_registration_id = subtree_registration_id;
4377 idle_source = g_idle_source_new ();
4378 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4379 g_source_set_callback (idle_source,
4380 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4382 (GDestroyNotify) property_data_free);
4383 g_source_attach (idle_source, main_context);
4384 g_source_unref (idle_source);
4392 /* called in GDBusWorker thread with connection's lock held */
4394 handle_getset_property (GDBusConnection *connection,
4396 GDBusMessage *message,
4399 ExportedInterface *ei;
4401 const char *interface_name;
4402 const char *property_name;
4407 g_variant_get (g_dbus_message_get_body (message),
4412 g_variant_get (g_dbus_message_get_body (message),
4418 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4419 * no such interface registered
4421 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4424 GDBusMessage *reply;
4425 reply = g_dbus_message_new_method_error (message,
4426 "org.freedesktop.DBus.Error.InvalidArgs",
4427 _("No such interface '%s'"),
4429 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4430 g_object_unref (reply);
4435 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4448 /* ---------------------------------------------------------------------------------------------------- */
4452 GDBusConnection *connection;
4453 GDBusMessage *message;
4455 const GDBusInterfaceVTable *vtable;
4456 GDBusInterfaceInfo *interface_info;
4457 guint registration_id;
4458 guint subtree_registration_id;
4459 } PropertyGetAllData;
4462 property_get_all_data_free (PropertyData *data)
4464 g_object_unref (data->connection);
4465 g_object_unref (data->message);
4469 /* called in thread where object was registered - no locks held */
4471 invoke_get_all_properties_in_idle_cb (gpointer _data)
4473 PropertyGetAllData *data = _data;
4474 GVariantBuilder builder;
4475 GDBusMessage *reply;
4478 if (has_object_been_unregistered (data->connection,
4479 data->registration_id,
4480 data->subtree_registration_id))
4482 reply = g_dbus_message_new_method_error (data->message,
4483 "org.freedesktop.DBus.Error.UnknownMethod",
4484 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4485 g_dbus_message_get_path (data->message));
4486 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4487 g_object_unref (reply);
4491 /* TODO: Right now we never fail this call - we just omit values if
4492 * a get_property() call is failing.
4494 * We could fail the whole call if just a single get_property() call
4495 * returns an error. We need clarification in the D-Bus spec about this.
4497 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4498 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4499 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4501 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4504 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4507 value = data->vtable->get_property (data->connection,
4508 g_dbus_message_get_sender (data->message),
4509 g_dbus_message_get_path (data->message),
4510 data->interface_info->name,
4511 property_info->name,
4518 g_variant_take_ref (value);
4519 g_variant_builder_add (&builder,
4521 property_info->name,
4523 g_variant_unref (value);
4525 g_variant_builder_close (&builder);
4527 reply = g_dbus_message_new_method_reply (data->message);
4528 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4529 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4530 g_object_unref (reply);
4537 interface_has_readable_properties (GDBusInterfaceInfo *interface_info)
4541 if (!interface_info->properties)
4544 for (i = 0; interface_info->properties[i]; i++)
4545 if (interface_info->properties[i]->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE)
4551 /* called in any thread with connection's lock held */
4553 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4554 GDBusMessage *message,
4555 guint registration_id,
4556 guint subtree_registration_id,
4557 GDBusInterfaceInfo *interface_info,
4558 const GDBusInterfaceVTable *vtable,
4559 GMainContext *main_context,
4563 GSource *idle_source;
4564 PropertyGetAllData *property_get_all_data;
4571 /* If the vtable pointer for get_property() is NULL but we have a
4572 * non-zero number of readable properties, then dispatch the call via
4573 * the method_call() handler.
4575 if (vtable->get_property == NULL && interface_has_readable_properties (interface_info))
4577 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4578 interface_info, NULL, NULL, g_dbus_message_get_body (message),
4579 vtable, main_context, user_data);
4584 /* ok, got the property info - call user in an idle handler */
4585 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4586 property_get_all_data->connection = g_object_ref (connection);
4587 property_get_all_data->message = g_object_ref (message);
4588 property_get_all_data->user_data = user_data;
4589 property_get_all_data->vtable = vtable;
4590 property_get_all_data->interface_info = interface_info;
4591 property_get_all_data->registration_id = registration_id;
4592 property_get_all_data->subtree_registration_id = subtree_registration_id;
4594 idle_source = g_idle_source_new ();
4595 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4596 g_source_set_callback (idle_source,
4597 invoke_get_all_properties_in_idle_cb,
4598 property_get_all_data,
4599 (GDestroyNotify) property_get_all_data_free);
4600 g_source_attach (idle_source, main_context);
4601 g_source_unref (idle_source);
4609 /* called in GDBusWorker thread with connection's lock held */
4611 handle_get_all_properties (GDBusConnection *connection,
4613 GDBusMessage *message)
4615 ExportedInterface *ei;
4617 const char *interface_name;
4621 g_variant_get (g_dbus_message_get_body (message),
4625 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4626 * no such interface registered
4628 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4631 GDBusMessage *reply;
4632 reply = g_dbus_message_new_method_error (message,
4633 "org.freedesktop.DBus.Error.InvalidArgs",
4634 _("No such interface"),
4636 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4637 g_object_unref (reply);
4642 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4654 /* ---------------------------------------------------------------------------------------------------- */
4656 static const gchar introspect_header[] =
4657 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4658 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4659 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4662 static const gchar introspect_tail[] =
4665 static const gchar introspect_properties_interface[] =
4666 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4667 " <method name=\"Get\">\n"
4668 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4669 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4670 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4672 " <method name=\"GetAll\">\n"
4673 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4674 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4676 " <method name=\"Set\">\n"
4677 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4678 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4679 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4681 " <signal name=\"PropertiesChanged\">\n"
4682 " <arg type=\"s\" name=\"interface_name\"/>\n"
4683 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4684 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4688 static const gchar introspect_introspectable_interface[] =
4689 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4690 " <method name=\"Introspect\">\n"
4691 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4694 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4695 " <method name=\"Ping\"/>\n"
4696 " <method name=\"GetMachineId\">\n"
4697 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4702 introspect_append_header (GString *s)
4704 g_string_append (s, introspect_header);
4708 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4710 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4716 begin = object_path + path_len;
4717 end = strchr (begin, '/');
4719 s = g_strndup (begin, end - begin);
4721 s = g_strdup (begin);
4723 if (g_hash_table_lookup (set, s) == NULL)
4724 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
4730 /* TODO: we want a nicer public interface for this */
4731 /* called in any thread with connection's lock held */
4733 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4738 GHashTableIter hash_iter;
4739 const gchar *object_path;
4745 CONNECTION_ENSURE_LOCK (connection);
4747 path_len = strlen (path);
4751 set = g_hash_table_new (g_str_hash, g_str_equal);
4753 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4754 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4755 maybe_add_path (path, path_len, object_path, set);
4757 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4758 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4759 maybe_add_path (path, path_len, object_path, set);
4761 p = g_ptr_array_new ();
4762 keys = g_hash_table_get_keys (set);
4763 for (l = keys; l != NULL; l = l->next)
4764 g_ptr_array_add (p, l->data);
4765 g_hash_table_unref (set);
4768 g_ptr_array_add (p, NULL);
4769 ret = (gchar **) g_ptr_array_free (p, FALSE);
4773 /* called in any thread with connection's lock not held */
4775 g_dbus_connection_list_registered (GDBusConnection *connection,
4779 CONNECTION_LOCK (connection);
4780 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4781 CONNECTION_UNLOCK (connection);
4785 /* called in GDBusWorker thread with connection's lock held */
4787 handle_introspect (GDBusConnection *connection,
4789 GDBusMessage *message)
4793 GDBusMessage *reply;
4794 GHashTableIter hash_iter;
4795 ExportedInterface *ei;
4798 /* first the header with the standard interfaces */
4799 s = g_string_sized_new (sizeof (introspect_header) +
4800 sizeof (introspect_properties_interface) +
4801 sizeof (introspect_introspectable_interface) +
4802 sizeof (introspect_tail));
4803 introspect_append_header (s);
4804 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4805 "org.freedesktop.DBus.Properties"))
4806 g_string_append (s, introspect_properties_interface);
4808 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4809 "org.freedesktop.DBus.Introspectable"))
4810 g_string_append (s, introspect_introspectable_interface);
4812 /* then include the registered interfaces */
4813 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4814 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4815 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4817 /* finally include nodes registered below us */
4818 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4819 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4820 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4821 g_strfreev (registered);
4822 g_string_append (s, introspect_tail);
4824 reply = g_dbus_message_new_method_reply (message);
4825 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4826 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4827 g_object_unref (reply);
4828 g_string_free (s, TRUE);
4833 /* called in thread where object was registered - no locks held */
4835 call_in_idle_cb (gpointer user_data)
4837 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4838 GDBusInterfaceVTable *vtable;
4839 guint registration_id;
4840 guint subtree_registration_id;
4842 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4843 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4845 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4847 subtree_registration_id))
4849 GDBusMessage *reply;
4850 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4851 "org.freedesktop.DBus.Error.UnknownMethod",
4852 _("No such interface '%s' on object at path %s"),
4853 g_dbus_method_invocation_get_interface_name (invocation),
4854 g_dbus_method_invocation_get_object_path (invocation));
4855 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4856 g_object_unref (reply);
4860 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4861 g_assert (vtable != NULL && vtable->method_call != NULL);
4863 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4864 g_dbus_method_invocation_get_sender (invocation),
4865 g_dbus_method_invocation_get_object_path (invocation),
4866 g_dbus_method_invocation_get_interface_name (invocation),
4867 g_dbus_method_invocation_get_method_name (invocation),
4868 g_dbus_method_invocation_get_parameters (invocation),
4869 g_object_ref (invocation),
4870 g_dbus_method_invocation_get_user_data (invocation));
4876 /* called in GDBusWorker thread with connection's lock held */
4878 schedule_method_call (GDBusConnection *connection,
4879 GDBusMessage *message,
4880 guint registration_id,
4881 guint subtree_registration_id,
4882 const GDBusInterfaceInfo *interface_info,
4883 const GDBusMethodInfo *method_info,
4884 const GDBusPropertyInfo *property_info,
4885 GVariant *parameters,
4886 const GDBusInterfaceVTable *vtable,
4887 GMainContext *main_context,
4890 GDBusMethodInvocation *invocation;
4891 GSource *idle_source;
4893 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4894 g_dbus_message_get_path (message),
4895 g_dbus_message_get_interface (message),
4896 g_dbus_message_get_member (message),
4904 /* TODO: would be nicer with a real MethodData like we already
4905 * have PropertyData and PropertyGetAllData... */
4906 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4907 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4908 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4910 idle_source = g_idle_source_new ();
4911 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4912 g_source_set_callback (idle_source,
4916 g_source_attach (idle_source, main_context);
4917 g_source_unref (idle_source);
4920 /* called in GDBusWorker thread with connection's lock held */
4922 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4923 GDBusMessage *message,
4924 guint registration_id,
4925 guint subtree_registration_id,
4926 GDBusInterfaceInfo *interface_info,
4927 const GDBusInterfaceVTable *vtable,
4928 GMainContext *main_context,
4931 GDBusMethodInfo *method_info;
4932 GDBusMessage *reply;
4933 GVariant *parameters;
4935 GVariantType *in_type;
4939 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4940 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4942 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4943 * error to the caller
4945 if (method_info == NULL)
4947 reply = g_dbus_message_new_method_error (message,
4948 "org.freedesktop.DBus.Error.UnknownMethod",
4949 _("No such method '%s'"),
4950 g_dbus_message_get_member (message));
4951 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4952 g_object_unref (reply);
4957 parameters = g_dbus_message_get_body (message);
4958 if (parameters == NULL)
4960 parameters = g_variant_new ("()");
4961 g_variant_ref_sink (parameters);
4965 g_variant_ref (parameters);
4968 /* Check that the incoming args are of the right type - if they are not, return
4969 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4971 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4972 if (!g_variant_is_of_type (parameters, in_type))
4976 type_string = g_variant_type_dup_string (in_type);
4978 reply = g_dbus_message_new_method_error (message,
4979 "org.freedesktop.DBus.Error.InvalidArgs",
4980 _("Type of message, '%s', does not match expected type '%s'"),
4981 g_variant_get_type_string (parameters),
4983 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4984 g_variant_type_free (in_type);
4985 g_variant_unref (parameters);
4986 g_object_unref (reply);
4987 g_free (type_string);
4991 g_variant_type_free (in_type);
4993 /* schedule the call in idle */
4994 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4995 interface_info, method_info, NULL, parameters,
4996 vtable, main_context, user_data);
4997 g_variant_unref (parameters);
5004 /* ---------------------------------------------------------------------------------------------------- */
5006 /* called in GDBusWorker thread with connection's lock held */
5008 obj_message_func (GDBusConnection *connection,
5010 GDBusMessage *message)
5012 const gchar *interface_name;
5013 const gchar *member;
5014 const gchar *signature;
5019 interface_name = g_dbus_message_get_interface (message);
5020 member = g_dbus_message_get_member (message);
5021 signature = g_dbus_message_get_signature (message);
5023 /* see if we have an interface for handling this call */
5024 if (interface_name != NULL)
5026 ExportedInterface *ei;
5027 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5030 /* we do - invoke the handler in idle in the right thread */
5032 /* handle no vtable or handler being present */
5033 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
5036 handled = validate_and_maybe_schedule_method_call (connection,
5048 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5049 g_strcmp0 (member, "Introspect") == 0 &&
5050 g_strcmp0 (signature, "") == 0)
5052 handled = handle_introspect (connection, eo, message);
5055 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5056 g_strcmp0 (member, "Get") == 0 &&
5057 g_strcmp0 (signature, "ss") == 0)
5059 handled = handle_getset_property (connection, eo, message, TRUE);
5062 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5063 g_strcmp0 (member, "Set") == 0 &&
5064 g_strcmp0 (signature, "ssv") == 0)
5066 handled = handle_getset_property (connection, eo, message, FALSE);
5069 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5070 g_strcmp0 (member, "GetAll") == 0 &&
5071 g_strcmp0 (signature, "s") == 0)
5073 handled = handle_get_all_properties (connection, eo, message);
5082 * g_dbus_connection_register_object:
5083 * @connection: a #GDBusConnection
5084 * @object_path: the object path to register at
5085 * @interface_info: introspection data for the interface
5086 * @vtable: (allow-none): a #GDBusInterfaceVTable to call into or %NULL
5087 * @user_data: (allow-none): data to pass to functions in @vtable
5088 * @user_data_free_func: function to call when the object path is unregistered
5089 * @error: return location for error or %NULL
5091 * Registers callbacks for exported objects at @object_path with the
5092 * D-Bus interface that is described in @interface_info.
5094 * Calls to functions in @vtable (and @user_data_free_func) will
5095 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
5096 * loop</link> of the thread you are calling this method from.
5098 * Note that all #GVariant values passed to functions in @vtable will match
5099 * the signature given in @interface_info - if a remote caller passes
5100 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
5101 * is returned to the remote caller.
5103 * Additionally, if the remote caller attempts to invoke methods or
5104 * access properties not mentioned in @interface_info the
5105 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
5106 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
5107 * are returned to the caller.
5109 * It is considered a programming error if the
5110 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
5111 * #GVariant of incorrect type.
5113 * If an existing callback is already registered at @object_path and
5114 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
5116 * GDBus automatically implements the standard D-Bus interfaces
5117 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
5118 * and org.freedesktop.Peer, so you don't have to implement those for the
5119 * objects you export. You can implement org.freedesktop.DBus.Properties
5120 * yourself, e.g. to handle getting and setting of properties asynchronously.
5122 * Note that the reference count on @interface_info will be
5123 * incremented by 1 (unless allocated statically, e.g. if the
5124 * reference count is -1, see g_dbus_interface_info_ref()) for as long
5125 * as the object is exported. Also note that @vtable will be copied.
5127 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
5129 * Returns: 0 if @error is set, otherwise a registration id (never 0)
5130 * that can be used with g_dbus_connection_unregister_object()
5135 g_dbus_connection_register_object (GDBusConnection *connection,
5136 const gchar *object_path,
5137 GDBusInterfaceInfo *interface_info,
5138 const GDBusInterfaceVTable *vtable,
5140 GDestroyNotify user_data_free_func,
5144 ExportedInterface *ei;
5147 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5148 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5149 g_return_val_if_fail (interface_info != NULL, 0);
5150 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
5151 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5152 g_return_val_if_fail (check_initialized (connection), 0);
5156 CONNECTION_LOCK (connection);
5158 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5161 eo = g_new0 (ExportedObject, 1);
5162 eo->object_path = g_strdup (object_path);
5163 eo->connection = connection;
5164 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
5167 (GDestroyNotify) exported_interface_free);
5168 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
5171 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
5177 _("An object is already exported for the interface %s at %s"),
5178 interface_info->name,
5183 ei = g_new0 (ExportedInterface, 1);
5184 ei->id = _global_registration_id++; /* TODO: overflow etc. */
5186 ei->user_data = user_data;
5187 ei->user_data_free_func = user_data_free_func;
5188 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
5189 ei->interface_info = g_dbus_interface_info_ref (interface_info);
5190 g_dbus_interface_info_cache_build (ei->interface_info);
5191 ei->interface_name = g_strdup (interface_info->name);
5192 ei->context = g_main_context_ref_thread_default ();
5194 g_hash_table_insert (eo->map_if_name_to_ei,
5195 (gpointer) ei->interface_name,
5197 g_hash_table_insert (connection->map_id_to_ei,
5198 GUINT_TO_POINTER (ei->id),
5204 CONNECTION_UNLOCK (connection);
5210 * g_dbus_connection_unregister_object:
5211 * @connection: a #GDBusConnection
5212 * @registration_id: a registration id obtained from
5213 * g_dbus_connection_register_object()
5215 * Unregisters an object.
5217 * Returns: %TRUE if the object was unregistered, %FALSE otherwise
5222 g_dbus_connection_unregister_object (GDBusConnection *connection,
5223 guint registration_id)
5225 ExportedInterface *ei;
5229 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5230 g_return_val_if_fail (check_initialized (connection), FALSE);
5234 CONNECTION_LOCK (connection);
5236 ei = g_hash_table_lookup (connection->map_id_to_ei,
5237 GUINT_TO_POINTER (registration_id));
5243 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5244 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5245 /* unregister object path if we have no more exported interfaces */
5246 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5247 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5253 CONNECTION_UNLOCK (connection);
5258 /* ---------------------------------------------------------------------------------------------------- */
5261 * g_dbus_connection_emit_signal:
5262 * @connection: a #GDBusConnection
5263 * @destination_bus_name: (allow-none): the unique bus name for the destination
5264 * for the signal or %NULL to emit to all listeners
5265 * @object_path: path of remote object
5266 * @interface_name: D-Bus interface to emit a signal on
5267 * @signal_name: the name of the signal to emit
5268 * @parameters: (allow-none): a #GVariant tuple with parameters for the signal
5269 * or %NULL if not passing parameters
5270 * @error: Return location for error or %NULL
5274 * If the parameters GVariant is floating, it is consumed.
5276 * This can only fail if @parameters is not compatible with the D-Bus protocol.
5278 * Returns: %TRUE unless @error is set
5283 g_dbus_connection_emit_signal (GDBusConnection *connection,
5284 const gchar *destination_bus_name,
5285 const gchar *object_path,
5286 const gchar *interface_name,
5287 const gchar *signal_name,
5288 GVariant *parameters,
5291 GDBusMessage *message;
5297 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5298 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5299 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5300 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5301 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5302 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5303 g_return_val_if_fail (check_initialized (connection), FALSE);
5305 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5307 _g_dbus_debug_print_lock ();
5308 g_print ("========================================================================\n"
5309 "GDBus-debug:Emission:\n"
5310 " >>>> SIGNAL EMISSION %s.%s()\n"
5312 " destination %s\n",
5313 interface_name, signal_name,
5315 destination_bus_name != NULL ? destination_bus_name : "(none)");
5316 _g_dbus_debug_print_unlock ();
5319 message = g_dbus_message_new_signal (object_path,
5323 if (destination_bus_name != NULL)
5324 g_dbus_message_set_header (message,
5325 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5326 g_variant_new_string (destination_bus_name));
5328 if (parameters != NULL)
5329 g_dbus_message_set_body (message, parameters);
5331 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5332 g_object_unref (message);
5338 add_call_flags (GDBusMessage *message,
5339 GDBusCallFlags flags)
5341 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5342 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
5346 decode_method_reply (GDBusMessage *reply,
5347 const gchar *method_name,
5348 const GVariantType *reply_type,
5349 GUnixFDList **out_fd_list,
5355 switch (g_dbus_message_get_message_type (reply))
5357 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5358 result = g_dbus_message_get_body (reply);
5361 result = g_variant_new ("()");
5362 g_variant_ref_sink (result);
5366 g_variant_ref (result);
5369 if (!g_variant_is_of_type (result, reply_type))
5371 gchar *type_string = g_variant_type_dup_string (reply_type);
5375 G_IO_ERROR_INVALID_ARGUMENT,
5376 _("Method '%s' returned type '%s', but expected '%s'"),
5377 method_name, g_variant_get_type_string (result), type_string);
5379 g_variant_unref (result);
5380 g_free (type_string);
5387 if (out_fd_list != NULL)
5389 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5390 if (*out_fd_list != NULL)
5391 g_object_ref (*out_fd_list);
5397 case G_DBUS_MESSAGE_TYPE_ERROR:
5398 g_dbus_message_to_gerror (reply, error);
5402 g_assert_not_reached ();
5412 GSimpleAsyncResult *simple;
5413 GVariantType *reply_type;
5414 gchar *method_name; /* for error message */
5418 GUnixFDList *fd_list;
5422 call_state_free (CallState *state)
5424 g_variant_type_free (state->reply_type);
5425 g_free (state->method_name);
5427 if (state->value != NULL)
5428 g_variant_unref (state->value);
5429 if (state->fd_list != NULL)
5430 g_object_unref (state->fd_list);
5431 g_slice_free (CallState, state);
5434 /* called in any thread, with the connection's lock not held */
5436 g_dbus_connection_call_done (GObject *source,
5437 GAsyncResult *result,
5440 GSimpleAsyncResult *simple;
5441 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5442 CallState *state = user_data;
5444 GDBusMessage *reply;
5447 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5451 if (G_UNLIKELY (_g_dbus_debug_call ()))
5453 _g_dbus_debug_print_lock ();
5454 g_print ("========================================================================\n"
5455 "GDBus-debug:Call:\n"
5456 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5462 g_print ("SUCCESS\n");
5466 g_print ("FAILED: %s\n",
5469 _g_dbus_debug_print_unlock ();
5473 state->value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5475 simple = state->simple; /* why? because state is freed before we unref simple.. */
5478 g_simple_async_result_take_error (state->simple, error);
5479 g_simple_async_result_complete (state->simple);
5480 call_state_free (state);
5484 g_simple_async_result_set_op_res_gpointer (state->simple, state, (GDestroyNotify) call_state_free);
5485 g_simple_async_result_complete (state->simple);
5487 g_clear_object (&reply);
5488 g_object_unref (simple);
5491 /* called in any thread, with the connection's lock not held */
5493 g_dbus_connection_call_internal (GDBusConnection *connection,
5494 const gchar *bus_name,
5495 const gchar *object_path,
5496 const gchar *interface_name,
5497 const gchar *method_name,
5498 GVariant *parameters,
5499 const GVariantType *reply_type,
5500 GDBusCallFlags flags,
5502 GUnixFDList *fd_list,
5503 GCancellable *cancellable,
5504 GAsyncReadyCallback callback,
5507 GDBusMessage *message;
5510 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5511 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5512 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5513 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5514 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5515 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5516 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5517 g_return_if_fail (check_initialized (connection));
5519 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5521 g_return_if_fail (fd_list == NULL);
5524 message = g_dbus_message_new_method_call (bus_name,
5528 add_call_flags (message, flags);
5529 if (parameters != NULL)
5530 g_dbus_message_set_body (message, parameters);
5533 if (fd_list != NULL)
5534 g_dbus_message_set_unix_fd_list (message, fd_list);
5537 /* If the user has no callback then we can just send the message with
5538 * the G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set and skip all
5539 * the logic for processing the reply. If the service sends the reply
5540 * anyway then it will just be ignored.
5542 if (callback != NULL)
5546 state = g_slice_new0 (CallState);
5547 state->simple = g_simple_async_result_new (G_OBJECT (connection),
5548 callback, user_data,
5549 g_dbus_connection_call_internal);
5550 g_simple_async_result_set_check_cancellable (state->simple, cancellable);
5551 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5553 if (reply_type == NULL)
5554 reply_type = G_VARIANT_TYPE_ANY;
5556 state->reply_type = g_variant_type_copy (reply_type);
5558 g_dbus_connection_send_message_with_reply (connection,
5560 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5564 g_dbus_connection_call_done,
5566 serial = state->serial;
5570 GDBusMessageFlags flags;
5572 flags = g_dbus_message_get_flags (message);
5573 flags |= G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
5574 g_dbus_message_set_flags (message, flags);
5576 g_dbus_connection_send_message (connection,
5578 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5582 if (G_UNLIKELY (_g_dbus_debug_call ()))
5584 _g_dbus_debug_print_lock ();
5585 g_print ("========================================================================\n"
5586 "GDBus-debug:Call:\n"
5587 " >>>> ASYNC %s.%s()\n"
5589 " owned by name %s (serial %d)\n",
5593 bus_name != NULL ? bus_name : "(none)",
5595 _g_dbus_debug_print_unlock ();
5598 if (message != NULL)
5599 g_object_unref (message);
5602 /* called in any thread, with the connection's lock not held */
5604 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
5605 GUnixFDList **out_fd_list,
5609 GSimpleAsyncResult *simple;
5612 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5613 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
5614 g_dbus_connection_call_internal), NULL);
5615 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5617 simple = G_SIMPLE_ASYNC_RESULT (res);
5619 if (g_simple_async_result_propagate_error (simple, error))
5622 state = g_simple_async_result_get_op_res_gpointer (simple);
5623 if (out_fd_list != NULL)
5624 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
5625 return g_variant_ref (state->value);
5628 /* called in any user thread, with the connection's lock not held */
5630 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
5631 const gchar *bus_name,
5632 const gchar *object_path,
5633 const gchar *interface_name,
5634 const gchar *method_name,
5635 GVariant *parameters,
5636 const GVariantType *reply_type,
5637 GDBusCallFlags flags,
5639 GUnixFDList *fd_list,
5640 GUnixFDList **out_fd_list,
5641 GCancellable *cancellable,
5644 GDBusMessage *message;
5645 GDBusMessage *reply;
5647 GError *local_error;
5648 GDBusSendMessageFlags send_flags;
5654 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5655 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5656 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5657 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5658 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5659 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5660 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5662 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
5664 g_return_val_if_fail (fd_list == NULL, NULL);
5666 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5668 if (!(flags & CALL_FLAGS_INITIALIZING))
5669 g_return_val_if_fail (check_initialized (connection), FALSE);
5671 if (reply_type == NULL)
5672 reply_type = G_VARIANT_TYPE_ANY;
5674 message = g_dbus_message_new_method_call (bus_name,
5678 add_call_flags (message, flags);
5679 if (parameters != NULL)
5680 g_dbus_message_set_body (message, parameters);
5683 if (fd_list != NULL)
5684 g_dbus_message_set_unix_fd_list (message, fd_list);
5687 if (G_UNLIKELY (_g_dbus_debug_call ()))
5689 _g_dbus_debug_print_lock ();
5690 g_print ("========================================================================\n"
5691 "GDBus-debug:Call:\n"
5692 " >>>> SYNC %s.%s()\n"
5694 " owned by name %s\n",
5698 bus_name != NULL ? bus_name : "(none)");
5699 _g_dbus_debug_print_unlock ();
5704 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
5706 /* translate from one flavour of flags to another... */
5707 if (flags & CALL_FLAGS_INITIALIZING)
5708 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
5710 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5714 NULL, /* volatile guint32 *out_serial */
5718 if (G_UNLIKELY (_g_dbus_debug_call ()))
5720 _g_dbus_debug_print_lock ();
5721 g_print ("========================================================================\n"
5722 "GDBus-debug:Call:\n"
5723 " <<<< SYNC COMPLETE %s.%s()\n"
5729 g_print ("SUCCESS\n");
5733 g_print ("FAILED: %s\n",
5734 local_error->message);
5736 _g_dbus_debug_print_unlock ();
5742 *error = local_error;
5744 g_error_free (local_error);
5748 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
5751 if (message != NULL)
5752 g_object_unref (message);
5754 g_object_unref (reply);
5759 /* ---------------------------------------------------------------------------------------------------- */
5762 * g_dbus_connection_call:
5763 * @connection: a #GDBusConnection
5764 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
5765 * @connection is not a message bus connection
5766 * @object_path: path of remote object
5767 * @interface_name: D-Bus interface to invoke method on
5768 * @method_name: the name of the method to invoke
5769 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
5770 * or %NULL if not passing parameters
5771 * @reply_type: (allow-none): the expected type of the reply, or %NULL
5772 * @flags: flags from the #GDBusCallFlags enumeration
5773 * @timeout_msec: the timeout in milliseconds, -1 to use the default
5774 * timeout or %G_MAXINT for no timeout
5775 * @cancellable: (allow-none): a #GCancellable or %NULL
5776 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request
5777 * is satisfied or %NULL if you don't care about the result of the
5779 * @user_data: the data to pass to @callback
5781 * Asynchronously invokes the @method_name method on the
5782 * @interface_name D-Bus interface on the remote object at
5783 * @object_path owned by @bus_name.
5785 * If @connection is closed then the operation will fail with
5786 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
5787 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
5788 * not compatible with the D-Bus protocol, the operation fails with
5789 * %G_IO_ERROR_INVALID_ARGUMENT.
5791 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
5792 * error will be raised if it does not match. Said another way, if you give a @reply_type
5793 * then any non-%NULL return value will be of this type.
5795 * If the @parameters #GVariant is floating, it is consumed. This allows
5796 * convenient 'inline' use of g_variant_new(), e.g.:
5797 * |[<!-- language="C" -->
5798 * g_dbus_connection_call (connection,
5799 * "org.freedesktop.StringThings",
5800 * "/org/freedesktop/StringThings",
5801 * "org.freedesktop.StringThings",
5803 * g_variant_new ("(ss)",
5807 * G_DBUS_CALL_FLAGS_NONE,
5810 * (GAsyncReadyCallback) two_strings_done,
5814 * This is an asynchronous method. When the operation is finished, @callback will be invoked
5815 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
5816 * of the thread you are calling this method from. You can then call
5817 * g_dbus_connection_call_finish() to get the result of the operation.
5818 * See g_dbus_connection_call_sync() for the synchronous version of this
5821 * If @callback is %NULL then the D-Bus method call message will be sent with
5822 * the %G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set.
5827 g_dbus_connection_call (GDBusConnection *connection,
5828 const gchar *bus_name,
5829 const gchar *object_path,
5830 const gchar *interface_name,
5831 const gchar *method_name,
5832 GVariant *parameters,
5833 const GVariantType *reply_type,
5834 GDBusCallFlags flags,
5836 GCancellable *cancellable,
5837 GAsyncReadyCallback callback,
5840 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);
5844 * g_dbus_connection_call_finish:
5845 * @connection: a #GDBusConnection
5846 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call()
5847 * @error: return location for error or %NULL
5849 * Finishes an operation started with g_dbus_connection_call().
5851 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5852 * return values. Free with g_variant_unref().
5857 g_dbus_connection_call_finish (GDBusConnection *connection,
5861 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
5865 * g_dbus_connection_call_sync:
5866 * @connection: a #GDBusConnection
5867 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
5868 * @connection is not a message bus connection
5869 * @object_path: path of remote object
5870 * @interface_name: D-Bus interface to invoke method on
5871 * @method_name: the name of the method to invoke
5872 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
5873 * or %NULL if not passing parameters
5874 * @reply_type: (allow-none): the expected type of the reply, or %NULL
5875 * @flags: flags from the #GDBusCallFlags enumeration
5876 * @timeout_msec: the timeout in milliseconds, -1 to use the default
5877 * timeout or %G_MAXINT for no timeout
5878 * @cancellable: (allow-none): a #GCancellable or %NULL
5879 * @error: return location for error or %NULL
5881 * Synchronously invokes the @method_name method on the
5882 * @interface_name D-Bus interface on the remote object at
5883 * @object_path owned by @bus_name.
5885 * If @connection is closed then the operation will fail with
5886 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
5887 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
5888 * contains a value not compatible with the D-Bus protocol, the operation
5889 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
5891 * If @reply_type is non-%NULL then the reply will be checked for having
5892 * this type and an error will be raised if it does not match. Said
5893 * another way, if you give a @reply_type then any non-%NULL return
5894 * value will be of this type.
5896 * If the @parameters #GVariant is floating, it is consumed.
5897 * This allows convenient 'inline' use of g_variant_new(), e.g.:
5898 * |[<!-- language="C" -->
5899 * g_dbus_connection_call_sync (connection,
5900 * "org.freedesktop.StringThings",
5901 * "/org/freedesktop/StringThings",
5902 * "org.freedesktop.StringThings",
5904 * g_variant_new ("(ss)",
5908 * G_DBUS_CALL_FLAGS_NONE,
5914 * The calling thread is blocked until a reply is received. See
5915 * g_dbus_connection_call() for the asynchronous version of
5918 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5919 * return values. Free with g_variant_unref().
5924 g_dbus_connection_call_sync (GDBusConnection *connection,
5925 const gchar *bus_name,
5926 const gchar *object_path,
5927 const gchar *interface_name,
5928 const gchar *method_name,
5929 GVariant *parameters,
5930 const GVariantType *reply_type,
5931 GDBusCallFlags flags,
5933 GCancellable *cancellable,
5936 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);
5939 /* ---------------------------------------------------------------------------------------------------- */
5944 * g_dbus_connection_call_with_unix_fd_list:
5945 * @connection: a #GDBusConnection
5946 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
5947 * @connection is not a message bus connection
5948 * @object_path: path of remote object
5949 * @interface_name: D-Bus interface to invoke method on
5950 * @method_name: the name of the method to invoke
5951 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
5952 * or %NULL if not passing parameters
5953 * @reply_type: (allow-none): the expected type of the reply, or %NULL
5954 * @flags: flags from the #GDBusCallFlags enumeration
5955 * @timeout_msec: the timeout in milliseconds, -1 to use the default
5956 * timeout or %G_MAXINT for no timeout
5957 * @fd_list: (allow-none): a #GUnixFDList or %NULL
5958 * @cancellable: (allow-none): a #GCancellable or %NULL
5959 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request is
5960 * satisfied or %NULL if you don't * care about the result of the
5962 * @user_data: The data to pass to @callback.
5964 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
5966 * This method is only available on UNIX.
5971 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
5972 const gchar *bus_name,
5973 const gchar *object_path,
5974 const gchar *interface_name,
5975 const gchar *method_name,
5976 GVariant *parameters,
5977 const GVariantType *reply_type,
5978 GDBusCallFlags flags,
5980 GUnixFDList *fd_list,
5981 GCancellable *cancellable,
5982 GAsyncReadyCallback callback,
5985 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);
5989 * g_dbus_connection_call_with_unix_fd_list_finish:
5990 * @connection: a #GDBusConnection
5991 * @out_fd_list: (out) (allow-none): return location for a #GUnixFDList or %NULL
5992 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
5993 * g_dbus_connection_call_with_unix_fd_list()
5994 * @error: return location for error or %NULL
5996 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
5998 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5999 * return values. Free with g_variant_unref().
6004 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
6005 GUnixFDList **out_fd_list,
6009 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
6013 * g_dbus_connection_call_with_unix_fd_list_sync:
6014 * @connection: a #GDBusConnection
6015 * @bus_name: (allow-none): a unique or well-known bus name or %NULL
6016 * if @connection is not a message bus connection
6017 * @object_path: path of remote object
6018 * @interface_name: D-Bus interface to invoke method on
6019 * @method_name: the name of the method to invoke
6020 * @parameters: (allow-none): a #GVariant tuple with parameters for
6021 * the method or %NULL if not passing parameters
6022 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6023 * @flags: flags from the #GDBusCallFlags enumeration
6024 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6025 * timeout or %G_MAXINT for no timeout
6026 * @fd_list: (allow-none): a #GUnixFDList or %NULL
6027 * @out_fd_list: (out) (allow-none): return location for a #GUnixFDList or %NULL
6028 * @cancellable: (allow-none): a #GCancellable or %NULL
6029 * @error: return location for error or %NULL
6031 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
6033 * This method is only available on UNIX.
6035 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6036 * return values. Free with g_variant_unref().
6041 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
6042 const gchar *bus_name,
6043 const gchar *object_path,
6044 const gchar *interface_name,
6045 const gchar *method_name,
6046 GVariant *parameters,
6047 const GVariantType *reply_type,
6048 GDBusCallFlags flags,
6050 GUnixFDList *fd_list,
6051 GUnixFDList **out_fd_list,
6052 GCancellable *cancellable,
6055 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);
6058 #endif /* G_OS_UNIX */
6060 /* ---------------------------------------------------------------------------------------------------- */
6062 struct ExportedSubtree
6066 GDBusConnection *connection;
6067 GDBusSubtreeVTable *vtable;
6068 GDBusSubtreeFlags flags;
6070 GMainContext *context;
6072 GDestroyNotify user_data_free_func;
6076 exported_subtree_free (ExportedSubtree *es)
6078 call_destroy_notify (es->context,
6079 es->user_data_free_func,
6082 g_main_context_unref (es->context);
6084 _g_dbus_subtree_vtable_free (es->vtable);
6085 g_free (es->object_path);
6089 /* called without lock held in the thread where the caller registered
6093 handle_subtree_introspect (GDBusConnection *connection,
6094 ExportedSubtree *es,
6095 GDBusMessage *message)
6099 GDBusMessage *reply;
6102 const gchar *sender;
6103 const gchar *requested_object_path;
6104 const gchar *requested_node;
6105 GDBusInterfaceInfo **interfaces;
6107 gchar **subnode_paths;
6108 gboolean has_properties_interface;
6109 gboolean has_introspectable_interface;
6113 requested_object_path = g_dbus_message_get_path (message);
6114 sender = g_dbus_message_get_sender (message);
6115 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6117 s = g_string_new (NULL);
6118 introspect_append_header (s);
6120 /* Strictly we don't need the children in dynamic mode, but we avoid the
6121 * conditionals to preserve code clarity
6123 children = es->vtable->enumerate (es->connection,
6130 requested_node = strrchr (requested_object_path, '/') + 1;
6132 /* Assert existence of object if we are not dynamic */
6133 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
6134 !_g_strv_has_string ((const gchar * const *) children, requested_node))
6139 requested_node = NULL;
6142 interfaces = es->vtable->introspect (es->connection,
6147 if (interfaces != NULL)
6149 has_properties_interface = FALSE;
6150 has_introspectable_interface = FALSE;
6152 for (n = 0; interfaces[n] != NULL; n++)
6154 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
6155 has_properties_interface = TRUE;
6156 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
6157 has_introspectable_interface = TRUE;
6159 if (!has_properties_interface)
6160 g_string_append (s, introspect_properties_interface);
6161 if (!has_introspectable_interface)
6162 g_string_append (s, introspect_introspectable_interface);
6164 for (n = 0; interfaces[n] != NULL; n++)
6166 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
6167 g_dbus_interface_info_unref (interfaces[n]);
6169 g_free (interfaces);
6172 /* then include <node> entries from the Subtree for the root */
6175 for (n = 0; children != NULL && children[n] != NULL; n++)
6176 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
6179 /* finally include nodes registered below us */
6180 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
6181 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
6182 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
6183 g_strfreev (subnode_paths);
6185 g_string_append (s, "</node>\n");
6187 reply = g_dbus_message_new_method_reply (message);
6188 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6189 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6190 g_object_unref (reply);
6195 g_string_free (s, TRUE);
6196 g_strfreev (children);
6200 /* called without lock held in the thread where the caller registered
6204 handle_subtree_method_invocation (GDBusConnection *connection,
6205 ExportedSubtree *es,
6206 GDBusMessage *message)
6209 const gchar *sender;
6210 const gchar *interface_name;
6211 const gchar *member;
6212 const gchar *signature;
6213 const gchar *requested_object_path;
6214 const gchar *requested_node;
6216 GDBusInterfaceInfo *interface_info;
6217 const GDBusInterfaceVTable *interface_vtable;
6218 gpointer interface_user_data;
6220 GDBusInterfaceInfo **interfaces;
6221 gboolean is_property_get;
6222 gboolean is_property_set;
6223 gboolean is_property_get_all;
6228 requested_object_path = g_dbus_message_get_path (message);
6229 sender = g_dbus_message_get_sender (message);
6230 interface_name = g_dbus_message_get_interface (message);
6231 member = g_dbus_message_get_member (message);
6232 signature = g_dbus_message_get_signature (message);
6233 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6235 is_property_get = FALSE;
6236 is_property_set = FALSE;
6237 is_property_get_all = FALSE;
6238 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6240 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6241 is_property_get = TRUE;
6242 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6243 is_property_set = TRUE;
6244 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6245 is_property_get_all = TRUE;
6250 requested_node = strrchr (requested_object_path, '/') + 1;
6252 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6254 /* We don't want to dispatch to unenumerated
6255 * nodes, so ensure that the child exists.
6260 children = es->vtable->enumerate (es->connection,
6265 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6266 g_strfreev (children);
6274 requested_node = NULL;
6277 /* get introspection data for the node */
6278 interfaces = es->vtable->introspect (es->connection,
6280 requested_object_path,
6284 if (interfaces == NULL)
6287 interface_info = NULL;
6288 for (n = 0; interfaces[n] != NULL; n++)
6290 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6291 interface_info = interfaces[n];
6294 /* dispatch the call if the user wants to handle it */
6295 if (interface_info != NULL)
6297 /* figure out where to dispatch the method call */
6298 interface_user_data = NULL;
6299 interface_vtable = es->vtable->dispatch (es->connection,
6304 &interface_user_data,
6306 if (interface_vtable == NULL)
6309 CONNECTION_LOCK (connection);
6310 handled = validate_and_maybe_schedule_method_call (es->connection,
6317 interface_user_data);
6318 CONNECTION_UNLOCK (connection);
6320 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6321 else if (is_property_get || is_property_set || is_property_get_all)
6323 if (is_property_get)
6324 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6325 else if (is_property_set)
6326 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6327 else if (is_property_get_all)
6328 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6330 g_assert_not_reached ();
6332 /* see if the object supports this interface at all */
6333 for (n = 0; interfaces[n] != NULL; n++)
6335 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6336 interface_info = interfaces[n];
6339 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6340 * claims it won't support the interface
6342 if (interface_info == NULL)
6344 GDBusMessage *reply;
6345 reply = g_dbus_message_new_method_error (message,
6346 "org.freedesktop.DBus.Error.InvalidArgs",
6347 _("No such interface '%s'"),
6349 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6350 g_object_unref (reply);
6355 /* figure out where to dispatch the property get/set/getall calls */
6356 interface_user_data = NULL;
6357 interface_vtable = es->vtable->dispatch (es->connection,
6362 &interface_user_data,
6364 if (interface_vtable == NULL)
6366 g_warning ("The subtree introspection function indicates that '%s' "
6367 "is a valid interface name, but calling the dispatch "
6368 "function on that interface gave us NULL", interface_name);
6372 if (is_property_get || is_property_set)
6374 CONNECTION_LOCK (connection);
6375 handled = validate_and_maybe_schedule_property_getset (es->connection,
6383 interface_user_data);
6384 CONNECTION_UNLOCK (connection);
6386 else if (is_property_get_all)
6388 CONNECTION_LOCK (connection);
6389 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6396 interface_user_data);
6397 CONNECTION_UNLOCK (connection);
6402 if (interfaces != NULL)
6404 for (n = 0; interfaces[n] != NULL; n++)
6405 g_dbus_interface_info_unref (interfaces[n]);
6406 g_free (interfaces);
6414 GDBusMessage *message;
6415 ExportedSubtree *es;
6416 } SubtreeDeferredData;
6419 subtree_deferred_data_free (SubtreeDeferredData *data)
6421 g_object_unref (data->message);
6425 /* called without lock held in the thread where the caller registered the subtree */
6427 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6429 SubtreeDeferredData *data = _data;
6434 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6435 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6436 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6437 handled = handle_subtree_introspect (data->es->connection,
6441 handled = handle_subtree_method_invocation (data->es->connection,
6447 CONNECTION_LOCK (data->es->connection);
6448 handled = handle_generic_unlocked (data->es->connection, data->message);
6449 CONNECTION_UNLOCK (data->es->connection);
6452 /* if we couldn't handle the request, just bail with the UnknownMethod error */
6455 GDBusMessage *reply;
6456 reply = g_dbus_message_new_method_error (data->message,
6457 "org.freedesktop.DBus.Error.UnknownMethod",
6458 _("Method '%s' on interface '%s' with signature '%s' does not exist"),
6459 g_dbus_message_get_member (data->message),
6460 g_dbus_message_get_interface (data->message),
6461 g_dbus_message_get_signature (data->message));
6462 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6463 g_object_unref (reply);
6469 /* called in GDBusWorker thread with connection's lock held */
6471 subtree_message_func (GDBusConnection *connection,
6472 ExportedSubtree *es,
6473 GDBusMessage *message)
6475 GSource *idle_source;
6476 SubtreeDeferredData *data;
6478 data = g_new0 (SubtreeDeferredData, 1);
6479 data->message = g_object_ref (message);
6482 /* defer this call to an idle handler in the right thread */
6483 idle_source = g_idle_source_new ();
6484 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
6485 g_source_set_callback (idle_source,
6486 process_subtree_vtable_message_in_idle_cb,
6488 (GDestroyNotify) subtree_deferred_data_free);
6489 g_source_attach (idle_source, es->context);
6490 g_source_unref (idle_source);
6492 /* since we own the entire subtree, handlers for objects not in the subtree have been
6493 * tried already by libdbus-1 - so we just need to ensure that we're always going
6494 * to reply to the message
6500 * g_dbus_connection_register_subtree:
6501 * @connection: a #GDBusConnection
6502 * @object_path: the object path to register the subtree at
6503 * @vtable: a #GDBusSubtreeVTable to enumerate, introspect and
6504 * dispatch nodes in the subtree
6505 * @flags: flags used to fine tune the behavior of the subtree
6506 * @user_data: data to pass to functions in @vtable
6507 * @user_data_free_func: function to call when the subtree is unregistered
6508 * @error: return location for error or %NULL
6510 * Registers a whole subtree of dynamic objects.
6512 * The @enumerate and @introspection functions in @vtable are used to
6513 * convey, to remote callers, what nodes exist in the subtree rooted
6516 * When handling remote calls into any node in the subtree, first the
6517 * @enumerate function is used to check if the node exists. If the node exists
6518 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6519 * the @introspection function is used to check if the node supports the
6520 * requested method. If so, the @dispatch function is used to determine
6521 * where to dispatch the call. The collected #GDBusInterfaceVTable and
6522 * #gpointer will be used to call into the interface vtable for processing
6525 * All calls into user-provided code will be invoked in the <link
6526 * linkend="g-main-context-push-thread-default">thread-default main
6527 * loop</link> of the thread you are calling this method from.
6529 * If an existing subtree is already registered at @object_path or
6530 * then @error is set to #G_IO_ERROR_EXISTS.
6532 * Note that it is valid to register regular objects (using
6533 * g_dbus_connection_register_object()) in a subtree registered with
6534 * g_dbus_connection_register_subtree() - if so, the subtree handler
6535 * is tried as the last resort. One way to think about a subtree
6536 * handler is to consider it a fallback handler for object paths not
6537 * registered via g_dbus_connection_register_object() or other bindings.
6539 * Note that @vtable will be copied so you cannot change it after
6542 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
6544 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
6545 * that can be used with g_dbus_connection_unregister_subtree() .
6550 g_dbus_connection_register_subtree (GDBusConnection *connection,
6551 const gchar *object_path,
6552 const GDBusSubtreeVTable *vtable,
6553 GDBusSubtreeFlags flags,
6555 GDestroyNotify user_data_free_func,
6559 ExportedSubtree *es;
6561 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
6562 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
6563 g_return_val_if_fail (vtable != NULL, 0);
6564 g_return_val_if_fail (error == NULL || *error == NULL, 0);
6565 g_return_val_if_fail (check_initialized (connection), 0);
6569 CONNECTION_LOCK (connection);
6571 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6577 _("A subtree is already exported for %s"),
6582 es = g_new0 (ExportedSubtree, 1);
6583 es->object_path = g_strdup (object_path);
6584 es->connection = connection;
6586 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
6588 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
6589 es->user_data = user_data;
6590 es->user_data_free_func = user_data_free_func;
6591 es->context = g_main_context_ref_thread_default ();
6593 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
6594 g_hash_table_insert (connection->map_id_to_es,
6595 GUINT_TO_POINTER (es->id),
6601 CONNECTION_UNLOCK (connection);
6606 /* ---------------------------------------------------------------------------------------------------- */
6609 * g_dbus_connection_unregister_subtree:
6610 * @connection: a #GDBusConnection
6611 * @registration_id: a subtree registration id obtained from
6612 * g_dbus_connection_register_subtree()
6614 * Unregisters a subtree.
6616 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise
6621 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
6622 guint registration_id)
6624 ExportedSubtree *es;
6627 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
6628 g_return_val_if_fail (check_initialized (connection), FALSE);
6632 CONNECTION_LOCK (connection);
6634 es = g_hash_table_lookup (connection->map_id_to_es,
6635 GUINT_TO_POINTER (registration_id));
6639 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
6640 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
6645 CONNECTION_UNLOCK (connection);
6650 /* ---------------------------------------------------------------------------------------------------- */
6652 /* may be called in any thread, with connection's lock held */
6654 handle_generic_ping_unlocked (GDBusConnection *connection,
6655 const gchar *object_path,
6656 GDBusMessage *message)
6658 GDBusMessage *reply;
6659 reply = g_dbus_message_new_method_reply (message);
6660 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6661 g_object_unref (reply);
6664 /* may be called in any thread, with connection's lock held */
6666 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
6667 const gchar *object_path,
6668 GDBusMessage *message)
6670 GDBusMessage *reply;
6673 if (connection->machine_id == NULL)
6678 connection->machine_id = _g_dbus_get_machine_id (&error);
6679 if (connection->machine_id == NULL)
6681 reply = g_dbus_message_new_method_error_literal (message,
6682 "org.freedesktop.DBus.Error.Failed",
6684 g_error_free (error);
6690 reply = g_dbus_message_new_method_reply (message);
6691 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
6693 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6694 g_object_unref (reply);
6697 /* may be called in any thread, with connection's lock held */
6699 handle_generic_introspect_unlocked (GDBusConnection *connection,
6700 const gchar *object_path,
6701 GDBusMessage *message)
6706 GDBusMessage *reply;
6708 /* first the header */
6709 s = g_string_new (NULL);
6710 introspect_append_header (s);
6712 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
6713 for (n = 0; registered != NULL && registered[n] != NULL; n++)
6714 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
6715 g_strfreev (registered);
6716 g_string_append (s, "</node>\n");
6718 reply = g_dbus_message_new_method_reply (message);
6719 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6720 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6721 g_object_unref (reply);
6722 g_string_free (s, TRUE);
6725 /* may be called in any thread, with connection's lock held */
6727 handle_generic_unlocked (GDBusConnection *connection,
6728 GDBusMessage *message)
6731 const gchar *interface_name;
6732 const gchar *member;
6733 const gchar *signature;
6736 CONNECTION_ENSURE_LOCK (connection);
6740 interface_name = g_dbus_message_get_interface (message);
6741 member = g_dbus_message_get_member (message);
6742 signature = g_dbus_message_get_signature (message);
6743 path = g_dbus_message_get_path (message);
6745 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
6746 g_strcmp0 (member, "Introspect") == 0 &&
6747 g_strcmp0 (signature, "") == 0)
6749 handle_generic_introspect_unlocked (connection, path, message);
6752 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6753 g_strcmp0 (member, "Ping") == 0 &&
6754 g_strcmp0 (signature, "") == 0)
6756 handle_generic_ping_unlocked (connection, path, message);
6759 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6760 g_strcmp0 (member, "GetMachineId") == 0 &&
6761 g_strcmp0 (signature, "") == 0)
6763 handle_generic_get_machine_id_unlocked (connection, path, message);
6770 /* ---------------------------------------------------------------------------------------------------- */
6772 /* called in GDBusWorker thread with connection's lock held */
6774 distribute_method_call (GDBusConnection *connection,
6775 GDBusMessage *message)
6777 GDBusMessage *reply;
6779 ExportedSubtree *es;
6780 const gchar *object_path;
6781 const gchar *interface_name;
6782 const gchar *member;
6784 gchar *subtree_path;
6787 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
6789 interface_name = g_dbus_message_get_interface (message);
6790 member = g_dbus_message_get_member (message);
6791 path = g_dbus_message_get_path (message);
6792 subtree_path = g_strdup (path);
6793 needle = strrchr (subtree_path, '/');
6794 if (needle != NULL && needle != subtree_path)
6800 g_free (subtree_path);
6801 subtree_path = NULL;
6805 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
6807 _g_dbus_debug_print_lock ();
6808 g_print ("========================================================================\n"
6809 "GDBus-debug:Incoming:\n"
6810 " <<<< METHOD INVOCATION %s.%s()\n"
6812 " invoked by name %s\n"
6814 interface_name, member,
6816 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
6817 g_dbus_message_get_serial (message));
6818 _g_dbus_debug_print_unlock ();
6821 object_path = g_dbus_message_get_path (message);
6822 g_assert (object_path != NULL);
6824 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
6827 if (obj_message_func (connection, eo, message))
6831 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6834 if (subtree_message_func (connection, es, message))
6838 if (subtree_path != NULL)
6840 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
6843 if (subtree_message_func (connection, es, message))
6848 if (handle_generic_unlocked (connection, message))
6851 /* if we end up here, the message has not been not handled - so return an error saying this */
6852 reply = g_dbus_message_new_method_error (message,
6853 "org.freedesktop.DBus.Error.UnknownMethod",
6854 _("No such interface '%s' on object at path %s"),
6857 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6858 g_object_unref (reply);
6861 g_free (subtree_path);
6864 /* ---------------------------------------------------------------------------------------------------- */
6866 /* Called in any user thread, with the message_bus_lock held. */
6868 message_bus_get_singleton (GBusType bus_type,
6872 const gchar *starter_bus;
6878 case G_BUS_TYPE_SESSION:
6879 ret = &the_session_bus;
6882 case G_BUS_TYPE_SYSTEM:
6883 ret = &the_system_bus;
6886 case G_BUS_TYPE_STARTER:
6887 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
6888 if (g_strcmp0 (starter_bus, "session") == 0)
6890 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
6893 else if (g_strcmp0 (starter_bus, "system") == 0)
6895 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
6900 if (starter_bus != NULL)
6904 G_IO_ERROR_INVALID_ARGUMENT,
6905 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
6906 " - unknown value '%s'"),
6911 g_set_error_literal (error,
6913 G_IO_ERROR_INVALID_ARGUMENT,
6914 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
6915 "variable is not set"));
6921 g_assert_not_reached ();
6929 /* Called in any user thread, without holding locks. */
6930 static GDBusConnection *
6931 get_uninitialized_connection (GBusType bus_type,
6932 GCancellable *cancellable,
6935 GWeakRef *singleton;
6936 GDBusConnection *ret;
6940 G_LOCK (message_bus_lock);
6941 singleton = message_bus_get_singleton (bus_type, error);
6942 if (singleton == NULL)
6945 ret = g_weak_ref_get (singleton);
6950 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
6951 if (address == NULL)
6953 ret = g_object_new (G_TYPE_DBUS_CONNECTION,
6955 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
6956 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
6957 "exit-on-close", TRUE,
6960 g_weak_ref_set (singleton, ret);
6964 g_assert (ret != NULL);
6967 G_UNLOCK (message_bus_lock);
6971 /* May be called from any thread. Must not hold message_bus_lock. */
6973 _g_bus_get_singleton_if_exists (GBusType bus_type)
6975 GWeakRef *singleton;
6976 GDBusConnection *ret = NULL;
6978 G_LOCK (message_bus_lock);
6979 singleton = message_bus_get_singleton (bus_type, NULL);
6980 if (singleton == NULL)
6983 ret = g_weak_ref_get (singleton);
6986 G_UNLOCK (message_bus_lock);
6992 * @bus_type: a #GBusType
6993 * @cancellable: (allow-none): a #GCancellable or %NULL
6994 * @error: return location for error or %NULL
6996 * Synchronously connects to the message bus specified by @bus_type.
6997 * Note that the returned object may shared with other callers,
6998 * e.g. if two separate parts of a process calls this function with
6999 * the same @bus_type, they will share the same object.
7001 * This is a synchronous failable function. See g_bus_get() and
7002 * g_bus_get_finish() for the asynchronous version.
7004 * The returned object is a singleton, that is, shared with other
7005 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7006 * event that you need a private message bus connection, use
7007 * g_dbus_address_get_for_bus_sync() and
7008 * g_dbus_connection_new_for_address().
7010 * Note that the returned #GDBusConnection object will (usually) have
7011 * the #GDBusConnection:exit-on-close property set to %TRUE.
7013 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7014 * Free with g_object_unref().
7019 g_bus_get_sync (GBusType bus_type,
7020 GCancellable *cancellable,
7023 GDBusConnection *connection;
7025 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7027 connection = get_uninitialized_connection (bus_type, cancellable, error);
7028 if (connection == NULL)
7031 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
7033 g_object_unref (connection);
7042 bus_get_async_initable_cb (GObject *source_object,
7046 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
7050 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
7054 g_assert (error != NULL);
7055 g_simple_async_result_take_error (simple, error);
7056 g_object_unref (source_object);
7060 g_simple_async_result_set_op_res_gpointer (simple,
7064 g_simple_async_result_complete_in_idle (simple);
7065 g_object_unref (simple);
7070 * @bus_type: a #GBusType
7071 * @cancellable: (allow-none): a #GCancellable or %NULL
7072 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
7073 * @user_data: the data to pass to @callback
7075 * Asynchronously connects to the message bus specified by @bus_type.
7077 * When the operation is finished, @callback will be invoked. You can
7078 * then call g_bus_get_finish() to get the result of the operation.
7080 * This is a asynchronous failable function. See g_bus_get_sync() for
7081 * the synchronous version.
7086 g_bus_get (GBusType bus_type,
7087 GCancellable *cancellable,
7088 GAsyncReadyCallback callback,
7091 GDBusConnection *connection;
7092 GSimpleAsyncResult *simple;
7095 simple = g_simple_async_result_new (NULL,
7099 g_simple_async_result_set_check_cancellable (simple, cancellable);
7102 connection = get_uninitialized_connection (bus_type, cancellable, &error);
7103 if (connection == NULL)
7105 g_assert (error != NULL);
7106 g_simple_async_result_take_error (simple, error);
7107 g_simple_async_result_complete_in_idle (simple);
7108 g_object_unref (simple);
7112 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
7115 bus_get_async_initable_cb,
7122 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
7124 * @error: return location for error or %NULL
7126 * Finishes an operation started with g_bus_get().
7128 * The returned object is a singleton, that is, shared with other
7129 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7130 * event that you need a private message bus connection, use
7131 * g_dbus_address_get_for_bus_sync() and
7132 * g_dbus_connection_new_for_address().
7134 * Note that the returned #GDBusConnection object will (usually) have
7135 * the #GDBusConnection:exit-on-close property set to %TRUE.
7137 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7138 * Free with g_object_unref().
7143 g_bus_get_finish (GAsyncResult *res,
7146 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
7148 GDBusConnection *ret;
7150 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7152 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
7156 if (g_simple_async_result_propagate_error (simple, error))
7159 object = g_simple_async_result_get_op_res_gpointer (simple);
7160 g_assert (object != NULL);
7161 ret = g_object_ref (G_DBUS_CONNECTION (object));
7167 /* ---------------------------------------------------------------------------------------------------- */