1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, write to the
17 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18 * Boston, MA 02111-1307, USA.
20 * Author: David Zeuthen <davidz@redhat.com>
26 * - would be nice to expose GDBusAuthMechanism and an extension point
28 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
29 * the mechanism VFuncs need to be able to set an error.
31 * - Need to document other mechanisms/sources for determining the D-Bus
32 * address of a well-known bus.
34 * - e.g. on Win32 we need code like from here
36 * http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
38 * that was never copied over here because it originally was copy-paste
39 * from the GPLv2 / AFL 2.1 libdbus sources.
41 * - on OS X we need to look in launchd for the address
43 * https://bugs.freedesktop.org/show_bug.cgi?id=14259
45 * - on X11 we need to look in a X11 property on the X server
46 * - (we can also just use dbus-launch(1) from the D-Bus
49 * - (ideally) this requires D-Bus spec work because none of
50 * this has never really been specced out properly (except
53 * - Related to the above, we also need to be able to launch a message bus
54 * instance.... Since we don't want to write our own bus daemon we should
55 * launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
57 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
58 * to specify where the nonce is stored. This will allow people to use
59 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
60 * to easily achieve secure RPC via nonce-tcp.
62 * - need to expose an extension point for resolving D-Bus address and
63 * turning them into GIOStream objects. This will allow us to implement
64 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
66 * - see g_dbus_address_connect() in gdbusaddress.c
68 * - would be cute to use kernel-specific APIs to resolve fds for
69 * debug output when using G_DBUS_DEBUG=message, e.g. in addition to
71 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
73 * maybe we can show more information about what fd 21 really is.
74 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
75 * Initial experiments on Linux 2.6 suggests that the symlink looks
80 * e.g. not of much use.
82 * - GDBus High-Level docs
83 * - Proxy: properties, signals...
84 * - Connection: IOStream based, ::close, connection setup steps
85 * mainloop integration, threading
86 * - Differences from libdbus (extend "Migrating from")
87 * - the message handling thread
88 * - Using GVariant instead of GValue
89 * - Explain why the high-level API is a good thing and what
90 * kind of pitfalls it avoids
91 * - Export objects before claiming names
92 * - Talk about auto-starting services (cf. GBusNameWatcherFlags)
94 * - use abstract sockets in test code
95 * - right now it doesn't work, dbus-daemon(1) fails with
97 * /gdbus/connection/filter: Failed to start message bus: Failed to bind
98 * socket "/tmp/g-dbus-tests-pid-28531": Address already in use
99 * ** WARNING **: Error reading address from dbus daemon, 0 bytes read
108 #include <sys/types.h>
113 #include "gdbusauth.h"
114 #include "gdbusutils.h"
115 #include "gdbusaddress.h"
116 #include "gdbusmessage.h"
117 #include "gdbusconnection.h"
118 #include "gdbuserror.h"
119 #include "gioenumtypes.h"
120 #include "gdbusintrospection.h"
121 #include "gdbusmethodinvocation.h"
122 #include "gdbusprivate.h"
123 #include "gdbusauthobserver.h"
124 #include "ginitable.h"
125 #include "gasyncinitable.h"
126 #include "giostream.h"
127 #include "gasyncresult.h"
128 #include "gsimpleasyncresult.h"
131 #include "gunixconnection.h"
132 #include "gunixfdmessage.h"
135 #include "glibintl.h"
138 * SECTION:gdbusconnection
139 * @short_description: D-Bus Connections
140 * @include: gio/gio.h
142 * The #GDBusConnection type is used for D-Bus connections to remote
143 * peers such as a message buses. It is a low-level API that offers a
144 * lot of flexibility. For instance, it lets you establish a connection
145 * over any transport that can by represented as an #GIOStream.
147 * This class is rarely used directly in D-Bus clients. If you are writing
148 * an D-Bus client, it is often easier to use the g_bus_own_name(),
149 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
151 * As an exception to the usual GLib rule that a particular object must not be
152 * used by two threads at the same time, #GDBusConnection's methods may be
153 * called from any thread<footnote>
155 * This is so that g_bus_get() and g_bus_get_sync() can safely return the
156 * same #GDBusConnection when called from any thread.
160 * Most of the ways to obtain a #GDBusConnection automatically initialize it
161 * (i.e. connect to D-Bus): for instance, g_dbus_connection_new() and
162 * g_bus_get(), and the synchronous versions of those methods, give you an
163 * initialized connection. Language bindings for GIO should use
164 * g_initable_new() or g_async_initable_new(), which also initialize the
167 * If you construct an uninitialized #GDBusConnection, such as via
168 * g_object_new(), you must initialize it via g_initable_init() or
169 * g_async_initable_init() before using its methods or properties. Calling
170 * methods or accessing properties on a #GDBusConnection that has not completed
171 * initialization successfully is considered to be invalid, and leads to
172 * undefined behaviour. In particular, if initialization fails with a #GError,
173 * the only valid thing you can do with that #GDBusConnection is to free it
174 * with g_object_unref().
176 * <example id="gdbus-server"><title>D-Bus server example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-server.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
178 * <example id="gdbus-subtree-server"><title>D-Bus subtree example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-subtree.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
180 * <example id="gdbus-unix-fd-client"><title>D-Bus UNIX File Descriptor example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-unix-fd-client.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
182 * <example id="gdbus-export"><title>Exporting a GObject</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-export.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
185 /* ---------------------------------------------------------------------------------------------------- */
187 typedef struct _GDBusConnectionClass GDBusConnectionClass;
190 * GDBusConnectionClass:
191 * @closed: Signal class handler for the #GDBusConnection::closed signal.
193 * Class structure for #GDBusConnection.
197 struct _GDBusConnectionClass
200 GObjectClass parent_class;
204 void (*closed) (GDBusConnection *connection,
205 gboolean remote_peer_vanished,
209 G_LOCK_DEFINE_STATIC (message_bus_lock);
211 static GDBusConnection *the_session_bus = NULL;
212 static GDBusConnection *the_system_bus = NULL;
214 /* Extra pseudo-member of GDBusSendMessageFlags.
215 * Set by initable_init() to indicate that despite not being initialized yet,
216 * enough of the only-valid-after-init members are set that we can send a
217 * message, and we're being called from its thread, so no memory barrier is
218 * required before accessing them.
220 #define SEND_MESSAGE_FLAGS_INITIALIZING (1<<31)
222 /* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
223 #define CALL_FLAGS_INITIALIZING (1<<31)
225 /* ---------------------------------------------------------------------------------------------------- */
229 GDestroyNotify callback;
231 GMainContext *context;
232 } CallDestroyNotifyData;
235 call_destroy_notify_data_in_idle (gpointer user_data)
237 CallDestroyNotifyData *data = user_data;
238 data->callback (data->user_data);
243 call_destroy_notify_data_free (CallDestroyNotifyData *data)
245 if (data->context != NULL)
246 g_main_context_unref (data->context);
251 * call_destroy_notify: <internal>
252 * @context: A #GMainContext or %NULL.
253 * @callback: A #GDestroyNotify or %NULL.
254 * @user_data: Data to pass to @callback.
256 * Schedules @callback to run in @context.
259 call_destroy_notify (GMainContext *context,
260 GDestroyNotify callback,
263 GSource *idle_source;
264 CallDestroyNotifyData *data;
266 if (callback == NULL)
269 data = g_new0 (CallDestroyNotifyData, 1);
270 data->callback = callback;
271 data->user_data = user_data;
272 data->context = context;
273 if (data->context != NULL)
274 g_main_context_ref (data->context);
276 idle_source = g_idle_source_new ();
277 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
278 g_source_set_callback (idle_source,
279 call_destroy_notify_data_in_idle,
281 (GDestroyNotify) call_destroy_notify_data_free);
282 g_source_attach (idle_source, data->context);
283 g_source_unref (idle_source);
289 /* ---------------------------------------------------------------------------------------------------- */
292 _g_strv_has_string (const gchar* const *haystack,
297 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
299 if (g_strcmp0 (haystack[n], needle) == 0)
305 /* ---------------------------------------------------------------------------------------------------- */
308 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
310 // TODO: for some reason this doesn't work on Windows
311 #define CONNECTION_ENSURE_LOCK(obj) do { \
312 if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock))) \
314 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
315 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
320 #define CONNECTION_LOCK(obj) do { \
321 g_mutex_lock (&(obj)->lock); \
324 #define CONNECTION_UNLOCK(obj) do { \
325 g_mutex_unlock (&(obj)->lock); \
328 /* Flags in connection->atomic_flags */
330 FLAG_INITIALIZED = 1 << 0,
331 FLAG_EXIT_ON_CLOSE = 1 << 1,
338 * The #GDBusConnection structure contains only private data and
339 * should only be accessed using the provided API.
343 struct _GDBusConnection
346 GObject parent_instance;
348 /* ------------------------------------------------------------------------ */
349 /* -- General object state ------------------------------------------------ */
350 /* ------------------------------------------------------------------------ */
352 /* General-purpose lock for most fields */
355 /* A lock used in the init() method of the GInitable interface - see comments
356 * in initable_init() for why a separate lock is needed.
358 * If you need both @lock and @init_lock, you must take @init_lock first.
362 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
363 * someone calls org.freedesktop.DBus.GetMachineId(). Protected by @lock.
367 /* The underlying stream used for communication
368 * Read-only after initable_init(), so it may be read if you either
369 * hold @init_lock or check for initialization first.
373 /* The object used for authentication (if any).
374 * Read-only after initable_init(), so it may be read if you either
375 * hold @init_lock or check for initialization first.
379 /* Last serial used. Protected by @lock. */
382 /* The object used to send/receive messages.
383 * Read-only after initable_init(), so it may be read if you either
384 * hold @init_lock or check for initialization first.
388 /* If connected to a message bus, this contains the unique name assigned to
389 * us by the bus (e.g. ":1.42").
390 * Read-only after initable_init(), so it may be read if you either
391 * hold @init_lock or check for initialization first.
393 gchar *bus_unique_name;
395 /* The GUID returned by the other side if we authenticed as a client or
396 * the GUID to use if authenticating as a server.
397 * Read-only after initable_init(), so it may be read if you either
398 * hold @init_lock or check for initialization first.
402 /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
403 * Inspect @initialization_error to see whether it succeeded or failed.
405 * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
407 * FLAG_CLOSED is the closed property. It may be read at any time, but
408 * may only be written while holding @lock.
410 volatile gint atomic_flags;
412 /* If the connection could not be established during initable_init(),
413 * this GError will be set.
414 * Read-only after initable_init(), so it may be read if you either
415 * hold @init_lock or check for initialization first.
417 GError *initialization_error;
419 /* The result of g_main_context_ref_thread_default() when the object
420 * was created (the GObject _init() function) - this is used for delivery
421 * of the :closed GObject signal.
423 * Only set in the GObject init function, so no locks are needed.
425 GMainContext *main_context_at_construction;
427 /* Read-only construct properties, no locks needed */
429 GDBusConnectionFlags flags;
431 /* Map used for managing method replies, protected by @lock */
432 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
434 /* Maps used for managing signal subscription, protected by @lock */
435 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
436 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
437 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
439 /* Maps used for managing exported objects and subtrees,
442 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
443 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
444 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
445 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
447 /* Structure used for message filters, protected by @lock */
450 /* Capabilities negotiated during authentication
451 * Read-only after initable_init(), so it may be read without holding a
452 * lock, if you check for initialization first.
454 GDBusCapabilityFlags capabilities;
456 /* Protected by @init_lock */
457 GDBusAuthObserver *authentication_observer;
459 /* Read-only after initable_init(), so it may be read if you either
460 * hold @init_lock or check for initialization first.
462 GCredentials *credentials;
464 /* set to TRUE when finalizing */
468 typedef struct ExportedObject ExportedObject;
469 static void exported_object_free (ExportedObject *eo);
471 typedef struct ExportedSubtree ExportedSubtree;
472 static void exported_subtree_free (ExportedSubtree *es);
490 PROP_CAPABILITY_FLAGS,
491 PROP_AUTHENTICATION_OBSERVER,
494 static void distribute_signals (GDBusConnection *connection,
495 GDBusMessage *message);
497 static void distribute_method_call (GDBusConnection *connection,
498 GDBusMessage *message);
500 static gboolean handle_generic_unlocked (GDBusConnection *connection,
501 GDBusMessage *message);
504 static void purge_all_signal_subscriptions (GDBusConnection *connection);
505 static void purge_all_filters (GDBusConnection *connection);
507 #define _G_ENSURE_LOCK(name) do { \
508 if (G_UNLIKELY (G_TRYLOCK(name))) \
510 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
511 "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
515 static guint signals[LAST_SIGNAL] = { 0 };
517 static void initable_iface_init (GInitableIface *initable_iface);
518 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
520 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
521 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
522 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
526 * Check that all members of @connection that can only be accessed after
527 * the connection is initialized can safely be accessed. If not,
528 * log a critical warning. This function is a memory barrier.
530 * Returns: %TRUE if initialized
533 check_initialized (GDBusConnection *connection)
535 /* The access to @atomic_flags isn't conditional, so that this function
536 * provides a memory barrier for thread-safety even if checks are disabled.
537 * (If you don't want this stricter guarantee, you can call
538 * g_return_if_fail (check_initialized (c)).)
540 * This isn't strictly necessary now that we've decided use of an
541 * uninitialized GDBusConnection is undefined behaviour, but it seems
542 * better to be as deterministic as is feasible.
544 * (Anything that could suffer a crash from seeing undefined values
545 * must have a race condition - thread A initializes the connection while
546 * thread B calls a method without initialization, hoping that thread A will
547 * win the race - so its behaviour is undefined anyway.)
549 gint flags = g_atomic_int_get (&connection->atomic_flags);
551 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
553 /* We can safely access this, due to the memory barrier above */
554 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
560 MAY_BE_UNINITIALIZED = (1<<1)
561 } CheckUnclosedFlags;
564 * Check the same thing as check_initialized(), and also that the
565 * connection is not closed. If the connection is uninitialized,
566 * raise a critical warning (it's programmer error); if it's closed,
567 * raise a recoverable GError (it's a runtime error).
569 * This function is a memory barrier.
571 * Returns: %TRUE if initialized and not closed
574 check_unclosed (GDBusConnection *connection,
575 CheckUnclosedFlags check,
578 /* check_initialized() is effectively inlined, so we don't waste time
579 * doing two memory barriers
581 gint flags = g_atomic_int_get (&connection->atomic_flags);
583 if (!(check & MAY_BE_UNINITIALIZED))
585 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
586 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
589 if (flags & FLAG_CLOSED)
591 g_set_error_literal (error,
594 _("The connection is closed"));
601 static GHashTable *alive_connections = NULL;
604 g_dbus_connection_dispose (GObject *object)
606 GDBusConnection *connection = G_DBUS_CONNECTION (object);
608 G_LOCK (message_bus_lock);
609 if (connection == the_session_bus)
611 the_session_bus = NULL;
613 else if (connection == the_system_bus)
615 the_system_bus = NULL;
617 CONNECTION_LOCK (connection);
618 if (connection->worker != NULL)
620 _g_dbus_worker_stop (connection->worker);
621 connection->worker = NULL;
622 if (alive_connections != NULL)
623 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
627 if (alive_connections != NULL)
628 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
630 CONNECTION_UNLOCK (connection);
631 G_UNLOCK (message_bus_lock);
633 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
634 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
638 g_dbus_connection_finalize (GObject *object)
640 GDBusConnection *connection = G_DBUS_CONNECTION (object);
642 connection->finalizing = TRUE;
644 purge_all_signal_subscriptions (connection);
646 purge_all_filters (connection);
647 g_ptr_array_unref (connection->filters);
649 if (connection->authentication_observer != NULL)
650 g_object_unref (connection->authentication_observer);
652 if (connection->auth != NULL)
653 g_object_unref (connection->auth);
655 if (connection->credentials)
656 g_object_unref (connection->credentials);
658 if (connection->stream != NULL)
660 g_object_unref (connection->stream);
661 connection->stream = NULL;
664 g_free (connection->address);
666 g_free (connection->guid);
667 g_free (connection->bus_unique_name);
669 if (connection->initialization_error != NULL)
670 g_error_free (connection->initialization_error);
672 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
674 g_hash_table_unref (connection->map_rule_to_signal_data);
675 g_hash_table_unref (connection->map_id_to_signal_data);
676 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
678 g_hash_table_unref (connection->map_id_to_ei);
679 g_hash_table_unref (connection->map_object_path_to_eo);
680 g_hash_table_unref (connection->map_id_to_es);
681 g_hash_table_unref (connection->map_object_path_to_es);
683 g_main_context_unref (connection->main_context_at_construction);
685 g_free (connection->machine_id);
687 g_mutex_clear (&connection->init_lock);
688 g_mutex_clear (&connection->lock);
690 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
693 /* called in any user thread, with the connection's lock not held */
695 g_dbus_connection_get_property (GObject *object,
700 GDBusConnection *connection = G_DBUS_CONNECTION (object);
705 g_value_set_object (value, g_dbus_connection_get_stream (connection));
709 g_value_set_string (value, g_dbus_connection_get_guid (connection));
712 case PROP_UNIQUE_NAME:
713 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
717 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
720 case PROP_EXIT_ON_CLOSE:
721 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
724 case PROP_CAPABILITY_FLAGS:
725 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
729 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
734 /* called in any user thread, with the connection's lock not held */
736 g_dbus_connection_set_property (GObject *object,
741 GDBusConnection *connection = G_DBUS_CONNECTION (object);
746 connection->stream = g_value_dup_object (value);
750 connection->guid = g_value_dup_string (value);
754 connection->address = g_value_dup_string (value);
758 connection->flags = g_value_get_flags (value);
761 case PROP_EXIT_ON_CLOSE:
762 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
765 case PROP_AUTHENTICATION_OBSERVER:
766 connection->authentication_observer = g_value_dup_object (value);
770 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
775 /* Base-class implementation of GDBusConnection::closed.
777 * Called in a user thread, by the main context that was thread-default when
778 * the object was constructed.
781 g_dbus_connection_real_closed (GDBusConnection *connection,
782 gboolean remote_peer_vanished,
785 gint flags = g_atomic_int_get (&connection->atomic_flags);
787 /* Because atomic int access is a memory barrier, we can safely read
788 * initialization_error without a lock, as long as we do it afterwards.
790 if (remote_peer_vanished &&
791 (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
792 (flags & FLAG_INITIALIZED) != 0 &&
793 connection->initialization_error == NULL)
797 g_print ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
800 g_quark_to_string (error->domain), error->code);
804 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
811 g_dbus_connection_class_init (GDBusConnectionClass *klass)
813 GObjectClass *gobject_class;
815 gobject_class = G_OBJECT_CLASS (klass);
817 gobject_class->finalize = g_dbus_connection_finalize;
818 gobject_class->dispose = g_dbus_connection_dispose;
819 gobject_class->set_property = g_dbus_connection_set_property;
820 gobject_class->get_property = g_dbus_connection_get_property;
822 klass->closed = g_dbus_connection_real_closed;
825 * GDBusConnection:stream:
827 * The underlying #GIOStream used for I/O.
829 * If this is passed on construction and is a #GSocketConnection,
830 * then the corresponding #GSocket will be put into non-blocking mode.
832 * While the #GDBusConnection is active, it will interact with this
833 * stream from a worker thread, so it is not safe to interact with
834 * the stream directly.
838 g_object_class_install_property (gobject_class,
840 g_param_spec_object ("stream",
842 P_("The underlying streams used for I/O"),
846 G_PARAM_CONSTRUCT_ONLY |
847 G_PARAM_STATIC_NAME |
848 G_PARAM_STATIC_BLURB |
849 G_PARAM_STATIC_NICK));
852 * GDBusConnection:address:
854 * A D-Bus address specifying potential endpoints that can be used
855 * when establishing the connection.
859 g_object_class_install_property (gobject_class,
861 g_param_spec_string ("address",
863 P_("D-Bus address specifying potential socket endpoints"),
866 G_PARAM_CONSTRUCT_ONLY |
867 G_PARAM_STATIC_NAME |
868 G_PARAM_STATIC_BLURB |
869 G_PARAM_STATIC_NICK));
872 * GDBusConnection:flags:
874 * Flags from the #GDBusConnectionFlags enumeration.
878 g_object_class_install_property (gobject_class,
880 g_param_spec_flags ("flags",
883 G_TYPE_DBUS_CONNECTION_FLAGS,
884 G_DBUS_CONNECTION_FLAGS_NONE,
886 G_PARAM_CONSTRUCT_ONLY |
887 G_PARAM_STATIC_NAME |
888 G_PARAM_STATIC_BLURB |
889 G_PARAM_STATIC_NICK));
892 * GDBusConnection:guid:
894 * The GUID of the peer performing the role of server when
897 * If you are constructing a #GDBusConnection and pass
898 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
899 * #GDBusConnection:flags property then you MUST also set this
900 * property to a valid guid.
902 * If you are constructing a #GDBusConnection and pass
903 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
904 * #GDBusConnection:flags property you will be able to read the GUID
905 * of the other peer here after the connection has been successfully
910 g_object_class_install_property (gobject_class,
912 g_param_spec_string ("guid",
914 P_("GUID of the server peer"),
918 G_PARAM_CONSTRUCT_ONLY |
919 G_PARAM_STATIC_NAME |
920 G_PARAM_STATIC_BLURB |
921 G_PARAM_STATIC_NICK));
924 * GDBusConnection:unique-name:
926 * The unique name as assigned by the message bus or %NULL if the
927 * connection is not open or not a message bus connection.
931 g_object_class_install_property (gobject_class,
933 g_param_spec_string ("unique-name",
935 P_("Unique name of bus connection"),
938 G_PARAM_STATIC_NAME |
939 G_PARAM_STATIC_BLURB |
940 G_PARAM_STATIC_NICK));
943 * GDBusConnection:closed:
945 * A boolean specifying whether the connection has been closed.
949 g_object_class_install_property (gobject_class,
951 g_param_spec_boolean ("closed",
953 P_("Whether the connection is closed"),
956 G_PARAM_STATIC_NAME |
957 G_PARAM_STATIC_BLURB |
958 G_PARAM_STATIC_NICK));
961 * GDBusConnection:exit-on-close:
963 * A boolean specifying whether the process will be terminated (by
964 * calling <literal>raise(SIGTERM)</literal>) if the connection
965 * is closed by the remote peer.
969 g_object_class_install_property (gobject_class,
971 g_param_spec_boolean ("exit-on-close",
973 P_("Whether the process is terminated when the connection is closed"),
977 G_PARAM_STATIC_NAME |
978 G_PARAM_STATIC_BLURB |
979 G_PARAM_STATIC_NICK));
982 * GDBusConnection:capabilities:
984 * Flags from the #GDBusCapabilityFlags enumeration
985 * representing connection features negotiated with the other peer.
989 g_object_class_install_property (gobject_class,
990 PROP_CAPABILITY_FLAGS,
991 g_param_spec_flags ("capabilities",
994 G_TYPE_DBUS_CAPABILITY_FLAGS,
995 G_DBUS_CAPABILITY_FLAGS_NONE,
997 G_PARAM_STATIC_NAME |
998 G_PARAM_STATIC_BLURB |
999 G_PARAM_STATIC_NICK));
1002 * GDBusConnection:authentication-observer:
1004 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
1008 g_object_class_install_property (gobject_class,
1009 PROP_AUTHENTICATION_OBSERVER,
1010 g_param_spec_object ("authentication-observer",
1011 P_("Authentication Observer"),
1012 P_("Object used to assist in the authentication process"),
1013 G_TYPE_DBUS_AUTH_OBSERVER,
1015 G_PARAM_CONSTRUCT_ONLY |
1016 G_PARAM_STATIC_NAME |
1017 G_PARAM_STATIC_BLURB |
1018 G_PARAM_STATIC_NICK));
1021 * GDBusConnection::closed:
1022 * @connection: The #GDBusConnection emitting the signal.
1023 * @remote_peer_vanished: %TRUE if @connection is closed because the
1024 * remote peer closed its end of the connection.
1025 * @error: A #GError with more details about the event or %NULL.
1027 * Emitted when the connection is closed.
1029 * The cause of this event can be
1032 * If g_dbus_connection_close() is called. In this case
1033 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
1034 * </para></listitem>
1036 * If the remote peer closes the connection. In this case
1037 * @remote_peer_vanished is set to %TRUE and @error is set.
1038 * </para></listitem>
1040 * If the remote peer sends invalid or malformed data. In this
1041 * case @remote_peer_vanished is set to %FALSE and @error
1043 * </para></listitem>
1046 * Upon receiving this signal, you should give up your reference to
1047 * @connection. You are guaranteed that this signal is emitted only
1052 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
1053 G_TYPE_DBUS_CONNECTION,
1055 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1066 g_dbus_connection_init (GDBusConnection *connection)
1068 g_mutex_init (&connection->lock);
1069 g_mutex_init (&connection->init_lock);
1071 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
1073 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1075 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1077 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1080 (GDestroyNotify) g_ptr_array_unref);
1082 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1085 (GDestroyNotify) exported_object_free);
1087 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1090 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1093 (GDestroyNotify) exported_subtree_free);
1095 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1098 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1100 connection->filters = g_ptr_array_new ();
1104 * g_dbus_connection_get_stream:
1105 * @connection: a #GDBusConnection
1107 * Gets the underlying stream used for IO.
1109 * While the #GDBusConnection is active, it will interact with this
1110 * stream from a worker thread, so it is not safe to interact with
1111 * the stream directly.
1113 * Returns: (transfer none): the stream used for IO
1118 g_dbus_connection_get_stream (GDBusConnection *connection)
1120 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1122 /* do not use g_return_val_if_fail(), we want the memory barrier */
1123 if (!check_initialized (connection))
1126 return connection->stream;
1130 * g_dbus_connection_start_message_processing:
1131 * @connection: A #GDBusConnection.
1133 * If @connection was created with
1134 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1135 * starts processing messages. Does nothing on if @connection wasn't
1136 * created with this flag or if the method has already been called.
1141 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1143 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1145 /* do not use g_return_val_if_fail(), we want the memory barrier */
1146 if (!check_initialized (connection))
1149 g_assert (connection->worker != NULL);
1150 _g_dbus_worker_unfreeze (connection->worker);
1154 * g_dbus_connection_is_closed:
1155 * @connection: A #GDBusConnection.
1157 * Gets whether @connection is closed.
1159 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
1164 g_dbus_connection_is_closed (GDBusConnection *connection)
1168 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1170 flags = g_atomic_int_get (&connection->atomic_flags);
1172 return (flags & FLAG_CLOSED) ? TRUE : FALSE;
1176 * g_dbus_connection_get_capabilities:
1177 * @connection: A #GDBusConnection.
1179 * Gets the capabilities negotiated with the remote peer
1181 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
1185 GDBusCapabilityFlags
1186 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1188 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1190 /* do not use g_return_val_if_fail(), we want the memory barrier */
1191 if (!check_initialized (connection))
1192 return G_DBUS_CAPABILITY_FLAGS_NONE;
1194 return connection->capabilities;
1197 /* ---------------------------------------------------------------------------------------------------- */
1199 /* Called in a temporary thread without holding locks. */
1201 flush_in_thread_func (GSimpleAsyncResult *res,
1203 GCancellable *cancellable)
1208 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1211 g_simple_async_result_take_error (res, error);
1215 * g_dbus_connection_flush:
1216 * @connection: A #GDBusConnection.
1217 * @cancellable: A #GCancellable or %NULL.
1218 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1219 * satisfied or %NULL if you don't care about the result.
1220 * @user_data: The data to pass to @callback.
1222 * Asynchronously flushes @connection, that is, writes all queued
1223 * outgoing message to the transport and then flushes the transport
1224 * (using g_output_stream_flush_async()). This is useful in programs
1225 * that wants to emit a D-Bus signal and then exit
1226 * immediately. Without flushing the connection, there is no guarantee
1227 * that the message has been sent to the networking buffers in the OS
1230 * This is an asynchronous method. When the operation is finished,
1231 * @callback will be invoked in the <link
1232 * linkend="g-main-context-push-thread-default">thread-default main
1233 * loop</link> of the thread you are calling this method from. You can
1234 * then call g_dbus_connection_flush_finish() to get the result of the
1235 * operation. See g_dbus_connection_flush_sync() for the synchronous
1241 g_dbus_connection_flush (GDBusConnection *connection,
1242 GCancellable *cancellable,
1243 GAsyncReadyCallback callback,
1246 GSimpleAsyncResult *simple;
1248 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1250 simple = g_simple_async_result_new (G_OBJECT (connection),
1253 g_dbus_connection_flush);
1254 g_simple_async_result_run_in_thread (simple,
1255 flush_in_thread_func,
1258 g_object_unref (simple);
1262 * g_dbus_connection_flush_finish:
1263 * @connection: A #GDBusConnection.
1264 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed 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: 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: 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_dbus_worker_close (connection->worker, cancellable, simple);
1468 g_object_unref (simple);
1472 * g_dbus_connection_close_finish:
1473 * @connection: A #GDBusConnection.
1474 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_close().
1475 * @error: Return location for error or %NULL.
1477 * Finishes an operation started with g_dbus_connection_close().
1479 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1484 g_dbus_connection_close_finish (GDBusConnection *connection,
1488 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1493 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1494 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1495 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1497 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1499 if (g_simple_async_result_propagate_error (simple, error))
1510 GAsyncResult *result;
1513 /* Can be called by any thread, without the connection lock */
1515 sync_close_cb (GObject *source_object,
1519 SyncCloseData *data = user_data;
1521 data->result = g_object_ref (res);
1522 g_main_loop_quit (data->loop);
1526 * g_dbus_connection_close_sync:
1527 * @connection: A #GDBusConnection.
1528 * @cancellable: A #GCancellable or %NULL.
1529 * @error: Return location for error or %NULL.
1531 * Synchronously closees @connection. The calling thread is blocked
1532 * until this is done. See g_dbus_connection_close() for the
1533 * asynchronous version of this method and more details about what it
1536 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1541 g_dbus_connection_close_sync (GDBusConnection *connection,
1542 GCancellable *cancellable,
1547 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1548 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1552 if (check_unclosed (connection, 0, error))
1554 GMainContext *context;
1557 context = g_main_context_new ();
1558 g_main_context_push_thread_default (context);
1559 data.loop = g_main_loop_new (context, TRUE);
1562 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1563 g_main_loop_run (data.loop);
1564 ret = g_dbus_connection_close_finish (connection, data.result, error);
1566 g_object_unref (data.result);
1567 g_main_loop_unref (data.loop);
1568 g_main_context_pop_thread_default (context);
1569 g_main_context_unref (context);
1575 /* ---------------------------------------------------------------------------------------------------- */
1577 /* Can be called by any thread, with the connection lock held */
1579 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1580 GDBusMessage *message,
1581 GDBusSendMessageFlags flags,
1582 volatile guint32 *out_serial,
1587 guint32 serial_to_use;
1590 CONNECTION_ENSURE_LOCK (connection);
1592 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1593 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1595 /* TODO: check all necessary headers are present */
1600 if (out_serial != NULL)
1603 /* If we're in initable_init(), don't check for being initialized, to avoid
1604 * chicken-and-egg problems. initable_init() is responsible for setting up
1605 * our prerequisites (mainly connection->worker), and only calling us
1606 * from its own thread (so no memory barrier is needed).
1608 if (!check_unclosed (connection,
1609 (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
1613 blob = g_dbus_message_to_blob (message,
1615 connection->capabilities,
1620 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1621 serial_to_use = g_dbus_message_get_serial (message);
1623 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1628 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1631 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1634 g_assert_not_reached ();
1639 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1640 blob_size, serial_to_use, connection);
1641 g_printerr ("----\n");
1642 hexdump (blob, blob_size);
1643 g_printerr ("----\n");
1646 /* TODO: use connection->auth to encode the blob */
1648 if (out_serial != NULL)
1649 *out_serial = serial_to_use;
1651 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
1652 g_dbus_message_set_serial (message, serial_to_use);
1654 g_dbus_message_lock (message);
1655 _g_dbus_worker_send_message (connection->worker,
1659 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1670 * g_dbus_connection_send_message:
1671 * @connection: A #GDBusConnection.
1672 * @message: A #GDBusMessage
1673 * @flags: Flags affecting how the message is sent.
1674 * @out_serial: (out) (allow-none): Return location for serial number assigned
1675 * to @message when sending it or %NULL.
1676 * @error: Return location for error or %NULL.
1678 * Asynchronously sends @message to the peer represented by @connection.
1680 * Unless @flags contain the
1681 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1682 * will be assigned by @connection and set on @message via
1683 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1684 * serial number used will be written to this location prior to
1685 * submitting the message to the underlying transport.
1687 * If @connection is closed then the operation will fail with
1688 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1689 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1691 * See <xref linkend="gdbus-server"/> and <xref
1692 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1693 * low-level API to send and receive UNIX file descriptors.
1695 * Note that @message must be unlocked, unless @flags contain the
1696 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1698 * Returns: %TRUE if the message was well-formed and queued for
1699 * transmission, %FALSE if @error is set.
1704 g_dbus_connection_send_message (GDBusConnection *connection,
1705 GDBusMessage *message,
1706 GDBusSendMessageFlags flags,
1707 volatile guint32 *out_serial,
1712 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1713 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1714 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1715 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1717 CONNECTION_LOCK (connection);
1718 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1719 CONNECTION_UNLOCK (connection);
1723 /* ---------------------------------------------------------------------------------------------------- */
1727 volatile gint ref_count;
1728 GDBusConnection *connection;
1730 GSimpleAsyncResult *simple;
1732 GMainContext *main_context;
1734 GCancellable *cancellable;
1736 gulong cancellable_handler_id;
1738 GSource *timeout_source;
1743 /* Can be called from any thread with or without lock held */
1744 static SendMessageData *
1745 send_message_data_ref (SendMessageData *data)
1747 g_atomic_int_inc (&data->ref_count);
1751 /* Can be called from any thread with or without lock held */
1753 send_message_data_unref (SendMessageData *data)
1755 if (g_atomic_int_dec_and_test (&data->ref_count))
1757 g_assert (data->timeout_source == NULL);
1758 g_assert (data->simple == NULL);
1759 g_assert (data->cancellable_handler_id == 0);
1760 g_object_unref (data->connection);
1761 if (data->cancellable != NULL)
1762 g_object_unref (data->cancellable);
1763 g_main_context_unref (data->main_context);
1768 /* ---------------------------------------------------------------------------------------------------- */
1770 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1772 send_message_with_reply_deliver (SendMessageData *data, gboolean remove)
1774 CONNECTION_ENSURE_LOCK (data->connection);
1776 g_assert (!data->delivered);
1778 data->delivered = TRUE;
1780 g_simple_async_result_complete_in_idle (data->simple);
1781 g_object_unref (data->simple);
1782 data->simple = NULL;
1784 if (data->timeout_source != NULL)
1786 g_source_destroy (data->timeout_source);
1787 data->timeout_source = NULL;
1789 if (data->cancellable_handler_id > 0)
1791 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1792 data->cancellable_handler_id = 0;
1797 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
1798 GUINT_TO_POINTER (data->serial)));
1801 send_message_data_unref (data);
1804 /* ---------------------------------------------------------------------------------------------------- */
1806 /* Can be called from any thread with lock held */
1808 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1809 GDBusMessage *reply)
1811 if (data->delivered)
1814 g_simple_async_result_set_op_res_gpointer (data->simple,
1815 g_object_ref (reply),
1818 send_message_with_reply_deliver (data, TRUE);
1824 /* ---------------------------------------------------------------------------------------------------- */
1826 /* Called from a user thread, lock is not held */
1828 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1830 SendMessageData *data = user_data;
1832 CONNECTION_LOCK (data->connection);
1833 if (data->delivered)
1836 g_simple_async_result_set_error (data->simple,
1838 G_IO_ERROR_CANCELLED,
1839 _("Operation was cancelled"));
1841 send_message_with_reply_deliver (data, TRUE);
1844 CONNECTION_UNLOCK (data->connection);
1848 /* Can be called from any thread with or without lock held */
1850 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1853 SendMessageData *data = user_data;
1854 GSource *idle_source;
1856 /* postpone cancellation to idle handler since we may be called directly
1857 * via g_cancellable_connect() (e.g. holding lock)
1859 idle_source = g_idle_source_new ();
1860 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1861 g_source_set_callback (idle_source,
1862 send_message_with_reply_cancelled_idle_cb,
1863 send_message_data_ref (data),
1864 (GDestroyNotify) send_message_data_unref);
1865 g_source_attach (idle_source, data->main_context);
1866 g_source_unref (idle_source);
1869 /* ---------------------------------------------------------------------------------------------------- */
1871 /* Called from a user thread, lock is not held */
1873 send_message_with_reply_timeout_cb (gpointer user_data)
1875 SendMessageData *data = user_data;
1877 CONNECTION_LOCK (data->connection);
1878 if (data->delivered)
1881 g_simple_async_result_set_error (data->simple,
1883 G_IO_ERROR_TIMED_OUT,
1884 _("Timeout was reached"));
1886 send_message_with_reply_deliver (data, TRUE);
1889 CONNECTION_UNLOCK (data->connection);
1894 /* ---------------------------------------------------------------------------------------------------- */
1896 /* Called from a user thread, connection's lock is held */
1898 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1899 GDBusMessage *message,
1900 GDBusSendMessageFlags flags,
1902 volatile guint32 *out_serial,
1903 GCancellable *cancellable,
1904 GAsyncReadyCallback callback,
1907 GSimpleAsyncResult *simple;
1908 SendMessageData *data;
1910 volatile guint32 serial;
1914 if (out_serial == NULL)
1915 out_serial = &serial;
1917 if (timeout_msec == -1)
1918 timeout_msec = 25 * 1000;
1920 simple = g_simple_async_result_new (G_OBJECT (connection),
1923 g_dbus_connection_send_message_with_reply);
1925 if (g_cancellable_is_cancelled (cancellable))
1927 g_simple_async_result_set_error (simple,
1929 G_IO_ERROR_CANCELLED,
1930 _("Operation was cancelled"));
1931 g_simple_async_result_complete_in_idle (simple);
1932 g_object_unref (simple);
1937 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1939 g_simple_async_result_take_error (simple, error);
1940 g_simple_async_result_complete_in_idle (simple);
1941 g_object_unref (simple);
1945 data = g_new0 (SendMessageData, 1);
1946 data->ref_count = 1;
1947 data->connection = g_object_ref (connection);
1948 data->simple = simple;
1949 data->serial = *out_serial;
1950 data->main_context = g_main_context_ref_thread_default ();
1952 if (cancellable != NULL)
1954 data->cancellable = g_object_ref (cancellable);
1955 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1956 G_CALLBACK (send_message_with_reply_cancelled_cb),
1957 send_message_data_ref (data),
1958 (GDestroyNotify) send_message_data_unref);
1959 g_object_set_data_full (G_OBJECT (simple),
1961 g_object_ref (cancellable),
1962 (GDestroyNotify) g_object_unref);
1965 if (timeout_msec != G_MAXINT)
1967 data->timeout_source = g_timeout_source_new (timeout_msec);
1968 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1969 g_source_set_callback (data->timeout_source,
1970 send_message_with_reply_timeout_cb,
1971 send_message_data_ref (data),
1972 (GDestroyNotify) send_message_data_unref);
1973 g_source_attach (data->timeout_source, data->main_context);
1974 g_source_unref (data->timeout_source);
1977 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
1978 GUINT_TO_POINTER (*out_serial),
1986 * g_dbus_connection_send_message_with_reply:
1987 * @connection: A #GDBusConnection.
1988 * @message: A #GDBusMessage.
1989 * @flags: Flags affecting how the message is sent.
1990 * @timeout_msec: The timeout in milliseconds, -1 to use the default
1991 * timeout or %G_MAXINT for no timeout.
1992 * @out_serial: (out) (allow-none): Return location for serial number assigned
1993 * to @message when sending it or %NULL.
1994 * @cancellable: A #GCancellable or %NULL.
1995 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1996 * satisfied or %NULL if you don't care about the result.
1997 * @user_data: The data to pass to @callback.
1999 * Asynchronously sends @message to the peer represented by @connection.
2001 * Unless @flags contain the
2002 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2003 * will be assigned by @connection and set on @message via
2004 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2005 * serial number used will be written to this location prior to
2006 * submitting the message to the underlying transport.
2008 * If @connection is closed then the operation will fail with
2009 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2010 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2011 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2013 * This is an asynchronous method. When the operation is finished, @callback will be invoked
2014 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
2015 * of the thread you are calling this method from. You can then call
2016 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
2017 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
2019 * Note that @message must be unlocked, unless @flags contain the
2020 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2022 * See <xref linkend="gdbus-server"/> and <xref
2023 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2024 * low-level API to send and receive UNIX file descriptors.
2029 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
2030 GDBusMessage *message,
2031 GDBusSendMessageFlags flags,
2033 volatile guint32 *out_serial,
2034 GCancellable *cancellable,
2035 GAsyncReadyCallback callback,
2038 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2039 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2040 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2041 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2043 CONNECTION_LOCK (connection);
2044 g_dbus_connection_send_message_with_reply_unlocked (connection,
2052 CONNECTION_UNLOCK (connection);
2056 * g_dbus_connection_send_message_with_reply_finish:
2057 * @connection: a #GDBusConnection
2058 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
2059 * @error: Return location for error or %NULL.
2061 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2063 * Note that @error is only set if a local in-process error
2064 * occurred. That is to say that the returned #GDBusMessage object may
2065 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2066 * g_dbus_message_to_gerror() to transcode this to a #GError.
2068 * See <xref linkend="gdbus-server"/> and <xref
2069 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2070 * low-level API to send and receive UNIX file descriptors.
2072 * Returns: (transfer full): A locked #GDBusMessage or %NULL if @error is set.
2077 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2081 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2082 GDBusMessage *reply;
2083 GCancellable *cancellable;
2085 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2086 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2090 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
2092 if (g_simple_async_result_propagate_error (simple, error))
2095 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
2096 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
2097 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
2099 g_object_unref (reply);
2101 g_set_error_literal (error,
2103 G_IO_ERROR_CANCELLED,
2104 _("Operation was cancelled"));
2110 /* ---------------------------------------------------------------------------------------------------- */
2115 GMainContext *context;
2117 } SendMessageSyncData;
2119 /* Called from a user thread, lock is not held */
2121 send_message_with_reply_sync_cb (GDBusConnection *connection,
2125 SendMessageSyncData *data = user_data;
2126 data->res = g_object_ref (res);
2127 g_main_loop_quit (data->loop);
2131 * g_dbus_connection_send_message_with_reply_sync:
2132 * @connection: A #GDBusConnection.
2133 * @message: A #GDBusMessage.
2134 * @flags: Flags affecting how the message is sent.
2135 * @timeout_msec: The timeout in milliseconds, -1 to use the default
2136 * timeout or %G_MAXINT for no timeout.
2137 * @out_serial: (out) (allow-none): Return location for serial number assigned
2138 * to @message when sending it or %NULL.
2139 * @cancellable: A #GCancellable or %NULL.
2140 * @error: Return location for error or %NULL.
2142 * Synchronously sends @message to the peer represented by @connection
2143 * and blocks the calling thread until a reply is received or the
2144 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2145 * for the asynchronous version of this method.
2147 * Unless @flags contain the
2148 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2149 * will be assigned by @connection and set on @message via
2150 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2151 * serial number used will be written to this location prior to
2152 * submitting the message to the underlying transport.
2154 * If @connection is closed then the operation will fail with
2155 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2156 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2157 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2159 * Note that @error is only set if a local in-process error
2160 * occurred. That is to say that the returned #GDBusMessage object may
2161 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2162 * g_dbus_message_to_gerror() to transcode this to a #GError.
2164 * See <xref linkend="gdbus-server"/> and <xref
2165 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2166 * low-level API to send and receive UNIX file descriptors.
2168 * Note that @message must be unlocked, unless @flags contain the
2169 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2171 * Returns: (transfer full): A locked #GDBusMessage that is the reply to @message or %NULL if @error is set.
2176 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2177 GDBusMessage *message,
2178 GDBusSendMessageFlags flags,
2180 volatile guint32 *out_serial,
2181 GCancellable *cancellable,
2184 SendMessageSyncData *data;
2185 GDBusMessage *reply;
2187 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2188 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2189 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2190 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2191 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2193 data = g_new0 (SendMessageSyncData, 1);
2194 data->context = g_main_context_new ();
2195 data->loop = g_main_loop_new (data->context, FALSE);
2197 g_main_context_push_thread_default (data->context);
2199 g_dbus_connection_send_message_with_reply (connection,
2205 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2207 g_main_loop_run (data->loop);
2208 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2212 g_main_context_pop_thread_default (data->context);
2214 g_main_context_unref (data->context);
2215 g_main_loop_unref (data->loop);
2216 g_object_unref (data->res);
2222 /* ---------------------------------------------------------------------------------------------------- */
2226 GDBusMessageFilterFunction func;
2233 GDBusMessageFilterFunction filter_function;
2235 GDestroyNotify user_data_free_func;
2238 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2240 on_worker_message_received (GDBusWorker *worker,
2241 GDBusMessage *message,
2244 GDBusConnection *connection;
2245 FilterCallback *filters;
2250 G_LOCK (message_bus_lock);
2251 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2254 G_UNLOCK (message_bus_lock);
2257 connection = G_DBUS_CONNECTION (user_data);
2258 g_object_ref (connection);
2259 G_UNLOCK (message_bus_lock);
2261 //g_debug ("in on_worker_message_received");
2263 g_object_ref (message);
2264 g_dbus_message_lock (message);
2266 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2268 /* First collect the set of callback functions */
2269 CONNECTION_LOCK (connection);
2270 num_filters = connection->filters->len;
2271 filters = g_new0 (FilterCallback, num_filters);
2272 for (n = 0; n < num_filters; n++)
2274 FilterData *data = connection->filters->pdata[n];
2275 filters[n].func = data->filter_function;
2276 filters[n].user_data = data->user_data;
2278 CONNECTION_UNLOCK (connection);
2280 /* then call the filters in order (without holding the lock) */
2281 for (n = 0; n < num_filters; n++)
2283 message = filters[n].func (connection,
2286 filters[n].user_data);
2287 if (message == NULL)
2289 g_dbus_message_lock (message);
2292 /* Standard dispatch unless the filter ate the message - no need to
2293 * do anything if the message was altered
2295 if (message != NULL)
2297 GDBusMessageType message_type;
2299 message_type = g_dbus_message_get_message_type (message);
2300 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2302 guint32 reply_serial;
2303 SendMessageData *send_message_data;
2305 reply_serial = g_dbus_message_get_reply_serial (message);
2306 CONNECTION_LOCK (connection);
2307 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2308 GUINT_TO_POINTER (reply_serial));
2309 if (send_message_data != NULL)
2311 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2312 send_message_data_deliver_reply_unlocked (send_message_data, message);
2316 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2318 CONNECTION_UNLOCK (connection);
2320 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2322 CONNECTION_LOCK (connection);
2323 distribute_signals (connection, message);
2324 CONNECTION_UNLOCK (connection);
2326 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2328 CONNECTION_LOCK (connection);
2329 distribute_method_call (connection, message);
2330 CONNECTION_UNLOCK (connection);
2334 if (message != NULL)
2335 g_object_unref (message);
2336 g_object_unref (connection);
2340 /* Called in GDBusWorker's thread, lock is not held */
2341 static GDBusMessage *
2342 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2343 GDBusMessage *message,
2346 GDBusConnection *connection;
2347 FilterCallback *filters;
2352 G_LOCK (message_bus_lock);
2353 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2356 G_UNLOCK (message_bus_lock);
2359 connection = G_DBUS_CONNECTION (user_data);
2360 g_object_ref (connection);
2361 G_UNLOCK (message_bus_lock);
2363 //g_debug ("in on_worker_message_about_to_be_sent");
2365 /* First collect the set of callback functions */
2366 CONNECTION_LOCK (connection);
2367 num_filters = connection->filters->len;
2368 filters = g_new0 (FilterCallback, num_filters);
2369 for (n = 0; n < num_filters; n++)
2371 FilterData *data = connection->filters->pdata[n];
2372 filters[n].func = data->filter_function;
2373 filters[n].user_data = data->user_data;
2375 CONNECTION_UNLOCK (connection);
2377 /* then call the filters in order (without holding the lock) */
2378 for (n = 0; n < num_filters; n++)
2380 g_dbus_message_lock (message);
2381 message = filters[n].func (connection,
2384 filters[n].user_data);
2385 if (message == NULL)
2389 g_object_unref (connection);
2395 /* called with connection lock held, in GDBusWorker thread */
2397 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2399 SendMessageData *data = value;
2401 if (data->delivered)
2404 g_simple_async_result_set_error (data->simple,
2407 _("The connection is closed"));
2409 /* Ask send_message_with_reply_deliver not to remove the element from the
2410 * hash table - we're in the middle of a foreach; that would be unsafe.
2411 * Instead, return TRUE from this function so that it gets removed safely.
2413 send_message_with_reply_deliver (data, FALSE);
2417 /* Called in GDBusWorker's thread - we must not block - without lock held */
2419 on_worker_closed (GDBusWorker *worker,
2420 gboolean remote_peer_vanished,
2424 GDBusConnection *connection;
2426 guint old_atomic_flags;
2428 G_LOCK (message_bus_lock);
2429 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2432 G_UNLOCK (message_bus_lock);
2435 connection = G_DBUS_CONNECTION (user_data);
2436 g_object_ref (connection);
2437 G_UNLOCK (message_bus_lock);
2439 //g_debug ("in on_worker_closed: %s", error->message);
2441 CONNECTION_LOCK (connection);
2442 /* Even though this is atomic, we do it inside the lock to avoid breaking
2443 * assumptions in remove_match_rule(). We'd need the lock in a moment
2444 * anyway, so, no loss.
2446 old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
2448 if (!(old_atomic_flags & FLAG_CLOSED))
2450 g_hash_table_foreach_remove (connection->map_method_serial_to_send_message_data, cancel_method_on_close, NULL);
2451 schedule_closed_unlocked (connection, remote_peer_vanished, error);
2453 CONNECTION_UNLOCK (connection);
2455 g_object_unref (connection);
2458 /* ---------------------------------------------------------------------------------------------------- */
2460 /* Determines the biggest set of capabilities we can support on this
2463 * Called with the init_lock held.
2465 static GDBusCapabilityFlags
2466 get_offered_capabilities_max (GDBusConnection *connection)
2468 GDBusCapabilityFlags ret;
2469 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2471 if (G_IS_UNIX_CONNECTION (connection->stream))
2472 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2477 /* Called in a user thread, lock is not held */
2479 initable_init (GInitable *initable,
2480 GCancellable *cancellable,
2483 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2486 /* This method needs to be idempotent to work with the singleton
2487 * pattern. See the docs for g_initable_init(). We implement this by
2490 * Unfortunately we can't use the main lock since the on_worker_*()
2491 * callbacks above needs the lock during initialization (for message
2492 * bus connections we do a synchronous Hello() call on the bus).
2494 g_mutex_lock (&connection->init_lock);
2498 /* Make this a no-op if we're already initialized (successfully or
2501 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
2503 ret = (connection->initialization_error == NULL);
2507 /* Because of init_lock, we can't get here twice in different threads */
2508 g_assert (connection->initialization_error == NULL);
2510 /* The user can pass multiple (but mutally exclusive) construct
2513 * - stream (of type GIOStream)
2514 * - address (of type gchar*)
2516 * At the end of the day we end up with a non-NULL GIOStream
2517 * object in connection->stream.
2519 if (connection->address != NULL)
2521 g_assert (connection->stream == NULL);
2523 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2524 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2526 g_set_error_literal (&connection->initialization_error,
2528 G_IO_ERROR_INVALID_ARGUMENT,
2529 _("Unsupported flags encountered when constructing a client-side connection"));
2533 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2534 NULL, /* TODO: out_guid */
2536 &connection->initialization_error);
2537 if (connection->stream == NULL)
2540 else if (connection->stream != NULL)
2546 g_assert_not_reached ();
2549 /* Authenticate the connection */
2550 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2552 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2553 g_assert (connection->guid != NULL);
2554 connection->auth = _g_dbus_auth_new (connection->stream);
2555 if (!_g_dbus_auth_run_server (connection->auth,
2556 connection->authentication_observer,
2558 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2559 get_offered_capabilities_max (connection),
2560 &connection->capabilities,
2561 &connection->credentials,
2563 &connection->initialization_error))
2566 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2568 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2569 g_assert (connection->guid == NULL);
2570 connection->auth = _g_dbus_auth_new (connection->stream);
2571 connection->guid = _g_dbus_auth_run_client (connection->auth,
2572 get_offered_capabilities_max (connection),
2573 &connection->capabilities,
2575 &connection->initialization_error);
2576 if (connection->guid == NULL)
2580 if (connection->authentication_observer != NULL)
2582 g_object_unref (connection->authentication_observer);
2583 connection->authentication_observer = NULL;
2586 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2588 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2591 /* We want all IO operations to be non-blocking since they happen in
2592 * the worker thread which is shared by _all_ connections.
2594 if (G_IS_SOCKET_CONNECTION (connection->stream))
2596 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2600 G_LOCK (message_bus_lock);
2601 if (alive_connections == NULL)
2602 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2603 g_hash_table_insert (alive_connections, connection, connection);
2604 G_UNLOCK (message_bus_lock);
2606 connection->worker = _g_dbus_worker_new (connection->stream,
2607 connection->capabilities,
2608 ((connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) != 0),
2609 on_worker_message_received,
2610 on_worker_message_about_to_be_sent,
2614 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2615 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2617 GVariant *hello_result;
2619 /* we could lift this restriction by adding code in gdbusprivate.c */
2620 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2622 g_set_error_literal (&connection->initialization_error,
2625 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2629 hello_result = g_dbus_connection_call_sync (connection,
2630 "org.freedesktop.DBus", /* name */
2631 "/org/freedesktop/DBus", /* path */
2632 "org.freedesktop.DBus", /* interface */
2634 NULL, /* parameters */
2635 G_VARIANT_TYPE ("(s)"),
2636 CALL_FLAGS_INITIALIZING,
2638 NULL, /* TODO: cancellable */
2639 &connection->initialization_error);
2640 if (hello_result == NULL)
2643 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2644 g_variant_unref (hello_result);
2645 //g_debug ("unique name is `%s'", connection->bus_unique_name);
2652 g_assert (connection->initialization_error != NULL);
2653 g_propagate_error (error, g_error_copy (connection->initialization_error));
2656 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
2657 g_mutex_unlock (&connection->init_lock);
2663 initable_iface_init (GInitableIface *initable_iface)
2665 initable_iface->init = initable_init;
2668 /* ---------------------------------------------------------------------------------------------------- */
2671 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2676 /* ---------------------------------------------------------------------------------------------------- */
2679 * g_dbus_connection_new:
2680 * @stream: A #GIOStream.
2681 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2682 * @flags: Flags describing how to make the connection.
2683 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2684 * @cancellable: A #GCancellable or %NULL.
2685 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2686 * @user_data: The data to pass to @callback.
2688 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2689 * with the end represented by @stream.
2691 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2692 * will be put into non-blocking mode.
2694 * The D-Bus connection will interact with @stream from a worker thread.
2695 * As a result, the caller should not interact with @stream after this
2696 * method has been called, except by calling g_object_unref() on it.
2698 * If @observer is not %NULL it may be used to control the
2699 * authentication process.
2701 * When the operation is finished, @callback will be invoked. You can
2702 * then call g_dbus_connection_new_finish() to get the result of the
2705 * This is a asynchronous failable constructor. See
2706 * g_dbus_connection_new_sync() for the synchronous
2712 g_dbus_connection_new (GIOStream *stream,
2714 GDBusConnectionFlags flags,
2715 GDBusAuthObserver *observer,
2716 GCancellable *cancellable,
2717 GAsyncReadyCallback callback,
2720 g_return_if_fail (G_IS_IO_STREAM (stream));
2721 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2729 "authentication-observer", observer,
2734 * g_dbus_connection_new_finish:
2735 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2736 * @error: Return location for error or %NULL.
2738 * Finishes an operation started with g_dbus_connection_new().
2740 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2745 g_dbus_connection_new_finish (GAsyncResult *res,
2749 GObject *source_object;
2751 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2752 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2754 source_object = g_async_result_get_source_object (res);
2755 g_assert (source_object != NULL);
2756 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2759 g_object_unref (source_object);
2761 return G_DBUS_CONNECTION (object);
2767 * g_dbus_connection_new_sync:
2768 * @stream: A #GIOStream.
2769 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2770 * @flags: Flags describing how to make the connection.
2771 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2772 * @cancellable: A #GCancellable or %NULL.
2773 * @error: Return location for error or %NULL.
2775 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2776 * with the end represented by @stream.
2778 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2779 * will be put into non-blocking mode.
2781 * The D-Bus connection will interact with @stream from a worker thread.
2782 * As a result, the caller should not interact with @stream after this
2783 * method has been called, except by calling g_object_unref() on it.
2785 * If @observer is not %NULL it may be used to control the
2786 * authentication process.
2788 * This is a synchronous failable constructor. See
2789 * g_dbus_connection_new() for the asynchronous version.
2791 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2796 g_dbus_connection_new_sync (GIOStream *stream,
2798 GDBusConnectionFlags flags,
2799 GDBusAuthObserver *observer,
2800 GCancellable *cancellable,
2803 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2804 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2805 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2811 "authentication-observer", observer,
2815 /* ---------------------------------------------------------------------------------------------------- */
2818 * g_dbus_connection_new_for_address:
2819 * @address: A D-Bus address.
2820 * @flags: Flags describing how to make the connection.
2821 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2822 * @cancellable: A #GCancellable or %NULL.
2823 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2824 * @user_data: The data to pass to @callback.
2826 * Asynchronously connects and sets up a D-Bus client connection for
2827 * exchanging D-Bus messages with an endpoint specified by @address
2828 * which must be in the D-Bus address format.
2830 * This constructor can only be used to initiate client-side
2831 * connections - use g_dbus_connection_new() if you need to act as the
2832 * server. In particular, @flags cannot contain the
2833 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2834 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2836 * When the operation is finished, @callback will be invoked. You can
2837 * then call g_dbus_connection_new_finish() to get the result of the
2840 * If @observer is not %NULL it may be used to control the
2841 * authentication process.
2843 * This is a asynchronous failable constructor. See
2844 * g_dbus_connection_new_for_address_sync() for the synchronous
2850 g_dbus_connection_new_for_address (const gchar *address,
2851 GDBusConnectionFlags flags,
2852 GDBusAuthObserver *observer,
2853 GCancellable *cancellable,
2854 GAsyncReadyCallback callback,
2857 g_return_if_fail (address != NULL);
2858 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2865 "authentication-observer", observer,
2870 * g_dbus_connection_new_for_address_finish:
2871 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2872 * @error: Return location for error or %NULL.
2874 * Finishes an operation started with g_dbus_connection_new_for_address().
2876 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2881 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2885 GObject *source_object;
2887 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2888 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2890 source_object = g_async_result_get_source_object (res);
2891 g_assert (source_object != NULL);
2892 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2895 g_object_unref (source_object);
2897 return G_DBUS_CONNECTION (object);
2903 * g_dbus_connection_new_for_address_sync:
2904 * @address: A D-Bus address.
2905 * @flags: Flags describing how to make the connection.
2906 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2907 * @cancellable: A #GCancellable or %NULL.
2908 * @error: Return location for error or %NULL.
2910 * Synchronously connects and sets up a D-Bus client connection for
2911 * exchanging D-Bus messages with an endpoint specified by @address
2912 * which must be in the D-Bus address format.
2914 * This constructor can only be used to initiate client-side
2915 * connections - use g_dbus_connection_new_sync() if you need to act
2916 * as the server. In particular, @flags cannot contain the
2917 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2918 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2920 * This is a synchronous failable constructor. See
2921 * g_dbus_connection_new_for_address() for the asynchronous version.
2923 * If @observer is not %NULL it may be used to control the
2924 * authentication process.
2926 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2931 g_dbus_connection_new_for_address_sync (const gchar *address,
2932 GDBusConnectionFlags flags,
2933 GDBusAuthObserver *observer,
2934 GCancellable *cancellable,
2937 g_return_val_if_fail (address != NULL, NULL);
2938 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2939 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2944 "authentication-observer", observer,
2948 /* ---------------------------------------------------------------------------------------------------- */
2951 * g_dbus_connection_set_exit_on_close:
2952 * @connection: A #GDBusConnection.
2953 * @exit_on_close: Whether the process should be terminated
2954 * when @connection is closed by the remote peer.
2956 * Sets whether the process should be terminated when @connection is
2957 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2960 * Note that this function should be used with care. Most modern UNIX
2961 * desktops tie the notion of a user session the session bus, and expect
2962 * all of a users applications to quit when their bus connection goes away.
2963 * If you are setting @exit_on_close to %FALSE for the shared session
2964 * bus connection, you should make sure that your application exits
2965 * when the user session ends.
2970 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2971 gboolean exit_on_close)
2973 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2976 g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
2978 g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
2983 * g_dbus_connection_get_exit_on_close:
2984 * @connection: A #GDBusConnection.
2986 * Gets whether the process is terminated when @connection is
2987 * closed by the remote peer. See
2988 * #GDBusConnection:exit-on-close for more details.
2990 * Returns: Whether the process is terminated when @connection is
2991 * closed by the remote peer.
2996 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2998 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3000 if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
3007 * g_dbus_connection_get_guid:
3008 * @connection: A #GDBusConnection.
3010 * The GUID of the peer performing the role of server when
3011 * authenticating. See #GDBusConnection:guid for more details.
3013 * Returns: The GUID. Do not free this string, it is owned by
3019 g_dbus_connection_get_guid (GDBusConnection *connection)
3021 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3022 return connection->guid;
3026 * g_dbus_connection_get_unique_name:
3027 * @connection: A #GDBusConnection.
3029 * Gets the unique name of @connection as assigned by the message
3030 * bus. This can also be used to figure out if @connection is a
3031 * message bus connection.
3033 * Returns: The unique name or %NULL if @connection is not a message
3034 * bus connection. Do not free this string, it is owned by
3040 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3042 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3044 /* do not use g_return_val_if_fail(), we want the memory barrier */
3045 if (!check_initialized (connection))
3048 return connection->bus_unique_name;
3052 * g_dbus_connection_get_peer_credentials:
3053 * @connection: A #GDBusConnection.
3055 * Gets the credentials of the authenticated peer. This will always
3056 * return %NULL unless @connection acted as a server
3057 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3058 * when set up and the client passed credentials as part of the
3059 * authentication process.
3061 * In a message bus setup, the message bus is always the server and
3062 * each application is a client. So this method will always return
3063 * %NULL for message bus clients.
3065 * Returns: (transfer none): A #GCredentials or %NULL if not available. Do not free
3066 * this object, it is owned by @connection.
3071 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3073 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3075 /* do not use g_return_val_if_fail(), we want the memory barrier */
3076 if (!check_initialized (connection))
3079 return connection->credentials;
3082 /* ---------------------------------------------------------------------------------------------------- */
3084 static guint _global_filter_id = 1;
3087 * g_dbus_connection_add_filter:
3088 * @connection: A #GDBusConnection.
3089 * @filter_function: A filter function.
3090 * @user_data: User data to pass to @filter_function.
3091 * @user_data_free_func: Function to free @user_data with when filter
3092 * is removed or %NULL.
3094 * Adds a message filter. Filters are handlers that are run on all
3095 * incoming and outgoing messages, prior to standard dispatch. Filters
3096 * are run in the order that they were added. The same handler can be
3097 * added as a filter more than once, in which case it will be run more
3098 * than once. Filters added during a filter callback won't be run on
3099 * the message being processed. Filter functions are allowed to modify
3100 * and even drop messages.
3102 * Note that filters are run in a dedicated message handling thread so
3103 * they can't block and, generally, can't do anything but signal a
3104 * worker thread. Also note that filters are rarely needed - use API
3105 * such as g_dbus_connection_send_message_with_reply(),
3106 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3108 * If a filter consumes an incoming message the message is not
3109 * dispatched anywhere else - not even the standard dispatch machinery
3110 * (that API such as g_dbus_connection_signal_subscribe() and
3111 * g_dbus_connection_send_message_with_reply() relies on) will see the
3112 * message. Similary, if a filter consumes an outgoing message, the
3113 * message will not be sent to the other peer.
3115 * Returns: A filter identifier that can be used with
3116 * g_dbus_connection_remove_filter().
3121 g_dbus_connection_add_filter (GDBusConnection *connection,
3122 GDBusMessageFilterFunction filter_function,
3124 GDestroyNotify user_data_free_func)
3128 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3129 g_return_val_if_fail (filter_function != NULL, 0);
3130 g_return_val_if_fail (check_initialized (connection), 0);
3132 CONNECTION_LOCK (connection);
3133 data = g_new0 (FilterData, 1);
3134 data->id = _global_filter_id++; /* TODO: overflow etc. */
3135 data->filter_function = filter_function;
3136 data->user_data = user_data;
3137 data->user_data_free_func = user_data_free_func;
3138 g_ptr_array_add (connection->filters, data);
3139 CONNECTION_UNLOCK (connection);
3144 /* only called from finalize(), removes all filters */
3146 purge_all_filters (GDBusConnection *connection)
3149 for (n = 0; n < connection->filters->len; n++)
3151 FilterData *data = connection->filters->pdata[n];
3152 if (data->user_data_free_func != NULL)
3153 data->user_data_free_func (data->user_data);
3159 * g_dbus_connection_remove_filter:
3160 * @connection: a #GDBusConnection
3161 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3168 g_dbus_connection_remove_filter (GDBusConnection *connection,
3172 FilterData *to_destroy;
3174 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3175 g_return_if_fail (check_initialized (connection));
3177 CONNECTION_LOCK (connection);
3179 for (n = 0; n < connection->filters->len; n++)
3181 FilterData *data = connection->filters->pdata[n];
3182 if (data->id == filter_id)
3184 g_ptr_array_remove_index (connection->filters, n);
3189 CONNECTION_UNLOCK (connection);
3191 /* do free without holding lock */
3192 if (to_destroy != NULL)
3194 if (to_destroy->user_data_free_func != NULL)
3195 to_destroy->user_data_free_func (to_destroy->user_data);
3196 g_free (to_destroy);
3200 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3204 /* ---------------------------------------------------------------------------------------------------- */
3210 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3211 gchar *interface_name;
3215 GArray *subscribers;
3220 GDBusSignalCallback callback;
3222 GDestroyNotify user_data_free_func;
3224 GMainContext *context;
3228 signal_data_free (SignalData *signal_data)
3230 g_free (signal_data->rule);
3231 g_free (signal_data->sender);
3232 g_free (signal_data->sender_unique_name);
3233 g_free (signal_data->interface_name);
3234 g_free (signal_data->member);
3235 g_free (signal_data->object_path);
3236 g_free (signal_data->arg0);
3237 g_array_free (signal_data->subscribers, TRUE);
3238 g_free (signal_data);
3242 args_to_rule (const gchar *sender,
3243 const gchar *interface_name,
3244 const gchar *member,
3245 const gchar *object_path,
3251 rule = g_string_new ("type='signal'");
3253 g_string_prepend_c (rule, '-');
3255 g_string_append_printf (rule, ",sender='%s'", sender);
3256 if (interface_name != NULL)
3257 g_string_append_printf (rule, ",interface='%s'", interface_name);
3259 g_string_append_printf (rule, ",member='%s'", member);
3260 if (object_path != NULL)
3261 g_string_append_printf (rule, ",path='%s'", object_path);
3263 g_string_append_printf (rule, ",arg0='%s'", arg0);
3265 return g_string_free (rule, FALSE);
3268 static guint _global_subscriber_id = 1;
3269 static guint _global_registration_id = 1;
3270 static guint _global_subtree_registration_id = 1;
3272 /* ---------------------------------------------------------------------------------------------------- */
3274 /* Called in a user thread, lock is held */
3276 add_match_rule (GDBusConnection *connection,
3277 const gchar *match_rule)
3280 GDBusMessage *message;
3282 if (match_rule[0] == '-')
3285 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3286 "/org/freedesktop/DBus", /* path */
3287 "org.freedesktop.DBus", /* interface */
3289 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3291 if (!g_dbus_connection_send_message_unlocked (connection,
3293 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3297 g_critical ("Error while sending AddMatch() message: %s", error->message);
3298 g_error_free (error);
3300 g_object_unref (message);
3303 /* ---------------------------------------------------------------------------------------------------- */
3305 /* Called in a user thread, lock is held */
3307 remove_match_rule (GDBusConnection *connection,
3308 const gchar *match_rule)
3311 GDBusMessage *message;
3313 if (match_rule[0] == '-')
3316 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3317 "/org/freedesktop/DBus", /* path */
3318 "org.freedesktop.DBus", /* interface */
3320 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3323 if (!g_dbus_connection_send_message_unlocked (connection,
3325 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3329 /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
3330 * critical; but we're holding the lock, and our caller checked whether
3331 * we were already closed, so we can't get that error.
3333 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3334 g_error_free (error);
3336 g_object_unref (message);
3339 /* ---------------------------------------------------------------------------------------------------- */
3342 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3344 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3345 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3346 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3347 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3348 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3351 /* ---------------------------------------------------------------------------------------------------- */
3354 * g_dbus_connection_signal_subscribe:
3355 * @connection: A #GDBusConnection.
3356 * @sender: (allow-none): Sender name to match on (unique or well-known name)
3357 * or %NULL to listen from all senders.
3358 * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3359 * match on all interfaces.
3360 * @member: (allow-none): D-Bus signal name to match on or %NULL to match on all signals.
3361 * @object_path: (allow-none): Object path to match on or %NULL to match on all object paths.
3362 * @arg0: (allow-none): Contents of first string argument to match on or %NULL
3363 * to match on all kinds of arguments.
3364 * @flags: Flags describing how to subscribe to the signal (currently unused).
3365 * @callback: Callback to invoke when there is a signal matching the requested data.
3366 * @user_data: User data to pass to @callback.
3367 * @user_data_free_func: (allow-none): Function to free @user_data with when
3368 * subscription is removed or %NULL.
3370 * Subscribes to signals on @connection and invokes @callback with a
3371 * whenever the signal is received. Note that @callback
3372 * will be invoked in the <link
3373 * linkend="g-main-context-push-thread-default">thread-default main
3374 * loop</link> of the thread you are calling this method from.
3376 * If @connection is not a message bus connection, @sender must be
3379 * If @sender is a well-known name note that @callback is invoked with
3380 * the unique name for the owner of @sender, not the well-known name
3381 * as one would expect. This is because the message bus rewrites the
3382 * name. As such, to avoid certain race conditions, users should be
3383 * tracking the name owner of the well-known name and use that when
3384 * processing the received signal.
3386 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
3391 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3392 const gchar *sender,
3393 const gchar *interface_name,
3394 const gchar *member,
3395 const gchar *object_path,
3397 GDBusSignalFlags flags,
3398 GDBusSignalCallback callback,
3400 GDestroyNotify user_data_free_func)
3403 SignalData *signal_data;
3404 SignalSubscriber subscriber;
3405 GPtrArray *signal_data_array;
3406 const gchar *sender_unique_name;
3408 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3409 * an OOM condition. We might want to change that but that would involve making
3410 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3411 * handle that. And there's really no sensible way of handling this short of retrying
3412 * to add the match rule... and then there's the little thing that, hey, maybe there's
3413 * a reason the bus in an OOM condition.
3415 * Doable, but not really sure it's worth it...
3418 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3419 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3420 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3421 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3422 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3423 g_return_val_if_fail (callback != NULL, 0);
3424 g_return_val_if_fail (check_initialized (connection), 0);
3426 CONNECTION_LOCK (connection);
3428 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3429 * with a '-' character to prefix the rule (which will otherwise be
3432 * This allows us to hash the rule and do our lifecycle tracking in
3433 * the usual way, but the '-' prevents the match rule from ever
3434 * actually being send to the bus (either for add or remove).
3436 rule = args_to_rule (sender, interface_name, member, object_path, arg0,
3437 (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE) != 0);
3439 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3440 sender_unique_name = sender;
3442 sender_unique_name = "";
3444 subscriber.callback = callback;
3445 subscriber.user_data = user_data;
3446 subscriber.user_data_free_func = user_data_free_func;
3447 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3448 subscriber.context = g_main_context_ref_thread_default ();
3450 /* see if we've already have this rule */
3451 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3452 if (signal_data != NULL)
3454 g_array_append_val (signal_data->subscribers, subscriber);
3459 signal_data = g_new0 (SignalData, 1);
3460 signal_data->rule = rule;
3461 signal_data->sender = g_strdup (sender);
3462 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3463 signal_data->interface_name = g_strdup (interface_name);
3464 signal_data->member = g_strdup (member);
3465 signal_data->object_path = g_strdup (object_path);
3466 signal_data->arg0 = g_strdup (arg0);
3467 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3468 g_array_append_val (signal_data->subscribers, subscriber);
3470 g_hash_table_insert (connection->map_rule_to_signal_data,
3474 /* Add the match rule to the bus...
3476 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3477 * always send such messages to us.
3479 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3481 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3482 add_match_rule (connection, signal_data->rule);
3485 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3486 signal_data->sender_unique_name);
3487 if (signal_data_array == NULL)
3489 signal_data_array = g_ptr_array_new ();
3490 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3491 g_strdup (signal_data->sender_unique_name),
3494 g_ptr_array_add (signal_data_array, signal_data);
3497 g_hash_table_insert (connection->map_id_to_signal_data,
3498 GUINT_TO_POINTER (subscriber.id),
3501 CONNECTION_UNLOCK (connection);
3503 return subscriber.id;
3506 /* ---------------------------------------------------------------------------------------------------- */
3508 /* called in any thread */
3509 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3511 unsubscribe_id_internal (GDBusConnection *connection,
3512 guint subscription_id,
3513 GArray *out_removed_subscribers)
3515 SignalData *signal_data;
3516 GPtrArray *signal_data_array;
3519 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3520 GUINT_TO_POINTER (subscription_id));
3521 if (signal_data == NULL)
3523 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3527 for (n = 0; n < signal_data->subscribers->len; n++)
3529 SignalSubscriber *subscriber;
3531 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3532 if (subscriber->id != subscription_id)
3535 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3536 GUINT_TO_POINTER (subscription_id)));
3537 g_array_append_val (out_removed_subscribers, *subscriber);
3538 g_array_remove_index (signal_data->subscribers, n);
3540 if (signal_data->subscribers->len == 0)
3542 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3544 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3545 signal_data->sender_unique_name);
3546 g_warn_if_fail (signal_data_array != NULL);
3547 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3549 if (signal_data_array->len == 0)
3551 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3552 signal_data->sender_unique_name));
3555 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3556 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
3557 !is_signal_data_for_name_lost_or_acquired (signal_data) &&
3558 !g_dbus_connection_is_closed (connection) &&
3559 !connection->finalizing)
3561 /* The check for g_dbus_connection_is_closed() means that
3562 * sending the RemoveMatch message can't fail with
3563 * G_IO_ERROR_CLOSED, because we're holding the lock,
3564 * so on_worker_closed() can't happen between the check we just
3565 * did, and releasing the lock later.
3567 remove_match_rule (connection, signal_data->rule);
3570 signal_data_free (signal_data);
3576 g_assert_not_reached ();
3583 * g_dbus_connection_signal_unsubscribe:
3584 * @connection: A #GDBusConnection.
3585 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
3587 * Unsubscribes from signals.
3592 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3593 guint subscription_id)
3595 GArray *subscribers;
3598 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3599 g_return_if_fail (check_initialized (connection));
3601 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3603 CONNECTION_LOCK (connection);
3604 unsubscribe_id_internal (connection,
3607 CONNECTION_UNLOCK (connection);
3610 g_assert (subscribers->len == 0 || subscribers->len == 1);
3612 /* call GDestroyNotify without lock held */
3613 for (n = 0; n < subscribers->len; n++)
3615 SignalSubscriber *subscriber;
3616 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3617 call_destroy_notify (subscriber->context,
3618 subscriber->user_data_free_func,
3619 subscriber->user_data);
3620 g_main_context_unref (subscriber->context);
3623 g_array_free (subscribers, TRUE);
3626 /* ---------------------------------------------------------------------------------------------------- */
3630 guint subscription_id;
3631 GDBusSignalCallback callback;
3633 GDBusMessage *message;
3634 GDBusConnection *connection;
3635 const gchar *sender;
3637 const gchar *interface;
3638 const gchar *member;
3641 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3645 emit_signal_instance_in_idle_cb (gpointer data)
3647 SignalInstance *signal_instance = data;
3648 GVariant *parameters;
3649 gboolean has_subscription;
3651 parameters = g_dbus_message_get_body (signal_instance->message);
3652 if (parameters == NULL)
3654 parameters = g_variant_new ("()");
3655 g_variant_ref_sink (parameters);
3659 g_variant_ref_sink (parameters);
3663 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3664 signal_instance->subscription_id,
3665 signal_instance->sender,
3666 signal_instance->path,
3667 signal_instance->interface,
3668 signal_instance->member,
3669 g_variant_print (parameters, TRUE));
3672 /* Careful here, don't do the callback if we no longer has the subscription */
3673 CONNECTION_LOCK (signal_instance->connection);
3674 has_subscription = FALSE;
3675 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3676 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3677 has_subscription = TRUE;
3678 CONNECTION_UNLOCK (signal_instance->connection);
3680 if (has_subscription)
3681 signal_instance->callback (signal_instance->connection,
3682 signal_instance->sender,
3683 signal_instance->path,
3684 signal_instance->interface,
3685 signal_instance->member,
3687 signal_instance->user_data);
3689 g_variant_unref (parameters);
3695 signal_instance_free (SignalInstance *signal_instance)
3697 g_object_unref (signal_instance->message);
3698 g_object_unref (signal_instance->connection);
3699 g_free (signal_instance);
3702 /* called in GDBusWorker thread WITH lock held */
3704 schedule_callbacks (GDBusConnection *connection,
3705 GPtrArray *signal_data_array,
3706 GDBusMessage *message,
3707 const gchar *sender)
3710 const gchar *interface;
3711 const gchar *member;
3720 interface = g_dbus_message_get_interface (message);
3721 member = g_dbus_message_get_member (message);
3722 path = g_dbus_message_get_path (message);
3723 arg0 = g_dbus_message_get_arg0 (message);
3726 g_print ("In schedule_callbacks:\n"
3728 " interface = `%s'\n"
3739 /* TODO: if this is slow, then we can change signal_data_array into
3740 * map_object_path_to_signal_data_array or something.
3742 for (n = 0; n < signal_data_array->len; n++)
3744 SignalData *signal_data = signal_data_array->pdata[n];
3746 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3749 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3752 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3755 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
3758 for (m = 0; m < signal_data->subscribers->len; m++)
3760 SignalSubscriber *subscriber;
3761 GSource *idle_source;
3762 SignalInstance *signal_instance;
3764 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3766 signal_instance = g_new0 (SignalInstance, 1);
3767 signal_instance->subscription_id = subscriber->id;
3768 signal_instance->callback = subscriber->callback;
3769 signal_instance->user_data = subscriber->user_data;
3770 signal_instance->message = g_object_ref (message);
3771 signal_instance->connection = g_object_ref (connection);
3772 signal_instance->sender = sender;
3773 signal_instance->path = path;
3774 signal_instance->interface = interface;
3775 signal_instance->member = member;
3777 idle_source = g_idle_source_new ();
3778 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3779 g_source_set_callback (idle_source,
3780 emit_signal_instance_in_idle_cb,
3782 (GDestroyNotify) signal_instance_free);
3783 g_source_attach (idle_source, subscriber->context);
3784 g_source_unref (idle_source);
3789 /* called in GDBusWorker thread with lock held */
3791 distribute_signals (GDBusConnection *connection,
3792 GDBusMessage *message)
3794 GPtrArray *signal_data_array;
3795 const gchar *sender;
3797 sender = g_dbus_message_get_sender (message);
3799 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3801 _g_dbus_debug_print_lock ();
3802 g_print ("========================================================================\n"
3803 "GDBus-debug:Signal:\n"
3804 " <<<< RECEIVED SIGNAL %s.%s\n"
3806 " sent by name %s\n",
3807 g_dbus_message_get_interface (message),
3808 g_dbus_message_get_member (message),
3809 g_dbus_message_get_path (message),
3810 sender != NULL ? sender : "(none)");
3811 _g_dbus_debug_print_unlock ();
3814 /* collect subscribers that match on sender */
3817 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3818 if (signal_data_array != NULL)
3819 schedule_callbacks (connection, signal_data_array, message, sender);
3822 /* collect subscribers not matching on sender */
3823 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3824 if (signal_data_array != NULL)
3825 schedule_callbacks (connection, signal_data_array, message, sender);
3828 /* ---------------------------------------------------------------------------------------------------- */
3830 /* only called from finalize(), removes all subscriptions */
3832 purge_all_signal_subscriptions (GDBusConnection *connection)
3834 GHashTableIter iter;
3837 GArray *subscribers;
3840 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3841 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3842 while (g_hash_table_iter_next (&iter, &key, NULL))
3844 guint subscription_id = GPOINTER_TO_UINT (key);
3845 g_array_append_val (ids, subscription_id);
3848 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3849 for (n = 0; n < ids->len; n++)
3851 guint subscription_id = g_array_index (ids, guint, n);
3852 unsubscribe_id_internal (connection,
3856 g_array_free (ids, TRUE);
3858 /* call GDestroyNotify without lock held */
3859 for (n = 0; n < subscribers->len; n++)
3861 SignalSubscriber *subscriber;
3862 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3863 call_destroy_notify (subscriber->context,
3864 subscriber->user_data_free_func,
3865 subscriber->user_data);
3866 g_main_context_unref (subscriber->context);
3869 g_array_free (subscribers, TRUE);
3872 /* ---------------------------------------------------------------------------------------------------- */
3874 static GDBusInterfaceVTable *
3875 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3877 /* Don't waste memory by copying padding - remember to update this
3878 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3880 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3884 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
3889 /* ---------------------------------------------------------------------------------------------------- */
3891 static GDBusSubtreeVTable *
3892 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
3894 /* Don't waste memory by copying padding - remember to update this
3895 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
3897 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3901 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
3906 /* ---------------------------------------------------------------------------------------------------- */
3908 struct ExportedObject
3911 GDBusConnection *connection;
3913 /* maps gchar* -> ExportedInterface* */
3914 GHashTable *map_if_name_to_ei;
3917 /* only called with lock held */
3919 exported_object_free (ExportedObject *eo)
3921 g_free (eo->object_path);
3922 g_hash_table_unref (eo->map_if_name_to_ei);
3931 gchar *interface_name;
3932 GDBusInterfaceVTable *vtable;
3933 GDBusInterfaceInfo *interface_info;
3935 GMainContext *context;
3937 GDestroyNotify user_data_free_func;
3938 } ExportedInterface;
3940 /* called with lock held */
3942 exported_interface_free (ExportedInterface *ei)
3944 g_dbus_interface_info_cache_release (ei->interface_info);
3945 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
3947 call_destroy_notify (ei->context,
3948 ei->user_data_free_func,
3951 g_main_context_unref (ei->context);
3953 g_free (ei->interface_name);
3954 _g_dbus_interface_vtable_free (ei->vtable);
3958 /* ---------------------------------------------------------------------------------------------------- */
3960 /* Convenience function to check if @registration_id (if not zero) or
3961 * @subtree_registration_id (if not zero) has been unregistered. If
3962 * so, returns %TRUE.
3964 * May be called by any thread. Caller must *not* hold lock.
3967 has_object_been_unregistered (GDBusConnection *connection,
3968 guint registration_id,
3969 guint subtree_registration_id)
3973 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3977 CONNECTION_LOCK (connection);
3978 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
3979 GUINT_TO_POINTER (registration_id)) == NULL)
3983 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
3984 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
3988 CONNECTION_UNLOCK (connection);
3993 /* ---------------------------------------------------------------------------------------------------- */
3997 GDBusConnection *connection;
3998 GDBusMessage *message;
4000 const gchar *property_name;
4001 const GDBusInterfaceVTable *vtable;
4002 GDBusInterfaceInfo *interface_info;
4003 const GDBusPropertyInfo *property_info;
4004 guint registration_id;
4005 guint subtree_registration_id;
4009 property_data_free (PropertyData *data)
4011 g_object_unref (data->connection);
4012 g_object_unref (data->message);
4016 /* called in thread where object was registered - no locks held */
4018 invoke_get_property_in_idle_cb (gpointer _data)
4020 PropertyData *data = _data;
4023 GDBusMessage *reply;
4025 if (has_object_been_unregistered (data->connection,
4026 data->registration_id,
4027 data->subtree_registration_id))
4029 reply = g_dbus_message_new_method_error (data->message,
4030 "org.freedesktop.DBus.Error.UnknownMethod",
4031 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
4032 g_dbus_message_get_path (data->message));
4033 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4034 g_object_unref (reply);
4039 value = data->vtable->get_property (data->connection,
4040 g_dbus_message_get_sender (data->message),
4041 g_dbus_message_get_path (data->message),
4042 data->interface_info->name,
4043 data->property_name,
4050 g_assert_no_error (error);
4052 g_variant_take_ref (value);
4053 reply = g_dbus_message_new_method_reply (data->message);
4054 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4055 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4056 g_variant_unref (value);
4057 g_object_unref (reply);
4061 gchar *dbus_error_name;
4062 g_assert (error != NULL);
4063 dbus_error_name = g_dbus_error_encode_gerror (error);
4064 reply = g_dbus_message_new_method_error_literal (data->message,
4067 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4068 g_free (dbus_error_name);
4069 g_error_free (error);
4070 g_object_unref (reply);
4077 /* called in thread where object was registered - no locks held */
4079 invoke_set_property_in_idle_cb (gpointer _data)
4081 PropertyData *data = _data;
4083 GDBusMessage *reply;
4089 g_variant_get (g_dbus_message_get_body (data->message),
4095 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4096 * of the given value is wrong
4098 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
4100 reply = g_dbus_message_new_method_error (data->message,
4101 "org.freedesktop.DBus.Error.InvalidArgs",
4102 _("Error setting property `%s': Expected type `%s' but got `%s'"),
4103 data->property_info->name,
4104 data->property_info->signature,
4105 g_variant_get_type_string (value));
4109 if (!data->vtable->set_property (data->connection,
4110 g_dbus_message_get_sender (data->message),
4111 g_dbus_message_get_path (data->message),
4112 data->interface_info->name,
4113 data->property_name,
4118 gchar *dbus_error_name;
4119 g_assert (error != NULL);
4120 dbus_error_name = g_dbus_error_encode_gerror (error);
4121 reply = g_dbus_message_new_method_error_literal (data->message,
4124 g_free (dbus_error_name);
4125 g_error_free (error);
4129 reply = g_dbus_message_new_method_reply (data->message);
4133 g_assert (reply != NULL);
4134 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4135 g_object_unref (reply);
4136 g_variant_unref (value);
4141 /* called in any thread with connection's lock held */
4143 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4144 GDBusMessage *message,
4145 guint registration_id,
4146 guint subtree_registration_id,
4148 GDBusInterfaceInfo *interface_info,
4149 const GDBusInterfaceVTable *vtable,
4150 GMainContext *main_context,
4154 const char *interface_name;
4155 const char *property_name;
4156 const GDBusPropertyInfo *property_info;
4157 GSource *idle_source;
4158 PropertyData *property_data;
4159 GDBusMessage *reply;
4164 g_variant_get (g_dbus_message_get_body (message),
4169 g_variant_get (g_dbus_message_get_body (message),
4178 if (vtable == NULL || vtable->get_property == NULL)
4183 if (vtable == NULL || vtable->set_property == NULL)
4187 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4189 property_info = NULL;
4191 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4192 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4193 if (property_info == NULL)
4195 reply = g_dbus_message_new_method_error (message,
4196 "org.freedesktop.DBus.Error.InvalidArgs",
4197 _("No such property `%s'"),
4199 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4200 g_object_unref (reply);
4205 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4207 reply = g_dbus_message_new_method_error (message,
4208 "org.freedesktop.DBus.Error.InvalidArgs",
4209 _("Property `%s' is not readable"),
4211 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4212 g_object_unref (reply);
4216 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4218 reply = g_dbus_message_new_method_error (message,
4219 "org.freedesktop.DBus.Error.InvalidArgs",
4220 _("Property `%s' is not writable"),
4222 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4223 g_object_unref (reply);
4228 /* ok, got the property info - call user code in an idle handler */
4229 property_data = g_new0 (PropertyData, 1);
4230 property_data->connection = g_object_ref (connection);
4231 property_data->message = g_object_ref (message);
4232 property_data->user_data = user_data;
4233 property_data->property_name = property_name;
4234 property_data->vtable = vtable;
4235 property_data->interface_info = interface_info;
4236 property_data->property_info = property_info;
4237 property_data->registration_id = registration_id;
4238 property_data->subtree_registration_id = subtree_registration_id;
4240 idle_source = g_idle_source_new ();
4241 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4242 g_source_set_callback (idle_source,
4243 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4245 (GDestroyNotify) property_data_free);
4246 g_source_attach (idle_source, main_context);
4247 g_source_unref (idle_source);
4255 /* called in GDBusWorker thread with connection's lock held */
4257 handle_getset_property (GDBusConnection *connection,
4259 GDBusMessage *message,
4262 ExportedInterface *ei;
4264 const char *interface_name;
4265 const char *property_name;
4270 g_variant_get (g_dbus_message_get_body (message),
4275 g_variant_get (g_dbus_message_get_body (message),
4281 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4282 * no such interface registered
4284 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4287 GDBusMessage *reply;
4288 reply = g_dbus_message_new_method_error (message,
4289 "org.freedesktop.DBus.Error.InvalidArgs",
4290 _("No such interface `%s'"),
4292 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4293 g_object_unref (reply);
4298 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4311 /* ---------------------------------------------------------------------------------------------------- */
4315 GDBusConnection *connection;
4316 GDBusMessage *message;
4318 const GDBusInterfaceVTable *vtable;
4319 GDBusInterfaceInfo *interface_info;
4320 guint registration_id;
4321 guint subtree_registration_id;
4322 } PropertyGetAllData;
4325 property_get_all_data_free (PropertyData *data)
4327 g_object_unref (data->connection);
4328 g_object_unref (data->message);
4332 /* called in thread where object was registered - no locks held */
4334 invoke_get_all_properties_in_idle_cb (gpointer _data)
4336 PropertyGetAllData *data = _data;
4337 GVariantBuilder builder;
4338 GDBusMessage *reply;
4341 if (has_object_been_unregistered (data->connection,
4342 data->registration_id,
4343 data->subtree_registration_id))
4345 reply = g_dbus_message_new_method_error (data->message,
4346 "org.freedesktop.DBus.Error.UnknownMethod",
4347 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
4348 g_dbus_message_get_path (data->message));
4349 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4350 g_object_unref (reply);
4354 /* TODO: Right now we never fail this call - we just omit values if
4355 * a get_property() call is failing.
4357 * We could fail the whole call if just a single get_property() call
4358 * returns an error. We need clarification in the D-Bus spec about this.
4360 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4361 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4362 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4364 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4367 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4370 value = data->vtable->get_property (data->connection,
4371 g_dbus_message_get_sender (data->message),
4372 g_dbus_message_get_path (data->message),
4373 data->interface_info->name,
4374 property_info->name,
4381 g_variant_take_ref (value);
4382 g_variant_builder_add (&builder,
4384 property_info->name,
4386 g_variant_unref (value);
4388 g_variant_builder_close (&builder);
4390 reply = g_dbus_message_new_method_reply (data->message);
4391 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4392 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4393 g_object_unref (reply);
4399 /* called in any thread with connection's lock held */
4401 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4402 GDBusMessage *message,
4403 guint registration_id,
4404 guint subtree_registration_id,
4405 GDBusInterfaceInfo *interface_info,
4406 const GDBusInterfaceVTable *vtable,
4407 GMainContext *main_context,
4411 const char *interface_name;
4412 GSource *idle_source;
4413 PropertyGetAllData *property_get_all_data;
4417 g_variant_get (g_dbus_message_get_body (message),
4421 if (vtable == NULL || vtable->get_property == NULL)
4424 /* ok, got the property info - call user in an idle handler */
4425 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4426 property_get_all_data->connection = g_object_ref (connection);
4427 property_get_all_data->message = g_object_ref (message);
4428 property_get_all_data->user_data = user_data;
4429 property_get_all_data->vtable = vtable;
4430 property_get_all_data->interface_info = interface_info;
4431 property_get_all_data->registration_id = registration_id;
4432 property_get_all_data->subtree_registration_id = subtree_registration_id;
4434 idle_source = g_idle_source_new ();
4435 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4436 g_source_set_callback (idle_source,
4437 invoke_get_all_properties_in_idle_cb,
4438 property_get_all_data,
4439 (GDestroyNotify) property_get_all_data_free);
4440 g_source_attach (idle_source, main_context);
4441 g_source_unref (idle_source);
4449 /* called in GDBusWorker thread with connection's lock held */
4451 handle_get_all_properties (GDBusConnection *connection,
4453 GDBusMessage *message)
4455 ExportedInterface *ei;
4457 const char *interface_name;
4461 g_variant_get (g_dbus_message_get_body (message),
4465 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4466 * no such interface registered
4468 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4471 GDBusMessage *reply;
4472 reply = g_dbus_message_new_method_error (message,
4473 "org.freedesktop.DBus.Error.InvalidArgs",
4474 _("No such interface"),
4476 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4477 g_object_unref (reply);
4482 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4494 /* ---------------------------------------------------------------------------------------------------- */
4496 static const gchar introspect_header[] =
4497 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4498 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4499 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4502 static const gchar introspect_tail[] =
4505 static const gchar introspect_properties_interface[] =
4506 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4507 " <method name=\"Get\">\n"
4508 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4509 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4510 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4512 " <method name=\"GetAll\">\n"
4513 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4514 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4516 " <method name=\"Set\">\n"
4517 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4518 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4519 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4521 " <signal name=\"PropertiesChanged\">\n"
4522 " <arg type=\"s\" name=\"interface_name\"/>\n"
4523 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4524 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4528 static const gchar introspect_introspectable_interface[] =
4529 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4530 " <method name=\"Introspect\">\n"
4531 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4534 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4535 " <method name=\"Ping\"/>\n"
4536 " <method name=\"GetMachineId\">\n"
4537 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4542 introspect_append_header (GString *s)
4544 g_string_append (s, introspect_header);
4548 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4550 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4556 begin = object_path + path_len;
4557 end = strchr (begin, '/');
4559 s = g_strndup (begin, end - begin);
4561 s = g_strdup (begin);
4563 if (g_hash_table_lookup (set, s) == NULL)
4564 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
4570 /* TODO: we want a nicer public interface for this */
4571 /* called in any thread with connection's lock held */
4573 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4578 GHashTableIter hash_iter;
4579 const gchar *object_path;
4585 CONNECTION_ENSURE_LOCK (connection);
4587 path_len = strlen (path);
4591 set = g_hash_table_new (g_str_hash, g_str_equal);
4593 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4594 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4595 maybe_add_path (path, path_len, object_path, set);
4597 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4598 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4599 maybe_add_path (path, path_len, object_path, set);
4601 p = g_ptr_array_new ();
4602 keys = g_hash_table_get_keys (set);
4603 for (l = keys; l != NULL; l = l->next)
4604 g_ptr_array_add (p, l->data);
4605 g_hash_table_unref (set);
4608 g_ptr_array_add (p, NULL);
4609 ret = (gchar **) g_ptr_array_free (p, FALSE);
4613 /* called in any thread with connection's lock not held */
4615 g_dbus_connection_list_registered (GDBusConnection *connection,
4619 CONNECTION_LOCK (connection);
4620 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4621 CONNECTION_UNLOCK (connection);
4625 /* called in GDBusWorker thread with connection's lock held */
4627 handle_introspect (GDBusConnection *connection,
4629 GDBusMessage *message)
4633 GDBusMessage *reply;
4634 GHashTableIter hash_iter;
4635 ExportedInterface *ei;
4638 /* first the header with the standard interfaces */
4639 s = g_string_sized_new (sizeof (introspect_header) +
4640 sizeof (introspect_properties_interface) +
4641 sizeof (introspect_introspectable_interface) +
4642 sizeof (introspect_tail));
4643 introspect_append_header (s);
4644 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4645 "org.freedesktop.DBus.Properties"))
4646 g_string_append (s, introspect_properties_interface);
4648 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4649 "org.freedesktop.DBus.Introspectable"))
4650 g_string_append (s, introspect_introspectable_interface);
4652 /* then include the registered interfaces */
4653 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4654 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4655 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4657 /* finally include nodes registered below us */
4658 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4659 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4660 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4661 g_strfreev (registered);
4662 g_string_append (s, introspect_tail);
4664 reply = g_dbus_message_new_method_reply (message);
4665 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4666 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4667 g_object_unref (reply);
4668 g_string_free (s, TRUE);
4673 /* called in thread where object was registered - no locks held */
4675 call_in_idle_cb (gpointer user_data)
4677 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4678 GDBusInterfaceVTable *vtable;
4679 guint registration_id;
4680 guint subtree_registration_id;
4682 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4683 g_assert (vtable != NULL && vtable->method_call != NULL);
4685 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4686 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4688 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4690 subtree_registration_id))
4692 GDBusMessage *reply;
4693 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4694 "org.freedesktop.DBus.Error.UnknownMethod",
4695 _("No such interface `%s' on object at path %s"),
4696 g_dbus_method_invocation_get_interface_name (invocation),
4697 g_dbus_method_invocation_get_object_path (invocation));
4698 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4699 g_object_unref (reply);
4703 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4704 g_dbus_method_invocation_get_sender (invocation),
4705 g_dbus_method_invocation_get_object_path (invocation),
4706 g_dbus_method_invocation_get_interface_name (invocation),
4707 g_dbus_method_invocation_get_method_name (invocation),
4708 g_dbus_method_invocation_get_parameters (invocation),
4709 g_object_ref (invocation),
4710 g_dbus_method_invocation_get_user_data (invocation));
4716 /* called in GDBusWorker thread with connection's lock held */
4718 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4719 GDBusMessage *message,
4720 guint registration_id,
4721 guint subtree_registration_id,
4722 GDBusInterfaceInfo *interface_info,
4723 const GDBusInterfaceVTable *vtable,
4724 GMainContext *main_context,
4727 GDBusMethodInvocation *invocation;
4728 const GDBusMethodInfo *method_info;
4729 GDBusMessage *reply;
4730 GVariant *parameters;
4731 GSource *idle_source;
4733 GVariantType *in_type;
4737 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4738 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4740 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4741 * error to the caller
4743 if (method_info == NULL)
4745 reply = g_dbus_message_new_method_error (message,
4746 "org.freedesktop.DBus.Error.UnknownMethod",
4747 _("No such method `%s'"),
4748 g_dbus_message_get_member (message));
4749 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4750 g_object_unref (reply);
4755 parameters = g_dbus_message_get_body (message);
4756 if (parameters == NULL)
4758 parameters = g_variant_new ("()");
4759 g_variant_ref_sink (parameters);
4763 g_variant_ref (parameters);
4766 /* Check that the incoming args are of the right type - if they are not, return
4767 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4769 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4770 if (!g_variant_is_of_type (parameters, in_type))
4774 type_string = g_variant_type_dup_string (in_type);
4776 reply = g_dbus_message_new_method_error (message,
4777 "org.freedesktop.DBus.Error.InvalidArgs",
4778 _("Type of message, `%s', does not match expected type `%s'"),
4779 g_variant_get_type_string (parameters),
4781 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4782 g_variant_type_free (in_type);
4783 g_variant_unref (parameters);
4784 g_object_unref (reply);
4785 g_free (type_string);
4789 g_variant_type_free (in_type);
4791 /* schedule the call in idle */
4792 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4793 g_dbus_message_get_path (message),
4794 g_dbus_message_get_interface (message),
4795 g_dbus_message_get_member (message),
4801 g_variant_unref (parameters);
4803 /* TODO: would be nicer with a real MethodData like we already
4804 * have PropertyData and PropertyGetAllData... */
4805 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4806 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4807 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4809 idle_source = g_idle_source_new ();
4810 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4811 g_source_set_callback (idle_source,
4815 g_source_attach (idle_source, main_context);
4816 g_source_unref (idle_source);
4824 /* ---------------------------------------------------------------------------------------------------- */
4826 /* called in GDBusWorker thread with connection's lock held */
4828 obj_message_func (GDBusConnection *connection,
4830 GDBusMessage *message)
4832 const gchar *interface_name;
4833 const gchar *member;
4834 const gchar *signature;
4839 interface_name = g_dbus_message_get_interface (message);
4840 member = g_dbus_message_get_member (message);
4841 signature = g_dbus_message_get_signature (message);
4843 /* see if we have an interface for handling this call */
4844 if (interface_name != NULL)
4846 ExportedInterface *ei;
4847 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4850 /* we do - invoke the handler in idle in the right thread */
4852 /* handle no vtable or handler being present */
4853 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
4856 handled = validate_and_maybe_schedule_method_call (connection,
4868 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4869 g_strcmp0 (member, "Introspect") == 0 &&
4870 g_strcmp0 (signature, "") == 0)
4872 handled = handle_introspect (connection, eo, message);
4875 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4876 g_strcmp0 (member, "Get") == 0 &&
4877 g_strcmp0 (signature, "ss") == 0)
4879 handled = handle_getset_property (connection, eo, message, TRUE);
4882 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4883 g_strcmp0 (member, "Set") == 0 &&
4884 g_strcmp0 (signature, "ssv") == 0)
4886 handled = handle_getset_property (connection, eo, message, FALSE);
4889 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4890 g_strcmp0 (member, "GetAll") == 0 &&
4891 g_strcmp0 (signature, "s") == 0)
4893 handled = handle_get_all_properties (connection, eo, message);
4902 * g_dbus_connection_register_object:
4903 * @connection: A #GDBusConnection.
4904 * @object_path: The object path to register at.
4905 * @interface_info: Introspection data for the interface.
4906 * @vtable: (allow-none): A #GDBusInterfaceVTable to call into or %NULL.
4907 * @user_data: (allow-none): Data to pass to functions in @vtable.
4908 * @user_data_free_func: Function to call when the object path is unregistered.
4909 * @error: Return location for error or %NULL.
4911 * Registers callbacks for exported objects at @object_path with the
4912 * D-Bus interface that is described in @interface_info.
4914 * Calls to functions in @vtable (and @user_data_free_func) will
4915 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
4916 * loop</link> of the thread you are calling this method from.
4918 * Note that all #GVariant values passed to functions in @vtable will match
4919 * the signature given in @interface_info - if a remote caller passes
4920 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
4921 * is returned to the remote caller.
4923 * Additionally, if the remote caller attempts to invoke methods or
4924 * access properties not mentioned in @interface_info the
4925 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
4926 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
4927 * are returned to the caller.
4929 * It is considered a programming error if the
4930 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
4931 * #GVariant of incorrect type.
4933 * If an existing callback is already registered at @object_path and
4934 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
4936 * GDBus automatically implements the standard D-Bus interfaces
4937 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
4938 * and org.freedesktop.Peer, so you don't have to implement those for
4939 * the objects you export. You <emphasis>can</emphasis> implement
4940 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
4941 * and setting of properties asynchronously.
4943 * Note that the reference count on @interface_info will be
4944 * incremented by 1 (unless allocated statically, e.g. if the
4945 * reference count is -1, see g_dbus_interface_info_ref()) for as long
4946 * as the object is exported. Also note that @vtable will be copied.
4948 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
4950 * Returns: 0 if @error is set, otherwise a registration id (never 0)
4951 * that can be used with g_dbus_connection_unregister_object() .
4956 g_dbus_connection_register_object (GDBusConnection *connection,
4957 const gchar *object_path,
4958 GDBusInterfaceInfo *interface_info,
4959 const GDBusInterfaceVTable *vtable,
4961 GDestroyNotify user_data_free_func,
4965 ExportedInterface *ei;
4968 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4969 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4970 g_return_val_if_fail (interface_info != NULL, 0);
4971 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
4972 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4973 g_return_val_if_fail (check_initialized (connection), 0);
4977 CONNECTION_LOCK (connection);
4979 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
4982 eo = g_new0 (ExportedObject, 1);
4983 eo->object_path = g_strdup (object_path);
4984 eo->connection = connection;
4985 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
4988 (GDestroyNotify) exported_interface_free);
4989 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
4992 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
4998 _("An object is already exported for the interface %s at %s"),
4999 interface_info->name,
5004 ei = g_new0 (ExportedInterface, 1);
5005 ei->id = _global_registration_id++; /* TODO: overflow etc. */
5007 ei->user_data = user_data;
5008 ei->user_data_free_func = user_data_free_func;
5009 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
5010 ei->interface_info = g_dbus_interface_info_ref (interface_info);
5011 g_dbus_interface_info_cache_build (ei->interface_info);
5012 ei->interface_name = g_strdup (interface_info->name);
5013 ei->context = g_main_context_ref_thread_default ();
5015 g_hash_table_insert (eo->map_if_name_to_ei,
5016 (gpointer) ei->interface_name,
5018 g_hash_table_insert (connection->map_id_to_ei,
5019 GUINT_TO_POINTER (ei->id),
5025 CONNECTION_UNLOCK (connection);
5031 * g_dbus_connection_unregister_object:
5032 * @connection: A #GDBusConnection.
5033 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
5035 * Unregisters an object.
5037 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
5042 g_dbus_connection_unregister_object (GDBusConnection *connection,
5043 guint registration_id)
5045 ExportedInterface *ei;
5049 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5050 g_return_val_if_fail (check_initialized (connection), FALSE);
5054 CONNECTION_LOCK (connection);
5056 ei = g_hash_table_lookup (connection->map_id_to_ei,
5057 GUINT_TO_POINTER (registration_id));
5063 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5064 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5065 /* unregister object path if we have no more exported interfaces */
5066 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5067 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5073 CONNECTION_UNLOCK (connection);
5078 /* ---------------------------------------------------------------------------------------------------- */
5081 * g_dbus_connection_emit_signal:
5082 * @connection: A #GDBusConnection.
5083 * @destination_bus_name: (allow-none): The unique bus name for the destination
5084 * for the signal or %NULL to emit to all listeners.
5085 * @object_path: Path of remote object.
5086 * @interface_name: D-Bus interface to emit a signal on.
5087 * @signal_name: The name of the signal to emit.
5088 * @parameters: (allow-none): A #GVariant tuple with parameters for the signal
5089 * or %NULL if not passing parameters.
5090 * @error: Return location for error or %NULL.
5094 * If the parameters GVariant is floating, it is consumed.
5096 * This can only fail if @parameters is not compatible with the D-Bus protocol.
5098 * Returns: %TRUE unless @error is set.
5103 g_dbus_connection_emit_signal (GDBusConnection *connection,
5104 const gchar *destination_bus_name,
5105 const gchar *object_path,
5106 const gchar *interface_name,
5107 const gchar *signal_name,
5108 GVariant *parameters,
5111 GDBusMessage *message;
5117 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5118 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5119 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5120 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5121 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5122 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5123 g_return_val_if_fail (check_initialized (connection), FALSE);
5125 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5127 _g_dbus_debug_print_lock ();
5128 g_print ("========================================================================\n"
5129 "GDBus-debug:Emission:\n"
5130 " >>>> SIGNAL EMISSION %s.%s()\n"
5132 " destination %s\n",
5133 interface_name, signal_name,
5135 destination_bus_name != NULL ? destination_bus_name : "(none)");
5136 _g_dbus_debug_print_unlock ();
5139 message = g_dbus_message_new_signal (object_path,
5143 if (destination_bus_name != NULL)
5144 g_dbus_message_set_header (message,
5145 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5146 g_variant_new_string (destination_bus_name));
5148 if (parameters != NULL)
5149 g_dbus_message_set_body (message, parameters);
5151 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5152 g_object_unref (message);
5158 add_call_flags (GDBusMessage *message,
5159 GDBusCallFlags flags)
5161 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5162 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
5166 decode_method_reply (GDBusMessage *reply,
5167 const gchar *method_name,
5168 const GVariantType *reply_type,
5169 GUnixFDList **out_fd_list,
5175 switch (g_dbus_message_get_message_type (reply))
5177 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5178 result = g_dbus_message_get_body (reply);
5181 result = g_variant_new ("()");
5182 g_variant_ref_sink (result);
5186 g_variant_ref (result);
5189 if (!g_variant_is_of_type (result, reply_type))
5191 gchar *type_string = g_variant_type_dup_string (reply_type);
5195 G_IO_ERROR_INVALID_ARGUMENT,
5196 _("Method `%s' returned type `%s', but expected `%s'"),
5197 method_name, g_variant_get_type_string (result), type_string);
5199 g_variant_unref (result);
5200 g_free (type_string);
5207 if (out_fd_list != NULL)
5209 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5210 if (*out_fd_list != NULL)
5211 g_object_ref (*out_fd_list);
5217 case G_DBUS_MESSAGE_TYPE_ERROR:
5218 g_dbus_message_to_gerror (reply, error);
5222 g_assert_not_reached ();
5232 GSimpleAsyncResult *simple;
5233 GVariantType *reply_type;
5234 gchar *method_name; /* for error message */
5238 GUnixFDList *fd_list;
5242 call_state_free (CallState *state)
5244 g_variant_type_free (state->reply_type);
5245 g_free (state->method_name);
5247 if (state->value != NULL)
5248 g_variant_unref (state->value);
5249 if (state->fd_list != NULL)
5250 g_object_unref (state->fd_list);
5251 g_slice_free (CallState, state);
5254 /* called in any thread, with the connection's lock not held */
5256 g_dbus_connection_call_done (GObject *source,
5257 GAsyncResult *result,
5260 GSimpleAsyncResult *simple;
5261 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5262 CallState *state = user_data;
5264 GDBusMessage *reply;
5267 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5271 if (G_UNLIKELY (_g_dbus_debug_call ()))
5273 _g_dbus_debug_print_lock ();
5274 g_print ("========================================================================\n"
5275 "GDBus-debug:Call:\n"
5276 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5282 g_print ("SUCCESS\n");
5286 g_print ("FAILED: %s\n",
5289 _g_dbus_debug_print_unlock ();
5293 state->value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5295 simple = state->simple; /* why? because state is freed before we unref simple.. */
5298 g_simple_async_result_take_error (state->simple, error);
5299 g_simple_async_result_complete (state->simple);
5300 call_state_free (state);
5304 g_simple_async_result_set_op_res_gpointer (state->simple, state, (GDestroyNotify) call_state_free);
5305 g_simple_async_result_complete (state->simple);
5306 g_object_unref (reply);
5308 g_object_unref (simple);
5311 /* called in any thread, with the connection's lock not held */
5313 g_dbus_connection_call_internal (GDBusConnection *connection,
5314 const gchar *bus_name,
5315 const gchar *object_path,
5316 const gchar *interface_name,
5317 const gchar *method_name,
5318 GVariant *parameters,
5319 const GVariantType *reply_type,
5320 GDBusCallFlags flags,
5322 GUnixFDList *fd_list,
5323 GCancellable *cancellable,
5324 GAsyncReadyCallback callback,
5327 GDBusMessage *message;
5330 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5331 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5332 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5333 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5334 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5335 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5336 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5337 g_return_if_fail (check_initialized (connection));
5339 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5341 g_return_if_fail (fd_list == NULL);
5344 state = g_slice_new0 (CallState);
5345 state->simple = g_simple_async_result_new (G_OBJECT (connection),
5346 callback, user_data,
5347 g_dbus_connection_call_internal);
5348 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5350 if (reply_type == NULL)
5351 reply_type = G_VARIANT_TYPE_ANY;
5353 state->reply_type = g_variant_type_copy (reply_type);
5355 message = g_dbus_message_new_method_call (bus_name,
5359 add_call_flags (message, flags);
5360 if (parameters != NULL)
5361 g_dbus_message_set_body (message, parameters);
5364 if (fd_list != NULL)
5365 g_dbus_message_set_unix_fd_list (message, fd_list);
5368 g_dbus_connection_send_message_with_reply (connection,
5370 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5374 g_dbus_connection_call_done,
5377 if (G_UNLIKELY (_g_dbus_debug_call ()))
5379 _g_dbus_debug_print_lock ();
5380 g_print ("========================================================================\n"
5381 "GDBus-debug:Call:\n"
5382 " >>>> ASYNC %s.%s()\n"
5384 " owned by name %s (serial %d)\n",
5388 bus_name != NULL ? bus_name : "(none)",
5390 _g_dbus_debug_print_unlock ();
5393 if (message != NULL)
5394 g_object_unref (message);
5397 /* called in any thread, with the connection's lock not held */
5399 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
5400 GUnixFDList **out_fd_list,
5404 GSimpleAsyncResult *simple;
5407 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5408 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
5409 g_dbus_connection_call_internal), NULL);
5410 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5412 simple = G_SIMPLE_ASYNC_RESULT (res);
5414 if (g_simple_async_result_propagate_error (simple, error))
5417 state = g_simple_async_result_get_op_res_gpointer (simple);
5418 if (out_fd_list != NULL)
5419 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
5420 return g_variant_ref (state->value);
5423 /* called in any user thread, with the connection's lock not held */
5425 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
5426 const gchar *bus_name,
5427 const gchar *object_path,
5428 const gchar *interface_name,
5429 const gchar *method_name,
5430 GVariant *parameters,
5431 const GVariantType *reply_type,
5432 GDBusCallFlags flags,
5434 GUnixFDList *fd_list,
5435 GUnixFDList **out_fd_list,
5436 GCancellable *cancellable,
5439 GDBusMessage *message;
5440 GDBusMessage *reply;
5442 GError *local_error;
5443 GDBusSendMessageFlags send_flags;
5449 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5450 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5451 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5452 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5453 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5454 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5455 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5457 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
5459 g_return_val_if_fail (fd_list == NULL, NULL);
5461 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5463 if (!(flags & CALL_FLAGS_INITIALIZING))
5464 g_return_val_if_fail (check_initialized (connection), FALSE);
5466 if (reply_type == NULL)
5467 reply_type = G_VARIANT_TYPE_ANY;
5469 message = g_dbus_message_new_method_call (bus_name,
5473 add_call_flags (message, flags);
5474 if (parameters != NULL)
5475 g_dbus_message_set_body (message, parameters);
5478 if (fd_list != NULL)
5479 g_dbus_message_set_unix_fd_list (message, fd_list);
5482 if (G_UNLIKELY (_g_dbus_debug_call ()))
5484 _g_dbus_debug_print_lock ();
5485 g_print ("========================================================================\n"
5486 "GDBus-debug:Call:\n"
5487 " >>>> SYNC %s.%s()\n"
5489 " owned by name %s\n",
5493 bus_name != NULL ? bus_name : "(none)");
5494 _g_dbus_debug_print_unlock ();
5499 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
5501 /* translate from one flavour of flags to another... */
5502 if (flags & CALL_FLAGS_INITIALIZING)
5503 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
5505 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5509 NULL, /* volatile guint32 *out_serial */
5513 if (G_UNLIKELY (_g_dbus_debug_call ()))
5515 _g_dbus_debug_print_lock ();
5516 g_print ("========================================================================\n"
5517 "GDBus-debug:Call:\n"
5518 " <<<< SYNC COMPLETE %s.%s()\n"
5524 g_print ("SUCCESS\n");
5528 g_print ("FAILED: %s\n",
5529 local_error->message);
5531 _g_dbus_debug_print_unlock ();
5537 *error = local_error;
5539 g_error_free (local_error);
5543 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
5546 if (message != NULL)
5547 g_object_unref (message);
5549 g_object_unref (reply);
5554 /* ---------------------------------------------------------------------------------------------------- */
5557 * g_dbus_connection_call:
5558 * @connection: A #GDBusConnection.
5559 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5560 * @connection is not a message bus connection.
5561 * @object_path: Path of remote object.
5562 * @interface_name: D-Bus interface to invoke method on.
5563 * @method_name: The name of the method to invoke.
5564 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5565 * or %NULL if not passing parameters.
5566 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5567 * @flags: Flags from the #GDBusCallFlags enumeration.
5568 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5569 * timeout or %G_MAXINT for no timeout.
5570 * @cancellable: A #GCancellable or %NULL.
5571 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5572 * satisfied or %NULL if you don't care about the result of the
5573 * method invocation.
5574 * @user_data: The data to pass to @callback.
5576 * Asynchronously invokes the @method_name method on the
5577 * @interface_name D-Bus interface on the remote object at
5578 * @object_path owned by @bus_name.
5580 * If @connection is closed then the operation will fail with
5581 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
5582 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
5583 * not compatible with the D-Bus protocol, the operation fails with
5584 * %G_IO_ERROR_INVALID_ARGUMENT.
5586 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
5587 * error will be raised if it does not match. Said another way, if you give a @reply_type
5588 * then any non-%NULL return value will be of this type.
5590 * If the @parameters #GVariant is floating, it is consumed. This allows
5591 * convenient 'inline' use of g_variant_new(), e.g.:
5593 * g_dbus_connection_call (connection,
5594 * "org.freedesktop.StringThings",
5595 * "/org/freedesktop/StringThings",
5596 * "org.freedesktop.StringThings",
5598 * g_variant_new ("(ss)",
5602 * G_DBUS_CALL_FLAGS_NONE,
5605 * (GAsyncReadyCallback) two_strings_done,
5609 * This is an asynchronous method. When the operation is finished, @callback will be invoked
5610 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
5611 * of the thread you are calling this method from. You can then call
5612 * g_dbus_connection_call_finish() to get the result of the operation.
5613 * See g_dbus_connection_call_sync() for the synchronous version of this
5619 g_dbus_connection_call (GDBusConnection *connection,
5620 const gchar *bus_name,
5621 const gchar *object_path,
5622 const gchar *interface_name,
5623 const gchar *method_name,
5624 GVariant *parameters,
5625 const GVariantType *reply_type,
5626 GDBusCallFlags flags,
5628 GCancellable *cancellable,
5629 GAsyncReadyCallback callback,
5632 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);
5636 * g_dbus_connection_call_finish:
5637 * @connection: A #GDBusConnection.
5638 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
5639 * @error: Return location for error or %NULL.
5641 * Finishes an operation started with g_dbus_connection_call().
5643 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5644 * return values. Free with g_variant_unref().
5649 g_dbus_connection_call_finish (GDBusConnection *connection,
5653 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
5657 * g_dbus_connection_call_sync:
5658 * @connection: A #GDBusConnection.
5659 * @bus_name: A unique or well-known bus name.
5660 * @object_path: Path of remote object.
5661 * @interface_name: D-Bus interface to invoke method on.
5662 * @method_name: The name of the method to invoke.
5663 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5664 * or %NULL if not passing parameters.
5665 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5666 * @flags: Flags from the #GDBusCallFlags enumeration.
5667 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5668 * timeout or %G_MAXINT for no timeout.
5669 * @cancellable: A #GCancellable or %NULL.
5670 * @error: Return location for error or %NULL.
5672 * Synchronously invokes the @method_name method on the
5673 * @interface_name D-Bus interface on the remote object at
5674 * @object_path owned by @bus_name.
5676 * If @connection is closed then the operation will fail with
5677 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
5678 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
5679 * contains a value not compatible with the D-Bus protocol, the operation
5680 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
5682 * If @reply_type is non-%NULL then the reply will be checked for having
5683 * this type and an error will be raised if it does not match. Said
5684 * another way, if you give a @reply_type then any non-%NULL return
5685 * value will be of this type.
5687 * If the @parameters #GVariant is floating, it is consumed.
5688 * This allows convenient 'inline' use of g_variant_new(), e.g.:
5690 * g_dbus_connection_call_sync (connection,
5691 * "org.freedesktop.StringThings",
5692 * "/org/freedesktop/StringThings",
5693 * "org.freedesktop.StringThings",
5695 * g_variant_new ("(ss)",
5699 * G_DBUS_CALL_FLAGS_NONE,
5705 * The calling thread is blocked until a reply is received. See
5706 * g_dbus_connection_call() for the asynchronous version of
5709 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5710 * return values. Free with g_variant_unref().
5715 g_dbus_connection_call_sync (GDBusConnection *connection,
5716 const gchar *bus_name,
5717 const gchar *object_path,
5718 const gchar *interface_name,
5719 const gchar *method_name,
5720 GVariant *parameters,
5721 const GVariantType *reply_type,
5722 GDBusCallFlags flags,
5724 GCancellable *cancellable,
5727 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);
5730 /* ---------------------------------------------------------------------------------------------------- */
5735 * g_dbus_connection_call_with_unix_fd_list:
5736 * @connection: A #GDBusConnection.
5737 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5738 * @connection is not a message bus connection.
5739 * @object_path: Path of remote object.
5740 * @interface_name: D-Bus interface to invoke method on.
5741 * @method_name: The name of the method to invoke.
5742 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5743 * or %NULL if not passing parameters.
5744 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5745 * @flags: Flags from the #GDBusCallFlags enumeration.
5746 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5747 * timeout or %G_MAXINT for no timeout.
5748 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
5749 * @cancellable: A #GCancellable or %NULL.
5750 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5751 * satisfied or %NULL if you don't * care about the result of the
5752 * method invocation.
5753 * @user_data: The data to pass to @callback.
5755 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
5757 * This method is only available on UNIX.
5762 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
5763 const gchar *bus_name,
5764 const gchar *object_path,
5765 const gchar *interface_name,
5766 const gchar *method_name,
5767 GVariant *parameters,
5768 const GVariantType *reply_type,
5769 GDBusCallFlags flags,
5771 GUnixFDList *fd_list,
5772 GCancellable *cancellable,
5773 GAsyncReadyCallback callback,
5776 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);
5780 * g_dbus_connection_call_with_unix_fd_list_finish:
5781 * @connection: A #GDBusConnection.
5782 * @out_fd_list: (out): Return location for a #GUnixFDList or %NULL.
5783 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call_with_unix_fd_list().
5784 * @error: Return location for error or %NULL.
5786 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
5788 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5789 * return values. Free with g_variant_unref().
5794 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
5795 GUnixFDList **out_fd_list,
5799 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
5803 * g_dbus_connection_call_with_unix_fd_list_sync:
5804 * @connection: A #GDBusConnection.
5805 * @bus_name: A unique or well-known bus name.
5806 * @object_path: Path of remote object.
5807 * @interface_name: D-Bus interface to invoke method on.
5808 * @method_name: The name of the method to invoke.
5809 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5810 * or %NULL if not passing parameters.
5811 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5812 * @flags: Flags from the #GDBusCallFlags enumeration.
5813 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5814 * timeout or %G_MAXINT for no timeout.
5815 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
5816 * @out_fd_list: (out): Return location for a #GUnixFDList or %NULL.
5817 * @cancellable: A #GCancellable or %NULL.
5818 * @error: Return location for error or %NULL.
5820 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
5822 * This method is only available on UNIX.
5824 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5825 * return values. Free with g_variant_unref().
5830 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
5831 const gchar *bus_name,
5832 const gchar *object_path,
5833 const gchar *interface_name,
5834 const gchar *method_name,
5835 GVariant *parameters,
5836 const GVariantType *reply_type,
5837 GDBusCallFlags flags,
5839 GUnixFDList *fd_list,
5840 GUnixFDList **out_fd_list,
5841 GCancellable *cancellable,
5844 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);
5847 #endif /* G_OS_UNIX */
5849 /* ---------------------------------------------------------------------------------------------------- */
5851 struct ExportedSubtree
5855 GDBusConnection *connection;
5856 GDBusSubtreeVTable *vtable;
5857 GDBusSubtreeFlags flags;
5859 GMainContext *context;
5861 GDestroyNotify user_data_free_func;
5865 exported_subtree_free (ExportedSubtree *es)
5867 call_destroy_notify (es->context,
5868 es->user_data_free_func,
5871 g_main_context_unref (es->context);
5873 _g_dbus_subtree_vtable_free (es->vtable);
5874 g_free (es->object_path);
5878 /* called without lock held in the thread where the caller registered
5882 handle_subtree_introspect (GDBusConnection *connection,
5883 ExportedSubtree *es,
5884 GDBusMessage *message)
5888 GDBusMessage *reply;
5891 const gchar *sender;
5892 const gchar *requested_object_path;
5893 const gchar *requested_node;
5894 GDBusInterfaceInfo **interfaces;
5896 gchar **subnode_paths;
5897 gboolean has_properties_interface;
5898 gboolean has_introspectable_interface;
5902 requested_object_path = g_dbus_message_get_path (message);
5903 sender = g_dbus_message_get_sender (message);
5904 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5906 s = g_string_new (NULL);
5907 introspect_append_header (s);
5909 /* Strictly we don't need the children in dynamic mode, but we avoid the
5910 * conditionals to preserve code clarity
5912 children = es->vtable->enumerate (es->connection,
5919 requested_node = strrchr (requested_object_path, '/') + 1;
5921 /* Assert existence of object if we are not dynamic */
5922 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
5923 !_g_strv_has_string ((const gchar * const *) children, requested_node))
5928 requested_node = NULL;
5931 interfaces = es->vtable->introspect (es->connection,
5936 if (interfaces != NULL)
5938 has_properties_interface = FALSE;
5939 has_introspectable_interface = FALSE;
5941 for (n = 0; interfaces[n] != NULL; n++)
5943 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
5944 has_properties_interface = TRUE;
5945 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
5946 has_introspectable_interface = TRUE;
5948 if (!has_properties_interface)
5949 g_string_append (s, introspect_properties_interface);
5950 if (!has_introspectable_interface)
5951 g_string_append (s, introspect_introspectable_interface);
5953 for (n = 0; interfaces[n] != NULL; n++)
5955 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
5956 g_dbus_interface_info_unref (interfaces[n]);
5958 g_free (interfaces);
5961 /* then include <node> entries from the Subtree for the root */
5964 for (n = 0; children != NULL && children[n] != NULL; n++)
5965 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
5968 /* finally include nodes registered below us */
5969 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
5970 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
5971 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
5972 g_strfreev (subnode_paths);
5974 g_string_append (s, "</node>\n");
5976 reply = g_dbus_message_new_method_reply (message);
5977 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5978 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5979 g_object_unref (reply);
5984 g_string_free (s, TRUE);
5985 g_strfreev (children);
5989 /* called without lock held in the thread where the caller registered
5993 handle_subtree_method_invocation (GDBusConnection *connection,
5994 ExportedSubtree *es,
5995 GDBusMessage *message)
5998 const gchar *sender;
5999 const gchar *interface_name;
6000 const gchar *member;
6001 const gchar *signature;
6002 const gchar *requested_object_path;
6003 const gchar *requested_node;
6005 GDBusInterfaceInfo *interface_info;
6006 const GDBusInterfaceVTable *interface_vtable;
6007 gpointer interface_user_data;
6009 GDBusInterfaceInfo **interfaces;
6010 gboolean is_property_get;
6011 gboolean is_property_set;
6012 gboolean is_property_get_all;
6017 requested_object_path = g_dbus_message_get_path (message);
6018 sender = g_dbus_message_get_sender (message);
6019 interface_name = g_dbus_message_get_interface (message);
6020 member = g_dbus_message_get_member (message);
6021 signature = g_dbus_message_get_signature (message);
6022 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6024 is_property_get = FALSE;
6025 is_property_set = FALSE;
6026 is_property_get_all = FALSE;
6027 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6029 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6030 is_property_get = TRUE;
6031 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6032 is_property_set = TRUE;
6033 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6034 is_property_get_all = TRUE;
6039 requested_node = strrchr (requested_object_path, '/') + 1;
6041 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6043 /* We don't want to dispatch to unenumerated
6044 * nodes, so ensure that the child exists.
6049 children = es->vtable->enumerate (es->connection,
6054 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6055 g_strfreev (children);
6063 requested_node = NULL;
6066 /* get introspection data for the node */
6067 interfaces = es->vtable->introspect (es->connection,
6069 requested_object_path,
6073 if (interfaces == NULL)
6076 interface_info = NULL;
6077 for (n = 0; interfaces[n] != NULL; n++)
6079 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6080 interface_info = interfaces[n];
6083 /* dispatch the call if the user wants to handle it */
6084 if (interface_info != NULL)
6086 /* figure out where to dispatch the method call */
6087 interface_user_data = NULL;
6088 interface_vtable = es->vtable->dispatch (es->connection,
6093 &interface_user_data,
6095 if (interface_vtable == NULL)
6098 CONNECTION_LOCK (connection);
6099 handled = validate_and_maybe_schedule_method_call (es->connection,
6106 interface_user_data);
6107 CONNECTION_UNLOCK (connection);
6109 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6110 else if (is_property_get || is_property_set || is_property_get_all)
6112 if (is_property_get)
6113 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6114 else if (is_property_set)
6115 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6116 else if (is_property_get_all)
6117 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6119 g_assert_not_reached ();
6121 /* see if the object supports this interface at all */
6122 for (n = 0; interfaces[n] != NULL; n++)
6124 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6125 interface_info = interfaces[n];
6128 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6129 * claims it won't support the interface
6131 if (interface_info == NULL)
6133 GDBusMessage *reply;
6134 reply = g_dbus_message_new_method_error (message,
6135 "org.freedesktop.DBus.Error.InvalidArgs",
6136 _("No such interface `%s'"),
6138 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6139 g_object_unref (reply);
6144 /* figure out where to dispatch the property get/set/getall calls */
6145 interface_user_data = NULL;
6146 interface_vtable = es->vtable->dispatch (es->connection,
6151 &interface_user_data,
6153 if (interface_vtable == NULL)
6155 g_warning ("The subtree introspection function indicates that '%s' "
6156 "is a valid interface name, but calling the dispatch "
6157 "function on that interface gave us NULL", interface_name);
6161 if (is_property_get || is_property_set)
6163 CONNECTION_LOCK (connection);
6164 handled = validate_and_maybe_schedule_property_getset (es->connection,
6172 interface_user_data);
6173 CONNECTION_UNLOCK (connection);
6175 else if (is_property_get_all)
6177 CONNECTION_LOCK (connection);
6178 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6185 interface_user_data);
6186 CONNECTION_UNLOCK (connection);
6191 if (interfaces != NULL)
6193 for (n = 0; interfaces[n] != NULL; n++)
6194 g_dbus_interface_info_unref (interfaces[n]);
6195 g_free (interfaces);
6203 GDBusMessage *message;
6204 ExportedSubtree *es;
6205 } SubtreeDeferredData;
6208 subtree_deferred_data_free (SubtreeDeferredData *data)
6210 g_object_unref (data->message);
6214 /* called without lock held in the thread where the caller registered the subtree */
6216 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6218 SubtreeDeferredData *data = _data;
6223 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6224 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6225 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6226 handled = handle_subtree_introspect (data->es->connection,
6230 handled = handle_subtree_method_invocation (data->es->connection,
6236 CONNECTION_LOCK (data->es->connection);
6237 handled = handle_generic_unlocked (data->es->connection, data->message);
6238 CONNECTION_UNLOCK (data->es->connection);
6241 /* if we couldn't handle the request, just bail with the UnknownMethod error */
6244 GDBusMessage *reply;
6245 reply = g_dbus_message_new_method_error (data->message,
6246 "org.freedesktop.DBus.Error.UnknownMethod",
6247 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
6248 g_dbus_message_get_member (data->message),
6249 g_dbus_message_get_interface (data->message),
6250 g_dbus_message_get_signature (data->message));
6251 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6252 g_object_unref (reply);
6258 /* called in GDBusWorker thread with connection's lock held */
6260 subtree_message_func (GDBusConnection *connection,
6261 ExportedSubtree *es,
6262 GDBusMessage *message)
6264 GSource *idle_source;
6265 SubtreeDeferredData *data;
6267 data = g_new0 (SubtreeDeferredData, 1);
6268 data->message = g_object_ref (message);
6271 /* defer this call to an idle handler in the right thread */
6272 idle_source = g_idle_source_new ();
6273 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
6274 g_source_set_callback (idle_source,
6275 process_subtree_vtable_message_in_idle_cb,
6277 (GDestroyNotify) subtree_deferred_data_free);
6278 g_source_attach (idle_source, es->context);
6279 g_source_unref (idle_source);
6281 /* since we own the entire subtree, handlers for objects not in the subtree have been
6282 * tried already by libdbus-1 - so we just need to ensure that we're always going
6283 * to reply to the message
6289 * g_dbus_connection_register_subtree:
6290 * @connection: A #GDBusConnection.
6291 * @object_path: The object path to register the subtree at.
6292 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
6293 * @flags: Flags used to fine tune the behavior of the subtree.
6294 * @user_data: Data to pass to functions in @vtable.
6295 * @user_data_free_func: Function to call when the subtree is unregistered.
6296 * @error: Return location for error or %NULL.
6298 * Registers a whole subtree of <quote>dynamic</quote> objects.
6300 * The @enumerate and @introspection functions in @vtable are used to
6301 * convey, to remote callers, what nodes exist in the subtree rooted
6304 * When handling remote calls into any node in the subtree, first the
6305 * @enumerate function is used to check if the node exists. If the node exists
6306 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6307 * the @introspection function is used to check if the node supports the
6308 * requested method. If so, the @dispatch function is used to determine
6309 * where to dispatch the call. The collected #GDBusInterfaceVTable and
6310 * #gpointer will be used to call into the interface vtable for processing
6313 * All calls into user-provided code will be invoked in the <link
6314 * linkend="g-main-context-push-thread-default">thread-default main
6315 * loop</link> of the thread you are calling this method from.
6317 * If an existing subtree is already registered at @object_path or
6318 * then @error is set to #G_IO_ERROR_EXISTS.
6320 * Note that it is valid to register regular objects (using
6321 * g_dbus_connection_register_object()) in a subtree registered with
6322 * g_dbus_connection_register_subtree() - if so, the subtree handler
6323 * is tried as the last resort. One way to think about a subtree
6324 * handler is to consider it a <quote>fallback handler</quote>
6325 * for object paths not registered via g_dbus_connection_register_object()
6326 * or other bindings.
6328 * Note that @vtable will be copied so you cannot change it after
6331 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
6333 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
6334 * that can be used with g_dbus_connection_unregister_subtree() .
6339 g_dbus_connection_register_subtree (GDBusConnection *connection,
6340 const gchar *object_path,
6341 const GDBusSubtreeVTable *vtable,
6342 GDBusSubtreeFlags flags,
6344 GDestroyNotify user_data_free_func,
6348 ExportedSubtree *es;
6350 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
6351 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
6352 g_return_val_if_fail (vtable != NULL, 0);
6353 g_return_val_if_fail (error == NULL || *error == NULL, 0);
6354 g_return_val_if_fail (check_initialized (connection), 0);
6358 CONNECTION_LOCK (connection);
6360 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6366 _("A subtree is already exported for %s"),
6371 es = g_new0 (ExportedSubtree, 1);
6372 es->object_path = g_strdup (object_path);
6373 es->connection = connection;
6375 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
6377 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
6378 es->user_data = user_data;
6379 es->user_data_free_func = user_data_free_func;
6380 es->context = g_main_context_ref_thread_default ();
6382 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
6383 g_hash_table_insert (connection->map_id_to_es,
6384 GUINT_TO_POINTER (es->id),
6390 CONNECTION_UNLOCK (connection);
6395 /* ---------------------------------------------------------------------------------------------------- */
6398 * g_dbus_connection_unregister_subtree:
6399 * @connection: A #GDBusConnection.
6400 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
6402 * Unregisters a subtree.
6404 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
6409 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
6410 guint registration_id)
6412 ExportedSubtree *es;
6415 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
6416 g_return_val_if_fail (check_initialized (connection), FALSE);
6420 CONNECTION_LOCK (connection);
6422 es = g_hash_table_lookup (connection->map_id_to_es,
6423 GUINT_TO_POINTER (registration_id));
6427 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
6428 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
6433 CONNECTION_UNLOCK (connection);
6438 /* ---------------------------------------------------------------------------------------------------- */
6440 /* may be called in any thread, with connection's lock held */
6442 handle_generic_ping_unlocked (GDBusConnection *connection,
6443 const gchar *object_path,
6444 GDBusMessage *message)
6446 GDBusMessage *reply;
6447 reply = g_dbus_message_new_method_reply (message);
6448 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6449 g_object_unref (reply);
6452 /* may be called in any thread, with connection's lock held */
6454 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
6455 const gchar *object_path,
6456 GDBusMessage *message)
6458 GDBusMessage *reply;
6461 if (connection->machine_id == NULL)
6466 connection->machine_id = _g_dbus_get_machine_id (&error);
6467 if (connection->machine_id == NULL)
6469 reply = g_dbus_message_new_method_error_literal (message,
6470 "org.freedesktop.DBus.Error.Failed",
6472 g_error_free (error);
6478 reply = g_dbus_message_new_method_reply (message);
6479 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
6481 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6482 g_object_unref (reply);
6485 /* may be called in any thread, with connection's lock held */
6487 handle_generic_introspect_unlocked (GDBusConnection *connection,
6488 const gchar *object_path,
6489 GDBusMessage *message)
6494 GDBusMessage *reply;
6496 /* first the header */
6497 s = g_string_new (NULL);
6498 introspect_append_header (s);
6500 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
6501 for (n = 0; registered != NULL && registered[n] != NULL; n++)
6502 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
6503 g_strfreev (registered);
6504 g_string_append (s, "</node>\n");
6506 reply = g_dbus_message_new_method_reply (message);
6507 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6508 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6509 g_object_unref (reply);
6510 g_string_free (s, TRUE);
6513 /* may be called in any thread, with connection's lock held */
6515 handle_generic_unlocked (GDBusConnection *connection,
6516 GDBusMessage *message)
6519 const gchar *interface_name;
6520 const gchar *member;
6521 const gchar *signature;
6524 CONNECTION_ENSURE_LOCK (connection);
6528 interface_name = g_dbus_message_get_interface (message);
6529 member = g_dbus_message_get_member (message);
6530 signature = g_dbus_message_get_signature (message);
6531 path = g_dbus_message_get_path (message);
6533 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
6534 g_strcmp0 (member, "Introspect") == 0 &&
6535 g_strcmp0 (signature, "") == 0)
6537 handle_generic_introspect_unlocked (connection, path, message);
6540 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6541 g_strcmp0 (member, "Ping") == 0 &&
6542 g_strcmp0 (signature, "") == 0)
6544 handle_generic_ping_unlocked (connection, path, message);
6547 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6548 g_strcmp0 (member, "GetMachineId") == 0 &&
6549 g_strcmp0 (signature, "") == 0)
6551 handle_generic_get_machine_id_unlocked (connection, path, message);
6558 /* ---------------------------------------------------------------------------------------------------- */
6560 /* called in GDBusWorker thread with connection's lock held */
6562 distribute_method_call (GDBusConnection *connection,
6563 GDBusMessage *message)
6565 GDBusMessage *reply;
6567 ExportedSubtree *es;
6568 const gchar *object_path;
6569 const gchar *interface_name;
6570 const gchar *member;
6572 gchar *subtree_path;
6575 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
6577 interface_name = g_dbus_message_get_interface (message);
6578 member = g_dbus_message_get_member (message);
6579 path = g_dbus_message_get_path (message);
6580 subtree_path = g_strdup (path);
6581 needle = strrchr (subtree_path, '/');
6582 if (needle != NULL && needle != subtree_path)
6588 g_free (subtree_path);
6589 subtree_path = NULL;
6593 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
6595 _g_dbus_debug_print_lock ();
6596 g_print ("========================================================================\n"
6597 "GDBus-debug:Incoming:\n"
6598 " <<<< METHOD INVOCATION %s.%s()\n"
6600 " invoked by name %s\n"
6602 interface_name, member,
6604 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
6605 g_dbus_message_get_serial (message));
6606 _g_dbus_debug_print_unlock ();
6609 object_path = g_dbus_message_get_path (message);
6610 g_assert (object_path != NULL);
6612 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
6615 if (obj_message_func (connection, eo, message))
6619 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6622 if (subtree_message_func (connection, es, message))
6626 if (subtree_path != NULL)
6628 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
6631 if (subtree_message_func (connection, es, message))
6636 if (handle_generic_unlocked (connection, message))
6639 /* if we end up here, the message has not been not handled - so return an error saying this */
6640 reply = g_dbus_message_new_method_error (message,
6641 "org.freedesktop.DBus.Error.UnknownMethod",
6642 _("No such interface `%s' on object at path %s"),
6645 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6646 g_object_unref (reply);
6649 g_free (subtree_path);
6652 /* ---------------------------------------------------------------------------------------------------- */
6654 /* Called in any user thread, with the message_bus_lock held. */
6655 static GDBusConnection **
6656 message_bus_get_singleton (GBusType bus_type,
6659 GDBusConnection **ret;
6660 const gchar *starter_bus;
6666 case G_BUS_TYPE_SESSION:
6667 ret = &the_session_bus;
6670 case G_BUS_TYPE_SYSTEM:
6671 ret = &the_system_bus;
6674 case G_BUS_TYPE_STARTER:
6675 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
6676 if (g_strcmp0 (starter_bus, "session") == 0)
6678 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
6681 else if (g_strcmp0 (starter_bus, "system") == 0)
6683 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
6688 if (starter_bus != NULL)
6692 G_IO_ERROR_INVALID_ARGUMENT,
6693 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
6694 " - unknown value `%s'"),
6699 g_set_error_literal (error,
6701 G_IO_ERROR_INVALID_ARGUMENT,
6702 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
6703 "variable is not set"));
6709 g_assert_not_reached ();
6717 /* Called in any user thread, without holding locks. */
6718 static GDBusConnection *
6719 get_uninitialized_connection (GBusType bus_type,
6720 GCancellable *cancellable,
6723 GDBusConnection **singleton;
6724 GDBusConnection *ret;
6728 G_LOCK (message_bus_lock);
6729 singleton = message_bus_get_singleton (bus_type, error);
6730 if (singleton == NULL)
6733 if (*singleton == NULL)
6736 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
6737 if (address == NULL)
6739 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
6741 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
6742 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
6743 "exit-on-close", TRUE,
6749 ret = g_object_ref (*singleton);
6752 g_assert (ret != NULL);
6755 G_UNLOCK (message_bus_lock);
6761 * @bus_type: A #GBusType.
6762 * @cancellable: A #GCancellable or %NULL.
6763 * @error: Return location for error or %NULL.
6765 * Synchronously connects to the message bus specified by @bus_type.
6766 * Note that the returned object may shared with other callers,
6767 * e.g. if two separate parts of a process calls this function with
6768 * the same @bus_type, they will share the same object.
6770 * This is a synchronous failable function. See g_bus_get() and
6771 * g_bus_get_finish() for the asynchronous version.
6773 * The returned object is a singleton, that is, shared with other
6774 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6775 * event that you need a private message bus connection, use
6776 * g_dbus_address_get_for_bus_sync() and
6777 * g_dbus_connection_new_for_address().
6779 * Note that the returned #GDBusConnection object will (usually) have
6780 * the #GDBusConnection:exit-on-close property set to %TRUE.
6782 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6787 g_bus_get_sync (GBusType bus_type,
6788 GCancellable *cancellable,
6791 GDBusConnection *connection;
6793 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6795 connection = get_uninitialized_connection (bus_type, cancellable, error);
6796 if (connection == NULL)
6799 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
6801 g_object_unref (connection);
6810 bus_get_async_initable_cb (GObject *source_object,
6814 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
6818 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
6822 g_assert (error != NULL);
6823 g_simple_async_result_take_error (simple, error);
6824 g_object_unref (source_object);
6828 g_simple_async_result_set_op_res_gpointer (simple,
6832 g_simple_async_result_complete_in_idle (simple);
6833 g_object_unref (simple);
6838 * @bus_type: A #GBusType.
6839 * @cancellable: A #GCancellable or %NULL.
6840 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
6841 * @user_data: The data to pass to @callback.
6843 * Asynchronously connects to the message bus specified by @bus_type.
6845 * When the operation is finished, @callback will be invoked. You can
6846 * then call g_bus_get_finish() to get the result of the operation.
6848 * This is a asynchronous failable function. See g_bus_get_sync() for
6849 * the synchronous version.
6854 g_bus_get (GBusType bus_type,
6855 GCancellable *cancellable,
6856 GAsyncReadyCallback callback,
6859 GDBusConnection *connection;
6860 GSimpleAsyncResult *simple;
6863 simple = g_simple_async_result_new (NULL,
6869 connection = get_uninitialized_connection (bus_type, cancellable, &error);
6870 if (connection == NULL)
6872 g_assert (error != NULL);
6873 g_simple_async_result_take_error (simple, error);
6874 g_simple_async_result_complete_in_idle (simple);
6875 g_object_unref (simple);
6879 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
6882 bus_get_async_initable_cb,
6889 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
6890 * @error: Return location for error or %NULL.
6892 * Finishes an operation started with g_bus_get().
6894 * The returned object is a singleton, that is, shared with other
6895 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6896 * event that you need a private message bus connection, use
6897 * g_dbus_address_get_for_bus_sync() and
6898 * g_dbus_connection_new_for_address().
6900 * Note that the returned #GDBusConnection object will (usually) have
6901 * the #GDBusConnection:exit-on-close property set to %TRUE.
6903 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6908 g_bus_get_finish (GAsyncResult *res,
6911 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
6913 GDBusConnection *ret;
6915 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6917 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
6921 if (g_simple_async_result_propagate_error (simple, error))
6924 object = g_simple_async_result_get_op_res_gpointer (simple);
6925 g_assert (object != NULL);
6926 ret = g_object_ref (G_DBUS_CONNECTION (object));
6932 /* ---------------------------------------------------------------------------------------------------- */