1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, write to the
17 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18 * Boston, MA 02111-1307, USA.
20 * Author: David Zeuthen <davidz@redhat.com>
26 * - would be nice to expose GDBusAuthMechanism and an extension point
28 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
29 * the mechanism VFuncs need to be able to set an error.
31 * - Need to document other mechanisms/sources for determining the D-Bus
32 * address of a well-known bus.
34 * - e.g. on Win32 we need code like from here
36 * http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
38 * that was never copied over here because it originally was copy-paste
39 * from the GPLv2 / AFL 2.1 libdbus sources.
41 * - on OS X we need to look in launchd for the address
43 * https://bugs.freedesktop.org/show_bug.cgi?id=14259
45 * - on X11 we need to look in a X11 property on the X server
46 * - (we can also just use dbus-launch(1) from the D-Bus
49 * - (ideally) this requires D-Bus spec work because none of
50 * this has never really been specced out properly (except
53 * - Related to the above, we also need to be able to launch a message bus
54 * instance.... Since we don't want to write our own bus daemon we should
55 * launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
57 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
58 * to specify where the nonce is stored. This will allow people to use
59 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
60 * to easily achieve secure RPC via nonce-tcp.
62 * - need to expose an extension point for resolving D-Bus address and
63 * turning them into GIOStream objects. This will allow us to implement
64 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
66 * - see g_dbus_address_connect() in gdbusaddress.c
68 * - would be cute to use kernel-specific APIs to resolve fds for
69 * debug output when using G_DBUS_DEBUG=message, e.g. in addition to
71 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
73 * maybe we can show more information about what fd 21 really is.
74 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
75 * Initial experiments on Linux 2.6 suggests that the symlink looks
80 * e.g. not of much use.
82 * - GDBus High-Level docs
83 * - Proxy: properties, signals...
84 * - Connection: IOStream based, ::close, connection setup steps
85 * mainloop integration, threading
86 * - Differences from libdbus (extend "Migrating from")
87 * - the message handling thread
88 * - Using GVariant instead of GValue
89 * - Explain why the high-level API is a good thing and what
90 * kind of pitfalls it avoids
91 * - Export objects before claiming names
92 * - Talk about auto-starting services (cf. GBusNameWatcherFlags)
94 * - use abstract sockets in test code
95 * - right now it doesn't work, dbus-daemon(1) fails with
97 * /gdbus/connection/filter: Failed to start message bus: Failed to bind
98 * socket "/tmp/g-dbus-tests-pid-28531": Address already in use
99 * ** WARNING **: Error reading address from dbus daemon, 0 bytes read
108 #include <sys/types.h>
113 #include "gdbusauth.h"
114 #include "gdbusutils.h"
115 #include "gdbusaddress.h"
116 #include "gdbusmessage.h"
117 #include "gdbusconnection.h"
118 #include "gdbuserror.h"
119 #include "gioenumtypes.h"
120 #include "gdbusintrospection.h"
121 #include "gdbusmethodinvocation.h"
122 #include "gdbusprivate.h"
123 #include "gdbusauthobserver.h"
124 #include "ginitable.h"
125 #include "gasyncinitable.h"
126 #include "giostream.h"
127 #include "gasyncresult.h"
128 #include "gsimpleasyncresult.h"
131 #include "gunixconnection.h"
132 #include "gunixfdmessage.h"
135 #include "glibintl.h"
138 * SECTION:gdbusconnection
139 * @short_description: D-Bus Connections
140 * @include: gio/gio.h
142 * The #GDBusConnection type is used for D-Bus connections to remote
143 * peers such as a message buses. It is a low-level API that offers a
144 * lot of flexibility. For instance, it lets you establish a connection
145 * over any transport that can by represented as an #GIOStream.
147 * This class is rarely used directly in D-Bus clients. If you are writing
148 * an D-Bus client, it is often easier to use the g_bus_own_name(),
149 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
151 * As an exception to the usual GLib rule that a particular object must not be
152 * used by two threads at the same time, #GDBusConnection's methods may be
153 * called from any thread<footnote>
155 * This is so that g_bus_get() and g_bus_get_sync() can safely return the
156 * same #GDBusConnection when called from any thread.
160 * Most of the ways to obtain a #GDBusConnection automatically initialize it
161 * (i.e. connect to D-Bus): for instance, g_dbus_connection_new() and
162 * g_bus_get(), and the synchronous versions of those methods, give you an
163 * initialized connection. Language bindings for GIO should use
164 * g_initable_new() or g_async_initable_new_async(), which also initialize the
167 * If you construct an uninitialized #GDBusConnection, such as via
168 * g_object_new(), you must initialize it via g_initable_init() or
169 * g_async_initable_init_async() before using its methods or properties.
170 * Calling methods or accessing properties on a #GDBusConnection that has not
171 * completed initialization successfully is considered to be invalid, and leads
172 * to undefined behaviour. In particular, if initialization fails with a
173 * #GError, the only valid thing you can do with that #GDBusConnection is to
174 * free it with g_object_unref().
176 * <example id="gdbus-server"><title>D-Bus server example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-server.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
178 * <example id="gdbus-subtree-server"><title>D-Bus subtree example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-subtree.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
180 * <example id="gdbus-unix-fd-client"><title>D-Bus UNIX File Descriptor example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-unix-fd-client.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
182 * <example id="gdbus-export"><title>Exporting a GObject</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-export.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
185 /* ---------------------------------------------------------------------------------------------------- */
187 typedef struct _GDBusConnectionClass GDBusConnectionClass;
190 * GDBusConnectionClass:
191 * @closed: Signal class handler for the #GDBusConnection::closed signal.
193 * Class structure for #GDBusConnection.
197 struct _GDBusConnectionClass
200 GObjectClass parent_class;
204 void (*closed) (GDBusConnection *connection,
205 gboolean remote_peer_vanished,
209 G_LOCK_DEFINE_STATIC (message_bus_lock);
211 static GWeakRef the_session_bus;
212 static GWeakRef the_system_bus;
214 /* Extra pseudo-member of GDBusSendMessageFlags.
215 * Set by initable_init() to indicate that despite not being initialized yet,
216 * enough of the only-valid-after-init members are set that we can send a
217 * message, and we're being called from its thread, so no memory barrier is
218 * required before accessing them.
220 #define SEND_MESSAGE_FLAGS_INITIALIZING (1<<31)
222 /* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
223 #define CALL_FLAGS_INITIALIZING (1<<31)
225 /* ---------------------------------------------------------------------------------------------------- */
229 GDestroyNotify callback;
231 GMainContext *context;
232 } CallDestroyNotifyData;
235 call_destroy_notify_data_in_idle (gpointer user_data)
237 CallDestroyNotifyData *data = user_data;
238 data->callback (data->user_data);
243 call_destroy_notify_data_free (CallDestroyNotifyData *data)
245 if (data->context != NULL)
246 g_main_context_unref (data->context);
251 * call_destroy_notify: <internal>
252 * @context: (allow-none): A #GMainContext or %NULL.
253 * @callback: (allow-none): A #GDestroyNotify or %NULL.
254 * @user_data: Data to pass to @callback.
256 * Schedules @callback to run in @context.
259 call_destroy_notify (GMainContext *context,
260 GDestroyNotify callback,
263 GSource *idle_source;
264 CallDestroyNotifyData *data;
266 if (callback == NULL)
269 data = g_new0 (CallDestroyNotifyData, 1);
270 data->callback = callback;
271 data->user_data = user_data;
272 data->context = context;
273 if (data->context != NULL)
274 g_main_context_ref (data->context);
276 idle_source = g_idle_source_new ();
277 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
278 g_source_set_callback (idle_source,
279 call_destroy_notify_data_in_idle,
281 (GDestroyNotify) call_destroy_notify_data_free);
282 g_source_attach (idle_source, data->context);
283 g_source_unref (idle_source);
289 /* ---------------------------------------------------------------------------------------------------- */
292 _g_strv_has_string (const gchar* const *haystack,
297 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
299 if (g_strcmp0 (haystack[n], needle) == 0)
305 /* ---------------------------------------------------------------------------------------------------- */
308 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
310 // TODO: for some reason this doesn't work on Windows
311 #define CONNECTION_ENSURE_LOCK(obj) do { \
312 if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock))) \
314 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
315 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
320 #define CONNECTION_LOCK(obj) do { \
321 g_mutex_lock (&(obj)->lock); \
324 #define CONNECTION_UNLOCK(obj) do { \
325 g_mutex_unlock (&(obj)->lock); \
328 /* Flags in connection->atomic_flags */
330 FLAG_INITIALIZED = 1 << 0,
331 FLAG_EXIT_ON_CLOSE = 1 << 1,
338 * The #GDBusConnection structure contains only private data and
339 * should only be accessed using the provided API.
343 struct _GDBusConnection
346 GObject parent_instance;
348 /* ------------------------------------------------------------------------ */
349 /* -- General object state ------------------------------------------------ */
350 /* ------------------------------------------------------------------------ */
352 /* General-purpose lock for most fields */
355 /* A lock used in the init() method of the GInitable interface - see comments
356 * in initable_init() for why a separate lock is needed.
358 * If you need both @lock and @init_lock, you must take @init_lock first.
362 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
363 * someone calls org.freedesktop.DBus.GetMachineId(). Protected by @lock.
367 /* The underlying stream used for communication
368 * Read-only after initable_init(), so it may be read if you either
369 * hold @init_lock or check for initialization first.
373 /* The object used for authentication (if any).
374 * Read-only after initable_init(), so it may be read if you either
375 * hold @init_lock or check for initialization first.
379 /* Last serial used. Protected by @lock. */
382 /* The object used to send/receive messages.
383 * Read-only after initable_init(), so it may be read if you either
384 * hold @init_lock or check for initialization first.
388 /* If connected to a message bus, this contains the unique name assigned to
389 * us by the bus (e.g. ":1.42").
390 * Read-only after initable_init(), so it may be read if you either
391 * hold @init_lock or check for initialization first.
393 gchar *bus_unique_name;
395 /* The GUID returned by the other side if we authenticed as a client or
396 * the GUID to use if authenticating as a server.
397 * Read-only after initable_init(), so it may be read if you either
398 * hold @init_lock or check for initialization first.
402 /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
403 * Inspect @initialization_error to see whether it succeeded or failed.
405 * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
407 * FLAG_CLOSED is the closed property. It may be read at any time, but
408 * may only be written while holding @lock.
410 volatile gint atomic_flags;
412 /* If the connection could not be established during initable_init(),
413 * this GError will be set.
414 * Read-only after initable_init(), so it may be read if you either
415 * hold @init_lock or check for initialization first.
417 GError *initialization_error;
419 /* The result of g_main_context_ref_thread_default() when the object
420 * was created (the GObject _init() function) - this is used for delivery
421 * of the :closed GObject signal.
423 * Only set in the GObject init function, so no locks are needed.
425 GMainContext *main_context_at_construction;
427 /* Read-only construct properties, no locks needed */
429 GDBusConnectionFlags flags;
431 /* Map used for managing method replies, protected by @lock */
432 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
434 /* Maps used for managing signal subscription, protected by @lock */
435 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
436 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
437 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
439 /* Maps used for managing exported objects and subtrees,
442 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
443 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
444 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
445 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
447 /* 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 CONNECTION_LOCK (connection);
610 if (connection->worker != NULL)
612 _g_dbus_worker_stop (connection->worker);
613 connection->worker = NULL;
614 if (alive_connections != NULL)
615 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
619 if (alive_connections != NULL)
620 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
622 CONNECTION_UNLOCK (connection);
623 G_UNLOCK (message_bus_lock);
625 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
626 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
630 g_dbus_connection_finalize (GObject *object)
632 GDBusConnection *connection = G_DBUS_CONNECTION (object);
634 connection->finalizing = TRUE;
636 purge_all_signal_subscriptions (connection);
638 purge_all_filters (connection);
639 g_ptr_array_unref (connection->filters);
641 if (connection->authentication_observer != NULL)
642 g_object_unref (connection->authentication_observer);
644 if (connection->auth != NULL)
645 g_object_unref (connection->auth);
647 if (connection->credentials)
648 g_object_unref (connection->credentials);
650 if (connection->stream != NULL)
652 g_object_unref (connection->stream);
653 connection->stream = NULL;
656 g_free (connection->address);
658 g_free (connection->guid);
659 g_free (connection->bus_unique_name);
661 if (connection->initialization_error != NULL)
662 g_error_free (connection->initialization_error);
664 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
666 g_hash_table_unref (connection->map_rule_to_signal_data);
667 g_hash_table_unref (connection->map_id_to_signal_data);
668 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
670 g_hash_table_unref (connection->map_id_to_ei);
671 g_hash_table_unref (connection->map_object_path_to_eo);
672 g_hash_table_unref (connection->map_id_to_es);
673 g_hash_table_unref (connection->map_object_path_to_es);
675 g_main_context_unref (connection->main_context_at_construction);
677 g_free (connection->machine_id);
679 g_mutex_clear (&connection->init_lock);
680 g_mutex_clear (&connection->lock);
682 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
685 /* called in any user thread, with the connection's lock not held */
687 g_dbus_connection_get_property (GObject *object,
692 GDBusConnection *connection = G_DBUS_CONNECTION (object);
697 g_value_set_object (value, g_dbus_connection_get_stream (connection));
701 g_value_set_string (value, g_dbus_connection_get_guid (connection));
704 case PROP_UNIQUE_NAME:
705 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
709 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
712 case PROP_EXIT_ON_CLOSE:
713 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
716 case PROP_CAPABILITY_FLAGS:
717 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
721 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
726 /* called in any user thread, with the connection's lock not held */
728 g_dbus_connection_set_property (GObject *object,
733 GDBusConnection *connection = G_DBUS_CONNECTION (object);
738 connection->stream = g_value_dup_object (value);
742 connection->guid = g_value_dup_string (value);
746 connection->address = g_value_dup_string (value);
750 connection->flags = g_value_get_flags (value);
753 case PROP_EXIT_ON_CLOSE:
754 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
757 case PROP_AUTHENTICATION_OBSERVER:
758 connection->authentication_observer = g_value_dup_object (value);
762 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
767 /* Base-class implementation of GDBusConnection::closed.
769 * Called in a user thread, by the main context that was thread-default when
770 * the object was constructed.
773 g_dbus_connection_real_closed (GDBusConnection *connection,
774 gboolean remote_peer_vanished,
777 gint flags = g_atomic_int_get (&connection->atomic_flags);
779 /* Because atomic int access is a memory barrier, we can safely read
780 * initialization_error without a lock, as long as we do it afterwards.
782 if (remote_peer_vanished &&
783 (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
784 (flags & FLAG_INITIALIZED) != 0 &&
785 connection->initialization_error == NULL)
789 g_print ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
792 g_quark_to_string (error->domain), error->code);
796 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
803 g_dbus_connection_class_init (GDBusConnectionClass *klass)
805 GObjectClass *gobject_class;
807 gobject_class = G_OBJECT_CLASS (klass);
809 gobject_class->finalize = g_dbus_connection_finalize;
810 gobject_class->dispose = g_dbus_connection_dispose;
811 gobject_class->set_property = g_dbus_connection_set_property;
812 gobject_class->get_property = g_dbus_connection_get_property;
814 klass->closed = g_dbus_connection_real_closed;
817 * GDBusConnection:stream:
819 * The underlying #GIOStream used for I/O.
821 * If this is passed on construction and is a #GSocketConnection,
822 * then the corresponding #GSocket will be put into non-blocking mode.
824 * While the #GDBusConnection is active, it will interact with this
825 * stream from a worker thread, so it is not safe to interact with
826 * the stream directly.
830 g_object_class_install_property (gobject_class,
832 g_param_spec_object ("stream",
834 P_("The underlying streams used for I/O"),
838 G_PARAM_CONSTRUCT_ONLY |
839 G_PARAM_STATIC_NAME |
840 G_PARAM_STATIC_BLURB |
841 G_PARAM_STATIC_NICK));
844 * GDBusConnection:address:
846 * A D-Bus address specifying potential endpoints that can be used
847 * when establishing the connection.
851 g_object_class_install_property (gobject_class,
853 g_param_spec_string ("address",
855 P_("D-Bus address specifying potential socket endpoints"),
858 G_PARAM_CONSTRUCT_ONLY |
859 G_PARAM_STATIC_NAME |
860 G_PARAM_STATIC_BLURB |
861 G_PARAM_STATIC_NICK));
864 * GDBusConnection:flags:
866 * Flags from the #GDBusConnectionFlags enumeration.
870 g_object_class_install_property (gobject_class,
872 g_param_spec_flags ("flags",
875 G_TYPE_DBUS_CONNECTION_FLAGS,
876 G_DBUS_CONNECTION_FLAGS_NONE,
878 G_PARAM_CONSTRUCT_ONLY |
879 G_PARAM_STATIC_NAME |
880 G_PARAM_STATIC_BLURB |
881 G_PARAM_STATIC_NICK));
884 * GDBusConnection:guid:
886 * The GUID of the peer performing the role of server when
889 * If you are constructing a #GDBusConnection and pass
890 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
891 * #GDBusConnection:flags property then you MUST also set this
892 * property to a valid guid.
894 * If you are constructing a #GDBusConnection and pass
895 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
896 * #GDBusConnection:flags property you will be able to read the GUID
897 * of the other peer here after the connection has been successfully
902 g_object_class_install_property (gobject_class,
904 g_param_spec_string ("guid",
906 P_("GUID of the server peer"),
910 G_PARAM_CONSTRUCT_ONLY |
911 G_PARAM_STATIC_NAME |
912 G_PARAM_STATIC_BLURB |
913 G_PARAM_STATIC_NICK));
916 * GDBusConnection:unique-name:
918 * The unique name as assigned by the message bus or %NULL if the
919 * connection is not open or not a message bus connection.
923 g_object_class_install_property (gobject_class,
925 g_param_spec_string ("unique-name",
927 P_("Unique name of bus connection"),
930 G_PARAM_STATIC_NAME |
931 G_PARAM_STATIC_BLURB |
932 G_PARAM_STATIC_NICK));
935 * GDBusConnection:closed:
937 * A boolean specifying whether the connection has been closed.
941 g_object_class_install_property (gobject_class,
943 g_param_spec_boolean ("closed",
945 P_("Whether the connection is closed"),
948 G_PARAM_STATIC_NAME |
949 G_PARAM_STATIC_BLURB |
950 G_PARAM_STATIC_NICK));
953 * GDBusConnection:exit-on-close:
955 * A boolean specifying whether the process will be terminated (by
956 * calling <literal>raise(SIGTERM)</literal>) if the connection
957 * is closed by the remote peer.
959 * Note that #GDBusConnection objects returned by g_bus_get_finish() and
960 * g_bus_get_sync() will (usually) have this property set to %TRUE.
964 g_object_class_install_property (gobject_class,
966 g_param_spec_boolean ("exit-on-close",
968 P_("Whether the process is terminated when the connection is closed"),
972 G_PARAM_STATIC_NAME |
973 G_PARAM_STATIC_BLURB |
974 G_PARAM_STATIC_NICK));
977 * GDBusConnection:capabilities:
979 * Flags from the #GDBusCapabilityFlags enumeration
980 * representing connection features negotiated with the other peer.
984 g_object_class_install_property (gobject_class,
985 PROP_CAPABILITY_FLAGS,
986 g_param_spec_flags ("capabilities",
989 G_TYPE_DBUS_CAPABILITY_FLAGS,
990 G_DBUS_CAPABILITY_FLAGS_NONE,
992 G_PARAM_STATIC_NAME |
993 G_PARAM_STATIC_BLURB |
994 G_PARAM_STATIC_NICK));
997 * GDBusConnection:authentication-observer:
999 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
1003 g_object_class_install_property (gobject_class,
1004 PROP_AUTHENTICATION_OBSERVER,
1005 g_param_spec_object ("authentication-observer",
1006 P_("Authentication Observer"),
1007 P_("Object used to assist in the authentication process"),
1008 G_TYPE_DBUS_AUTH_OBSERVER,
1010 G_PARAM_CONSTRUCT_ONLY |
1011 G_PARAM_STATIC_NAME |
1012 G_PARAM_STATIC_BLURB |
1013 G_PARAM_STATIC_NICK));
1016 * GDBusConnection::closed:
1017 * @connection: The #GDBusConnection emitting the signal.
1018 * @remote_peer_vanished: %TRUE if @connection is closed because the
1019 * remote peer closed its end of the connection.
1020 * @error: A #GError with more details about the event or %NULL.
1022 * Emitted when the connection is closed.
1024 * The cause of this event can be
1027 * If g_dbus_connection_close() is called. In this case
1028 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
1029 * </para></listitem>
1031 * If the remote peer closes the connection. In this case
1032 * @remote_peer_vanished is set to %TRUE and @error is set.
1033 * </para></listitem>
1035 * If the remote peer sends invalid or malformed data. In this
1036 * case @remote_peer_vanished is set to %FALSE and @error
1038 * </para></listitem>
1041 * Upon receiving this signal, you should give up your reference to
1042 * @connection. You are guaranteed that this signal is emitted only
1047 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
1048 G_TYPE_DBUS_CONNECTION,
1050 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1061 g_dbus_connection_init (GDBusConnection *connection)
1063 g_mutex_init (&connection->lock);
1064 g_mutex_init (&connection->init_lock);
1066 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
1068 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1070 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1072 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1075 (GDestroyNotify) g_ptr_array_unref);
1077 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1080 (GDestroyNotify) exported_object_free);
1082 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1085 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1088 (GDestroyNotify) exported_subtree_free);
1090 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1093 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1095 connection->filters = g_ptr_array_new ();
1099 * g_dbus_connection_get_stream:
1100 * @connection: a #GDBusConnection
1102 * Gets the underlying stream used for IO.
1104 * While the #GDBusConnection is active, it will interact with this
1105 * stream from a worker thread, so it is not safe to interact with
1106 * the stream directly.
1108 * Returns: (transfer none): the stream used for IO
1113 g_dbus_connection_get_stream (GDBusConnection *connection)
1115 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1117 /* do not use g_return_val_if_fail(), we want the memory barrier */
1118 if (!check_initialized (connection))
1121 return connection->stream;
1125 * g_dbus_connection_start_message_processing:
1126 * @connection: A #GDBusConnection.
1128 * If @connection was created with
1129 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1130 * starts processing messages. Does nothing on if @connection wasn't
1131 * created with this flag or if the method has already been called.
1136 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1138 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1140 /* do not use g_return_val_if_fail(), we want the memory barrier */
1141 if (!check_initialized (connection))
1144 g_assert (connection->worker != NULL);
1145 _g_dbus_worker_unfreeze (connection->worker);
1149 * g_dbus_connection_is_closed:
1150 * @connection: A #GDBusConnection.
1152 * Gets whether @connection is closed.
1154 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
1159 g_dbus_connection_is_closed (GDBusConnection *connection)
1163 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1165 flags = g_atomic_int_get (&connection->atomic_flags);
1167 return (flags & FLAG_CLOSED) ? TRUE : FALSE;
1171 * g_dbus_connection_get_capabilities:
1172 * @connection: A #GDBusConnection.
1174 * Gets the capabilities negotiated with the remote peer
1176 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
1180 GDBusCapabilityFlags
1181 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1183 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1185 /* do not use g_return_val_if_fail(), we want the memory barrier */
1186 if (!check_initialized (connection))
1187 return G_DBUS_CAPABILITY_FLAGS_NONE;
1189 return connection->capabilities;
1192 /* ---------------------------------------------------------------------------------------------------- */
1194 /* Called in a temporary thread without holding locks. */
1196 flush_in_thread_func (GSimpleAsyncResult *res,
1198 GCancellable *cancellable)
1203 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1206 g_simple_async_result_take_error (res, error);
1210 * g_dbus_connection_flush:
1211 * @connection: A #GDBusConnection.
1212 * @cancellable: (allow-none): A #GCancellable or %NULL.
1213 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1214 * satisfied or %NULL if you don't care about the result.
1215 * @user_data: The data to pass to @callback.
1217 * Asynchronously flushes @connection, that is, writes all queued
1218 * outgoing message to the transport and then flushes the transport
1219 * (using g_output_stream_flush_async()). This is useful in programs
1220 * that wants to emit a D-Bus signal and then exit
1221 * immediately. Without flushing the connection, there is no guarantee
1222 * that the message has been sent to the networking buffers in the OS
1225 * This is an asynchronous method. When the operation is finished,
1226 * @callback will be invoked in the <link
1227 * linkend="g-main-context-push-thread-default">thread-default main
1228 * loop</link> of the thread you are calling this method from. You can
1229 * then call g_dbus_connection_flush_finish() to get the result of the
1230 * operation. See g_dbus_connection_flush_sync() for the synchronous
1236 g_dbus_connection_flush (GDBusConnection *connection,
1237 GCancellable *cancellable,
1238 GAsyncReadyCallback callback,
1241 GSimpleAsyncResult *simple;
1243 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1245 simple = g_simple_async_result_new (G_OBJECT (connection),
1248 g_dbus_connection_flush);
1249 g_simple_async_result_set_check_cancellable (simple, cancellable);
1250 g_simple_async_result_run_in_thread (simple,
1251 flush_in_thread_func,
1254 g_object_unref (simple);
1258 * g_dbus_connection_flush_finish:
1259 * @connection: A #GDBusConnection.
1260 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_flush().
1261 * @error: Return location for error or %NULL.
1263 * Finishes an operation started with g_dbus_connection_flush().
1265 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1270 g_dbus_connection_flush_finish (GDBusConnection *connection,
1274 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1279 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1280 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1281 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1283 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1285 if (g_simple_async_result_propagate_error (simple, error))
1295 * g_dbus_connection_flush_sync:
1296 * @connection: A #GDBusConnection.
1297 * @cancellable: (allow-none): A #GCancellable or %NULL.
1298 * @error: Return location for error or %NULL.
1300 * Synchronously flushes @connection. The calling thread is blocked
1301 * until this is done. See g_dbus_connection_flush() for the
1302 * asynchronous version of this method and more details about what it
1305 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1310 g_dbus_connection_flush_sync (GDBusConnection *connection,
1311 GCancellable *cancellable,
1316 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1317 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1321 /* This is only a best-effort attempt to see whether the connection is
1322 * closed, so it doesn't need the lock. If the connection closes just
1323 * after this check, but before scheduling the flush operation, the
1324 * result will be more or less the same as if the connection closed while
1325 * the flush operation was pending - it'll fail with either CLOSED or
1328 if (!check_unclosed (connection, 0, error))
1331 g_assert (connection->worker != NULL);
1333 ret = _g_dbus_worker_flush_sync (connection->worker,
1341 /* ---------------------------------------------------------------------------------------------------- */
1345 GDBusConnection *connection;
1347 gboolean remote_peer_vanished;
1351 emit_closed_data_free (EmitClosedData *data)
1353 g_object_unref (data->connection);
1354 if (data->error != NULL)
1355 g_error_free (data->error);
1359 /* Called in a user thread that has acquired the main context that was
1360 * thread-default when the object was constructed
1363 emit_closed_in_idle (gpointer user_data)
1365 EmitClosedData *data = user_data;
1368 g_object_notify (G_OBJECT (data->connection), "closed");
1369 g_signal_emit (data->connection,
1370 signals[CLOSED_SIGNAL],
1372 data->remote_peer_vanished,
1378 /* Can be called from any thread, must hold lock.
1379 * FLAG_CLOSED must already have been set.
1382 schedule_closed_unlocked (GDBusConnection *connection,
1383 gboolean remote_peer_vanished,
1386 GSource *idle_source;
1387 EmitClosedData *data;
1389 CONNECTION_ENSURE_LOCK (connection);
1391 data = g_new0 (EmitClosedData, 1);
1392 data->connection = g_object_ref (connection);
1393 data->remote_peer_vanished = remote_peer_vanished;
1394 data->error = error != NULL ? g_error_copy (error) : NULL;
1396 idle_source = g_idle_source_new ();
1397 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1398 g_source_set_callback (idle_source,
1399 emit_closed_in_idle,
1401 (GDestroyNotify) emit_closed_data_free);
1402 g_source_attach (idle_source, connection->main_context_at_construction);
1403 g_source_unref (idle_source);
1406 /* ---------------------------------------------------------------------------------------------------- */
1409 * g_dbus_connection_close:
1410 * @connection: A #GDBusConnection.
1411 * @cancellable: (allow-none): A #GCancellable or %NULL.
1412 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1413 * satisfied or %NULL if you don't care about the result.
1414 * @user_data: The data to pass to @callback.
1416 * Closes @connection. Note that this never causes the process to
1417 * exit (this might only happen if the other end of a shared message
1418 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1420 * Once the connection is closed, operations such as sending a message
1421 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1422 * will not automatically flush the connection so queued messages may
1423 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1425 * If @connection is already closed, this method fails with
1426 * %G_IO_ERROR_CLOSED.
1428 * When @connection has been closed, the #GDBusConnection::closed
1429 * signal is emitted in the <link
1430 * linkend="g-main-context-push-thread-default">thread-default main
1431 * loop</link> of the thread that @connection was constructed in.
1433 * This is an asynchronous method. When the operation is finished,
1434 * @callback will be invoked in the <link
1435 * linkend="g-main-context-push-thread-default">thread-default main
1436 * loop</link> of the thread you are calling this method from. You can
1437 * then call g_dbus_connection_close_finish() to get the result of the
1438 * operation. See g_dbus_connection_close_sync() for the synchronous
1444 g_dbus_connection_close (GDBusConnection *connection,
1445 GCancellable *cancellable,
1446 GAsyncReadyCallback callback,
1449 GSimpleAsyncResult *simple;
1451 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1453 /* do not use g_return_val_if_fail(), we want the memory barrier */
1454 if (!check_initialized (connection))
1457 g_assert (connection->worker != NULL);
1459 simple = g_simple_async_result_new (G_OBJECT (connection),
1462 g_dbus_connection_close);
1463 g_simple_async_result_set_check_cancellable (simple, cancellable);
1464 _g_dbus_worker_close (connection->worker, cancellable, simple);
1465 g_object_unref (simple);
1469 * g_dbus_connection_close_finish:
1470 * @connection: A #GDBusConnection.
1471 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_close().
1472 * @error: Return location for error or %NULL.
1474 * Finishes an operation started with g_dbus_connection_close().
1476 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1481 g_dbus_connection_close_finish (GDBusConnection *connection,
1485 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1490 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1491 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1492 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1494 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1496 if (g_simple_async_result_propagate_error (simple, error))
1507 GAsyncResult *result;
1510 /* Can be called by any thread, without the connection lock */
1512 sync_close_cb (GObject *source_object,
1516 SyncCloseData *data = user_data;
1518 data->result = g_object_ref (res);
1519 g_main_loop_quit (data->loop);
1523 * g_dbus_connection_close_sync:
1524 * @connection: A #GDBusConnection.
1525 * @cancellable: (allow-none): A #GCancellable or %NULL.
1526 * @error: Return location for error or %NULL.
1528 * Synchronously closees @connection. The calling thread is blocked
1529 * until this is done. See g_dbus_connection_close() for the
1530 * asynchronous version of this method and more details about what it
1533 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1538 g_dbus_connection_close_sync (GDBusConnection *connection,
1539 GCancellable *cancellable,
1544 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1545 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1549 if (check_unclosed (connection, 0, error))
1551 GMainContext *context;
1554 context = g_main_context_new ();
1555 g_main_context_push_thread_default (context);
1556 data.loop = g_main_loop_new (context, TRUE);
1559 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1560 g_main_loop_run (data.loop);
1561 ret = g_dbus_connection_close_finish (connection, data.result, error);
1563 g_object_unref (data.result);
1564 g_main_loop_unref (data.loop);
1565 g_main_context_pop_thread_default (context);
1566 g_main_context_unref (context);
1572 /* ---------------------------------------------------------------------------------------------------- */
1574 /* Can be called by any thread, with the connection lock held */
1576 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1577 GDBusMessage *message,
1578 GDBusSendMessageFlags flags,
1579 volatile guint32 *out_serial,
1584 guint32 serial_to_use;
1587 CONNECTION_ENSURE_LOCK (connection);
1589 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1590 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1592 /* TODO: check all necessary headers are present */
1597 if (out_serial != NULL)
1600 /* If we're in initable_init(), don't check for being initialized, to avoid
1601 * chicken-and-egg problems. initable_init() is responsible for setting up
1602 * our prerequisites (mainly connection->worker), and only calling us
1603 * from its own thread (so no memory barrier is needed).
1605 if (!check_unclosed (connection,
1606 (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
1610 blob = g_dbus_message_to_blob (message,
1612 connection->capabilities,
1617 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1618 serial_to_use = g_dbus_message_get_serial (message);
1620 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1625 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1628 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1631 g_assert_not_reached ();
1636 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1637 blob_size, serial_to_use, connection);
1638 g_printerr ("----\n");
1639 hexdump (blob, blob_size);
1640 g_printerr ("----\n");
1643 /* TODO: use connection->auth to encode the blob */
1645 if (out_serial != NULL)
1646 *out_serial = serial_to_use;
1648 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
1649 g_dbus_message_set_serial (message, serial_to_use);
1651 g_dbus_message_lock (message);
1652 _g_dbus_worker_send_message (connection->worker,
1656 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1667 * g_dbus_connection_send_message:
1668 * @connection: A #GDBusConnection.
1669 * @message: A #GDBusMessage
1670 * @flags: Flags affecting how the message is sent.
1671 * @out_serial: (out) (allow-none): Return location for serial number assigned
1672 * to @message when sending it or %NULL.
1673 * @error: Return location for error or %NULL.
1675 * Asynchronously sends @message to the peer represented by @connection.
1677 * Unless @flags contain the
1678 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1679 * will be assigned by @connection and set on @message via
1680 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1681 * serial number used will be written to this location prior to
1682 * submitting the message to the underlying transport.
1684 * If @connection is closed then the operation will fail with
1685 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1686 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1688 * See <xref linkend="gdbus-server"/> and <xref
1689 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1690 * low-level API to send and receive UNIX file descriptors.
1692 * Note that @message must be unlocked, unless @flags contain the
1693 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1695 * Returns: %TRUE if the message was well-formed and queued for
1696 * transmission, %FALSE if @error is set.
1701 g_dbus_connection_send_message (GDBusConnection *connection,
1702 GDBusMessage *message,
1703 GDBusSendMessageFlags flags,
1704 volatile guint32 *out_serial,
1709 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1710 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1711 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1712 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1714 CONNECTION_LOCK (connection);
1715 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1716 CONNECTION_UNLOCK (connection);
1720 /* ---------------------------------------------------------------------------------------------------- */
1724 volatile gint ref_count;
1725 GDBusConnection *connection;
1727 GSimpleAsyncResult *simple;
1729 GMainContext *main_context;
1731 GCancellable *cancellable;
1733 gulong cancellable_handler_id;
1735 GSource *timeout_source;
1740 /* Can be called from any thread with or without lock held */
1741 static SendMessageData *
1742 send_message_data_ref (SendMessageData *data)
1744 g_atomic_int_inc (&data->ref_count);
1748 /* Can be called from any thread with or without lock held */
1750 send_message_data_unref (SendMessageData *data)
1752 if (g_atomic_int_dec_and_test (&data->ref_count))
1754 g_assert (data->timeout_source == NULL);
1755 g_assert (data->simple == NULL);
1756 g_assert (data->cancellable_handler_id == 0);
1757 g_object_unref (data->connection);
1758 if (data->cancellable != NULL)
1759 g_object_unref (data->cancellable);
1760 g_main_context_unref (data->main_context);
1765 /* ---------------------------------------------------------------------------------------------------- */
1767 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1769 send_message_with_reply_deliver (SendMessageData *data, gboolean remove)
1771 CONNECTION_ENSURE_LOCK (data->connection);
1773 g_assert (!data->delivered);
1775 data->delivered = TRUE;
1777 g_simple_async_result_complete_in_idle (data->simple);
1778 g_object_unref (data->simple);
1779 data->simple = NULL;
1781 if (data->timeout_source != NULL)
1783 g_source_destroy (data->timeout_source);
1784 data->timeout_source = NULL;
1786 if (data->cancellable_handler_id > 0)
1788 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1789 data->cancellable_handler_id = 0;
1794 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
1795 GUINT_TO_POINTER (data->serial)));
1798 send_message_data_unref (data);
1801 /* ---------------------------------------------------------------------------------------------------- */
1803 /* Can be called from any thread with lock held */
1805 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1806 GDBusMessage *reply)
1808 if (data->delivered)
1811 g_simple_async_result_set_op_res_gpointer (data->simple,
1812 g_object_ref (reply),
1815 send_message_with_reply_deliver (data, TRUE);
1821 /* ---------------------------------------------------------------------------------------------------- */
1823 /* Called from a user thread, lock is not held */
1825 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1827 SendMessageData *data = user_data;
1829 CONNECTION_LOCK (data->connection);
1830 if (data->delivered)
1833 g_simple_async_result_set_error (data->simple,
1835 G_IO_ERROR_CANCELLED,
1836 _("Operation was cancelled"));
1838 send_message_with_reply_deliver (data, TRUE);
1841 CONNECTION_UNLOCK (data->connection);
1845 /* Can be called from any thread with or without lock held */
1847 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1850 SendMessageData *data = user_data;
1851 GSource *idle_source;
1853 /* postpone cancellation to idle handler since we may be called directly
1854 * via g_cancellable_connect() (e.g. holding lock)
1856 idle_source = g_idle_source_new ();
1857 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1858 g_source_set_callback (idle_source,
1859 send_message_with_reply_cancelled_idle_cb,
1860 send_message_data_ref (data),
1861 (GDestroyNotify) send_message_data_unref);
1862 g_source_attach (idle_source, data->main_context);
1863 g_source_unref (idle_source);
1866 /* ---------------------------------------------------------------------------------------------------- */
1868 /* Called from a user thread, lock is not held */
1870 send_message_with_reply_timeout_cb (gpointer user_data)
1872 SendMessageData *data = user_data;
1874 CONNECTION_LOCK (data->connection);
1875 if (data->delivered)
1878 g_simple_async_result_set_error (data->simple,
1880 G_IO_ERROR_TIMED_OUT,
1881 _("Timeout was reached"));
1883 send_message_with_reply_deliver (data, TRUE);
1886 CONNECTION_UNLOCK (data->connection);
1891 /* ---------------------------------------------------------------------------------------------------- */
1893 /* Called from a user thread, connection's lock is held */
1895 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1896 GDBusMessage *message,
1897 GDBusSendMessageFlags flags,
1899 volatile guint32 *out_serial,
1900 GCancellable *cancellable,
1901 GAsyncReadyCallback callback,
1904 GSimpleAsyncResult *simple;
1905 SendMessageData *data;
1907 volatile guint32 serial;
1911 if (out_serial == NULL)
1912 out_serial = &serial;
1914 if (timeout_msec == -1)
1915 timeout_msec = 25 * 1000;
1917 simple = g_simple_async_result_new (G_OBJECT (connection),
1920 g_dbus_connection_send_message_with_reply);
1921 g_simple_async_result_set_check_cancellable (simple, cancellable);
1923 if (g_cancellable_is_cancelled (cancellable))
1925 g_simple_async_result_set_error (simple,
1927 G_IO_ERROR_CANCELLED,
1928 _("Operation was cancelled"));
1929 g_simple_async_result_complete_in_idle (simple);
1930 g_object_unref (simple);
1935 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1937 g_simple_async_result_take_error (simple, error);
1938 g_simple_async_result_complete_in_idle (simple);
1939 g_object_unref (simple);
1943 data = g_new0 (SendMessageData, 1);
1944 data->ref_count = 1;
1945 data->connection = g_object_ref (connection);
1946 data->simple = simple;
1947 data->serial = *out_serial;
1948 data->main_context = g_main_context_ref_thread_default ();
1950 if (cancellable != NULL)
1952 data->cancellable = g_object_ref (cancellable);
1953 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1954 G_CALLBACK (send_message_with_reply_cancelled_cb),
1955 send_message_data_ref (data),
1956 (GDestroyNotify) send_message_data_unref);
1959 if (timeout_msec != G_MAXINT)
1961 data->timeout_source = g_timeout_source_new (timeout_msec);
1962 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1963 g_source_set_callback (data->timeout_source,
1964 send_message_with_reply_timeout_cb,
1965 send_message_data_ref (data),
1966 (GDestroyNotify) send_message_data_unref);
1967 g_source_attach (data->timeout_source, data->main_context);
1968 g_source_unref (data->timeout_source);
1971 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
1972 GUINT_TO_POINTER (*out_serial),
1980 * g_dbus_connection_send_message_with_reply:
1981 * @connection: A #GDBusConnection.
1982 * @message: A #GDBusMessage.
1983 * @flags: Flags affecting how the message is sent.
1984 * @timeout_msec: The timeout in milliseconds, -1 to use the default
1985 * timeout or %G_MAXINT for no timeout.
1986 * @out_serial: (out) (allow-none): Return location for serial number assigned
1987 * to @message when sending it or %NULL.
1988 * @cancellable: (allow-none): A #GCancellable or %NULL.
1989 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1990 * satisfied or %NULL if you don't care about the result.
1991 * @user_data: The data to pass to @callback.
1993 * Asynchronously sends @message to the peer represented by @connection.
1995 * Unless @flags contain the
1996 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1997 * will be assigned by @connection and set on @message via
1998 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1999 * serial number used will be written to this location prior to
2000 * submitting the message to the underlying transport.
2002 * If @connection is closed then the operation will fail with
2003 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2004 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2005 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2007 * This is an asynchronous method. When the operation is finished, @callback will be invoked
2008 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
2009 * of the thread you are calling this method from. You can then call
2010 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
2011 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
2013 * Note that @message must be unlocked, unless @flags contain the
2014 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2016 * See <xref linkend="gdbus-server"/> and <xref
2017 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2018 * low-level API to send and receive UNIX file descriptors.
2023 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
2024 GDBusMessage *message,
2025 GDBusSendMessageFlags flags,
2027 volatile guint32 *out_serial,
2028 GCancellable *cancellable,
2029 GAsyncReadyCallback callback,
2032 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2033 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2034 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2035 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2037 CONNECTION_LOCK (connection);
2038 g_dbus_connection_send_message_with_reply_unlocked (connection,
2046 CONNECTION_UNLOCK (connection);
2050 * g_dbus_connection_send_message_with_reply_finish:
2051 * @connection: a #GDBusConnection
2052 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
2053 * @error: Return location for error or %NULL.
2055 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2057 * Note that @error is only set if a local in-process error
2058 * occurred. That is to say that the returned #GDBusMessage object may
2059 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2060 * g_dbus_message_to_gerror() to transcode this to a #GError.
2062 * See <xref linkend="gdbus-server"/> and <xref
2063 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2064 * low-level API to send and receive UNIX file descriptors.
2066 * Returns: (transfer full): A locked #GDBusMessage or %NULL if @error is set.
2071 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2075 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2076 GDBusMessage *reply;
2078 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2079 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2083 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
2085 if (g_simple_async_result_propagate_error (simple, error))
2088 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
2094 /* ---------------------------------------------------------------------------------------------------- */
2099 GMainContext *context;
2101 } SendMessageSyncData;
2103 /* Called from a user thread, lock is not held */
2105 send_message_with_reply_sync_cb (GDBusConnection *connection,
2109 SendMessageSyncData *data = user_data;
2110 data->res = g_object_ref (res);
2111 g_main_loop_quit (data->loop);
2115 * g_dbus_connection_send_message_with_reply_sync:
2116 * @connection: A #GDBusConnection.
2117 * @message: A #GDBusMessage.
2118 * @flags: Flags affecting how the message is sent.
2119 * @timeout_msec: The timeout in milliseconds, -1 to use the default
2120 * timeout or %G_MAXINT for no timeout.
2121 * @out_serial: (out) (allow-none): Return location for serial number assigned
2122 * to @message when sending it or %NULL.
2123 * @cancellable: (allow-none): A #GCancellable or %NULL.
2124 * @error: Return location for error or %NULL.
2126 * Synchronously sends @message to the peer represented by @connection
2127 * and blocks the calling thread until a reply is received or the
2128 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2129 * for the asynchronous version of this method.
2131 * Unless @flags contain the
2132 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2133 * will be assigned by @connection and set on @message via
2134 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2135 * serial number used will be written to this location prior to
2136 * submitting the message to the underlying transport.
2138 * If @connection is closed then the operation will fail with
2139 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2140 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2141 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2143 * Note that @error is only set if a local in-process error
2144 * occurred. That is to say that the returned #GDBusMessage object may
2145 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2146 * g_dbus_message_to_gerror() to transcode this to a #GError.
2148 * See <xref linkend="gdbus-server"/> and <xref
2149 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2150 * low-level API to send and receive UNIX file descriptors.
2152 * Note that @message must be unlocked, unless @flags contain the
2153 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2155 * Returns: (transfer full): A locked #GDBusMessage that is the reply to @message or %NULL if @error is set.
2160 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2161 GDBusMessage *message,
2162 GDBusSendMessageFlags flags,
2164 volatile guint32 *out_serial,
2165 GCancellable *cancellable,
2168 SendMessageSyncData *data;
2169 GDBusMessage *reply;
2171 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2172 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2173 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2174 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2175 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2177 data = g_new0 (SendMessageSyncData, 1);
2178 data->context = g_main_context_new ();
2179 data->loop = g_main_loop_new (data->context, FALSE);
2181 g_main_context_push_thread_default (data->context);
2183 g_dbus_connection_send_message_with_reply (connection,
2189 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2191 g_main_loop_run (data->loop);
2192 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2196 g_main_context_pop_thread_default (data->context);
2198 g_main_context_unref (data->context);
2199 g_main_loop_unref (data->loop);
2200 g_object_unref (data->res);
2206 /* ---------------------------------------------------------------------------------------------------- */
2210 GDBusMessageFilterFunction func;
2217 GDBusMessageFilterFunction filter_function;
2219 GDestroyNotify user_data_free_func;
2222 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2224 on_worker_message_received (GDBusWorker *worker,
2225 GDBusMessage *message,
2228 GDBusConnection *connection;
2229 FilterCallback *filters;
2234 G_LOCK (message_bus_lock);
2235 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2238 G_UNLOCK (message_bus_lock);
2241 connection = G_DBUS_CONNECTION (user_data);
2242 g_object_ref (connection);
2243 G_UNLOCK (message_bus_lock);
2245 //g_debug ("in on_worker_message_received");
2247 g_object_ref (message);
2248 g_dbus_message_lock (message);
2250 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2252 /* First collect the set of callback functions */
2253 CONNECTION_LOCK (connection);
2254 num_filters = connection->filters->len;
2255 filters = g_new0 (FilterCallback, num_filters);
2256 for (n = 0; n < num_filters; n++)
2258 FilterData *data = connection->filters->pdata[n];
2259 filters[n].func = data->filter_function;
2260 filters[n].user_data = data->user_data;
2262 CONNECTION_UNLOCK (connection);
2264 /* then call the filters in order (without holding the lock) */
2265 for (n = 0; n < num_filters; n++)
2267 message = filters[n].func (connection,
2270 filters[n].user_data);
2271 if (message == NULL)
2273 g_dbus_message_lock (message);
2276 /* Standard dispatch unless the filter ate the message - no need to
2277 * do anything if the message was altered
2279 if (message != NULL)
2281 GDBusMessageType message_type;
2283 message_type = g_dbus_message_get_message_type (message);
2284 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2286 guint32 reply_serial;
2287 SendMessageData *send_message_data;
2289 reply_serial = g_dbus_message_get_reply_serial (message);
2290 CONNECTION_LOCK (connection);
2291 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2292 GUINT_TO_POINTER (reply_serial));
2293 if (send_message_data != NULL)
2295 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2296 send_message_data_deliver_reply_unlocked (send_message_data, message);
2300 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2302 CONNECTION_UNLOCK (connection);
2304 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2306 CONNECTION_LOCK (connection);
2307 distribute_signals (connection, message);
2308 CONNECTION_UNLOCK (connection);
2310 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2312 CONNECTION_LOCK (connection);
2313 distribute_method_call (connection, message);
2314 CONNECTION_UNLOCK (connection);
2318 if (message != NULL)
2319 g_object_unref (message);
2320 g_object_unref (connection);
2324 /* Called in GDBusWorker's thread, lock is not held */
2325 static GDBusMessage *
2326 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2327 GDBusMessage *message,
2330 GDBusConnection *connection;
2331 FilterCallback *filters;
2336 G_LOCK (message_bus_lock);
2337 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2340 G_UNLOCK (message_bus_lock);
2343 connection = G_DBUS_CONNECTION (user_data);
2344 g_object_ref (connection);
2345 G_UNLOCK (message_bus_lock);
2347 //g_debug ("in on_worker_message_about_to_be_sent");
2349 /* First collect the set of callback functions */
2350 CONNECTION_LOCK (connection);
2351 num_filters = connection->filters->len;
2352 filters = g_new0 (FilterCallback, num_filters);
2353 for (n = 0; n < num_filters; n++)
2355 FilterData *data = connection->filters->pdata[n];
2356 filters[n].func = data->filter_function;
2357 filters[n].user_data = data->user_data;
2359 CONNECTION_UNLOCK (connection);
2361 /* then call the filters in order (without holding the lock) */
2362 for (n = 0; n < num_filters; n++)
2364 g_dbus_message_lock (message);
2365 message = filters[n].func (connection,
2368 filters[n].user_data);
2369 if (message == NULL)
2373 g_object_unref (connection);
2379 /* called with connection lock held, in GDBusWorker thread */
2381 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2383 SendMessageData *data = value;
2385 if (data->delivered)
2388 g_simple_async_result_set_error (data->simple,
2391 _("The connection is closed"));
2393 /* Ask send_message_with_reply_deliver not to remove the element from the
2394 * hash table - we're in the middle of a foreach; that would be unsafe.
2395 * Instead, return TRUE from this function so that it gets removed safely.
2397 send_message_with_reply_deliver (data, FALSE);
2401 /* Called in GDBusWorker's thread - we must not block - without lock held */
2403 on_worker_closed (GDBusWorker *worker,
2404 gboolean remote_peer_vanished,
2408 GDBusConnection *connection;
2410 guint old_atomic_flags;
2412 G_LOCK (message_bus_lock);
2413 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2416 G_UNLOCK (message_bus_lock);
2419 connection = G_DBUS_CONNECTION (user_data);
2420 g_object_ref (connection);
2421 G_UNLOCK (message_bus_lock);
2423 //g_debug ("in on_worker_closed: %s", error->message);
2425 CONNECTION_LOCK (connection);
2426 /* Even though this is atomic, we do it inside the lock to avoid breaking
2427 * assumptions in remove_match_rule(). We'd need the lock in a moment
2428 * anyway, so, no loss.
2430 old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
2432 if (!(old_atomic_flags & FLAG_CLOSED))
2434 g_hash_table_foreach_remove (connection->map_method_serial_to_send_message_data, cancel_method_on_close, NULL);
2435 schedule_closed_unlocked (connection, remote_peer_vanished, error);
2437 CONNECTION_UNLOCK (connection);
2439 g_object_unref (connection);
2442 /* ---------------------------------------------------------------------------------------------------- */
2444 /* Determines the biggest set of capabilities we can support on this
2447 * Called with the init_lock held.
2449 static GDBusCapabilityFlags
2450 get_offered_capabilities_max (GDBusConnection *connection)
2452 GDBusCapabilityFlags ret;
2453 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2455 if (G_IS_UNIX_CONNECTION (connection->stream))
2456 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2461 /* Called in a user thread, lock is not held */
2463 initable_init (GInitable *initable,
2464 GCancellable *cancellable,
2467 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2470 /* This method needs to be idempotent to work with the singleton
2471 * pattern. See the docs for g_initable_init(). We implement this by
2474 * Unfortunately we can't use the main lock since the on_worker_*()
2475 * callbacks above needs the lock during initialization (for message
2476 * bus connections we do a synchronous Hello() call on the bus).
2478 g_mutex_lock (&connection->init_lock);
2482 /* Make this a no-op if we're already initialized (successfully or
2485 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
2487 ret = (connection->initialization_error == NULL);
2491 /* Because of init_lock, we can't get here twice in different threads */
2492 g_assert (connection->initialization_error == NULL);
2494 /* The user can pass multiple (but mutally exclusive) construct
2497 * - stream (of type GIOStream)
2498 * - address (of type gchar*)
2500 * At the end of the day we end up with a non-NULL GIOStream
2501 * object in connection->stream.
2503 if (connection->address != NULL)
2505 g_assert (connection->stream == NULL);
2507 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2508 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2510 g_set_error_literal (&connection->initialization_error,
2512 G_IO_ERROR_INVALID_ARGUMENT,
2513 _("Unsupported flags encountered when constructing a client-side connection"));
2517 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2518 NULL, /* TODO: out_guid */
2520 &connection->initialization_error);
2521 if (connection->stream == NULL)
2524 else if (connection->stream != NULL)
2530 g_assert_not_reached ();
2533 /* Authenticate the connection */
2534 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2536 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2537 g_assert (connection->guid != NULL);
2538 connection->auth = _g_dbus_auth_new (connection->stream);
2539 if (!_g_dbus_auth_run_server (connection->auth,
2540 connection->authentication_observer,
2542 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2543 get_offered_capabilities_max (connection),
2544 &connection->capabilities,
2545 &connection->credentials,
2547 &connection->initialization_error))
2550 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2552 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2553 g_assert (connection->guid == NULL);
2554 connection->auth = _g_dbus_auth_new (connection->stream);
2555 connection->guid = _g_dbus_auth_run_client (connection->auth,
2556 connection->authentication_observer,
2557 get_offered_capabilities_max (connection),
2558 &connection->capabilities,
2560 &connection->initialization_error);
2561 if (connection->guid == NULL)
2565 if (connection->authentication_observer != NULL)
2567 g_object_unref (connection->authentication_observer);
2568 connection->authentication_observer = NULL;
2571 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2573 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2576 /* We want all IO operations to be non-blocking since they happen in
2577 * the worker thread which is shared by _all_ connections.
2579 if (G_IS_SOCKET_CONNECTION (connection->stream))
2581 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2585 G_LOCK (message_bus_lock);
2586 if (alive_connections == NULL)
2587 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2588 g_hash_table_insert (alive_connections, connection, connection);
2589 G_UNLOCK (message_bus_lock);
2591 connection->worker = _g_dbus_worker_new (connection->stream,
2592 connection->capabilities,
2593 ((connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) != 0),
2594 on_worker_message_received,
2595 on_worker_message_about_to_be_sent,
2599 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2600 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2602 GVariant *hello_result;
2604 /* we could lift this restriction by adding code in gdbusprivate.c */
2605 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2607 g_set_error_literal (&connection->initialization_error,
2610 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2614 hello_result = g_dbus_connection_call_sync (connection,
2615 "org.freedesktop.DBus", /* name */
2616 "/org/freedesktop/DBus", /* path */
2617 "org.freedesktop.DBus", /* interface */
2619 NULL, /* parameters */
2620 G_VARIANT_TYPE ("(s)"),
2621 CALL_FLAGS_INITIALIZING,
2623 NULL, /* TODO: cancellable */
2624 &connection->initialization_error);
2625 if (hello_result == NULL)
2628 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2629 g_variant_unref (hello_result);
2630 //g_debug ("unique name is `%s'", connection->bus_unique_name);
2637 g_assert (connection->initialization_error != NULL);
2638 g_propagate_error (error, g_error_copy (connection->initialization_error));
2641 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
2642 g_mutex_unlock (&connection->init_lock);
2648 initable_iface_init (GInitableIface *initable_iface)
2650 initable_iface->init = initable_init;
2653 /* ---------------------------------------------------------------------------------------------------- */
2656 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2661 /* ---------------------------------------------------------------------------------------------------- */
2664 * g_dbus_connection_new:
2665 * @stream: A #GIOStream.
2666 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2667 * @flags: Flags describing how to make the connection.
2668 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2669 * @cancellable: (allow-none): A #GCancellable or %NULL.
2670 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2671 * @user_data: The data to pass to @callback.
2673 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2674 * with the end represented by @stream.
2676 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2677 * will be put into non-blocking mode.
2679 * The D-Bus connection will interact with @stream from a worker thread.
2680 * As a result, the caller should not interact with @stream after this
2681 * method has been called, except by calling g_object_unref() on it.
2683 * If @observer is not %NULL it may be used to control the
2684 * authentication process.
2686 * When the operation is finished, @callback will be invoked. You can
2687 * then call g_dbus_connection_new_finish() to get the result of the
2690 * This is a asynchronous failable constructor. See
2691 * g_dbus_connection_new_sync() for the synchronous
2697 g_dbus_connection_new (GIOStream *stream,
2699 GDBusConnectionFlags flags,
2700 GDBusAuthObserver *observer,
2701 GCancellable *cancellable,
2702 GAsyncReadyCallback callback,
2705 g_return_if_fail (G_IS_IO_STREAM (stream));
2706 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2714 "authentication-observer", observer,
2719 * g_dbus_connection_new_finish:
2720 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2721 * @error: Return location for error or %NULL.
2723 * Finishes an operation started with g_dbus_connection_new().
2725 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2730 g_dbus_connection_new_finish (GAsyncResult *res,
2734 GObject *source_object;
2736 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2737 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2739 source_object = g_async_result_get_source_object (res);
2740 g_assert (source_object != NULL);
2741 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2744 g_object_unref (source_object);
2746 return G_DBUS_CONNECTION (object);
2752 * g_dbus_connection_new_sync:
2753 * @stream: A #GIOStream.
2754 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2755 * @flags: Flags describing how to make the connection.
2756 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2757 * @cancellable: (allow-none): A #GCancellable or %NULL.
2758 * @error: Return location for error or %NULL.
2760 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2761 * with the end represented by @stream.
2763 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2764 * will be put into non-blocking mode.
2766 * The D-Bus connection will interact with @stream from a worker thread.
2767 * As a result, the caller should not interact with @stream after this
2768 * method has been called, except by calling g_object_unref() on it.
2770 * If @observer is not %NULL it may be used to control the
2771 * authentication process.
2773 * This is a synchronous failable constructor. See
2774 * g_dbus_connection_new() for the asynchronous version.
2776 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2781 g_dbus_connection_new_sync (GIOStream *stream,
2783 GDBusConnectionFlags flags,
2784 GDBusAuthObserver *observer,
2785 GCancellable *cancellable,
2788 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2789 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2790 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2796 "authentication-observer", observer,
2800 /* ---------------------------------------------------------------------------------------------------- */
2803 * g_dbus_connection_new_for_address:
2804 * @address: A D-Bus address.
2805 * @flags: Flags describing how to make the connection.
2806 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2807 * @cancellable: (allow-none): A #GCancellable or %NULL.
2808 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2809 * @user_data: The data to pass to @callback.
2811 * Asynchronously connects and sets up a D-Bus client connection for
2812 * exchanging D-Bus messages with an endpoint specified by @address
2813 * which must be in the D-Bus address format.
2815 * This constructor can only be used to initiate client-side
2816 * connections - use g_dbus_connection_new() if you need to act as the
2817 * server. In particular, @flags cannot contain the
2818 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2819 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2821 * When the operation is finished, @callback will be invoked. You can
2822 * then call g_dbus_connection_new_finish() to get the result of the
2825 * If @observer is not %NULL it may be used to control the
2826 * authentication process.
2828 * This is a asynchronous failable constructor. See
2829 * g_dbus_connection_new_for_address_sync() for the synchronous
2835 g_dbus_connection_new_for_address (const gchar *address,
2836 GDBusConnectionFlags flags,
2837 GDBusAuthObserver *observer,
2838 GCancellable *cancellable,
2839 GAsyncReadyCallback callback,
2842 g_return_if_fail (address != NULL);
2843 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2850 "authentication-observer", observer,
2855 * g_dbus_connection_new_for_address_finish:
2856 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2857 * @error: Return location for error or %NULL.
2859 * Finishes an operation started with g_dbus_connection_new_for_address().
2861 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2866 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2870 GObject *source_object;
2872 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2873 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2875 source_object = g_async_result_get_source_object (res);
2876 g_assert (source_object != NULL);
2877 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2880 g_object_unref (source_object);
2882 return G_DBUS_CONNECTION (object);
2888 * g_dbus_connection_new_for_address_sync:
2889 * @address: A D-Bus address.
2890 * @flags: Flags describing how to make the connection.
2891 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2892 * @cancellable: (allow-none): A #GCancellable or %NULL.
2893 * @error: Return location for error or %NULL.
2895 * Synchronously connects and sets up a D-Bus client connection for
2896 * exchanging D-Bus messages with an endpoint specified by @address
2897 * which must be in the D-Bus address format.
2899 * This constructor can only be used to initiate client-side
2900 * connections - use g_dbus_connection_new_sync() if you need to act
2901 * as the server. In particular, @flags cannot contain the
2902 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2903 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2905 * This is a synchronous failable constructor. See
2906 * g_dbus_connection_new_for_address() for the asynchronous version.
2908 * If @observer is not %NULL it may be used to control the
2909 * authentication process.
2911 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2916 g_dbus_connection_new_for_address_sync (const gchar *address,
2917 GDBusConnectionFlags flags,
2918 GDBusAuthObserver *observer,
2919 GCancellable *cancellable,
2922 g_return_val_if_fail (address != NULL, NULL);
2923 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2924 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2929 "authentication-observer", observer,
2933 /* ---------------------------------------------------------------------------------------------------- */
2936 * g_dbus_connection_set_exit_on_close:
2937 * @connection: A #GDBusConnection.
2938 * @exit_on_close: Whether the process should be terminated
2939 * when @connection is closed by the remote peer.
2941 * Sets whether the process should be terminated when @connection is
2942 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2945 * Note that this function should be used with care. Most modern UNIX
2946 * desktops tie the notion of a user session the session bus, and expect
2947 * all of a users applications to quit when their bus connection goes away.
2948 * If you are setting @exit_on_close to %FALSE for the shared session
2949 * bus connection, you should make sure that your application exits
2950 * when the user session ends.
2955 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2956 gboolean exit_on_close)
2958 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2961 g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
2963 g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
2968 * g_dbus_connection_get_exit_on_close:
2969 * @connection: A #GDBusConnection.
2971 * Gets whether the process is terminated when @connection is
2972 * closed by the remote peer. See
2973 * #GDBusConnection:exit-on-close for more details.
2975 * Returns: Whether the process is terminated when @connection is
2976 * closed by the remote peer.
2981 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2983 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2985 if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
2992 * g_dbus_connection_get_guid:
2993 * @connection: A #GDBusConnection.
2995 * The GUID of the peer performing the role of server when
2996 * authenticating. See #GDBusConnection:guid for more details.
2998 * Returns: The GUID. Do not free this string, it is owned by
3004 g_dbus_connection_get_guid (GDBusConnection *connection)
3006 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3007 return connection->guid;
3011 * g_dbus_connection_get_unique_name:
3012 * @connection: A #GDBusConnection.
3014 * Gets the unique name of @connection as assigned by the message
3015 * bus. This can also be used to figure out if @connection is a
3016 * message bus connection.
3018 * Returns: The unique name or %NULL if @connection is not a message
3019 * bus connection. Do not free this string, it is owned by
3025 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3027 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3029 /* do not use g_return_val_if_fail(), we want the memory barrier */
3030 if (!check_initialized (connection))
3033 return connection->bus_unique_name;
3037 * g_dbus_connection_get_peer_credentials:
3038 * @connection: A #GDBusConnection.
3040 * Gets the credentials of the authenticated peer. This will always
3041 * return %NULL unless @connection acted as a server
3042 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3043 * when set up and the client passed credentials as part of the
3044 * authentication process.
3046 * In a message bus setup, the message bus is always the server and
3047 * each application is a client. So this method will always return
3048 * %NULL for message bus clients.
3050 * Returns: (transfer none): A #GCredentials or %NULL if not available. Do not free
3051 * this object, it is owned by @connection.
3056 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3058 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3060 /* do not use g_return_val_if_fail(), we want the memory barrier */
3061 if (!check_initialized (connection))
3064 return connection->credentials;
3067 /* ---------------------------------------------------------------------------------------------------- */
3069 static guint _global_filter_id = 1;
3072 * g_dbus_connection_add_filter:
3073 * @connection: A #GDBusConnection.
3074 * @filter_function: A filter function.
3075 * @user_data: User data to pass to @filter_function.
3076 * @user_data_free_func: Function to free @user_data with when filter
3077 * is removed or %NULL.
3079 * Adds a message filter. Filters are handlers that are run on all
3080 * incoming and outgoing messages, prior to standard dispatch. Filters
3081 * are run in the order that they were added. The same handler can be
3082 * added as a filter more than once, in which case it will be run more
3083 * than once. Filters added during a filter callback won't be run on
3084 * the message being processed. Filter functions are allowed to modify
3085 * and even drop messages.
3087 * Note that filters are run in a dedicated message handling thread so
3088 * they can't block and, generally, can't do anything but signal a
3089 * worker thread. Also note that filters are rarely needed - use API
3090 * such as g_dbus_connection_send_message_with_reply(),
3091 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3093 * If a filter consumes an incoming message the message is not
3094 * dispatched anywhere else - not even the standard dispatch machinery
3095 * (that API such as g_dbus_connection_signal_subscribe() and
3096 * g_dbus_connection_send_message_with_reply() relies on) will see the
3097 * message. Similary, if a filter consumes an outgoing message, the
3098 * message will not be sent to the other peer.
3100 * Returns: A filter identifier that can be used with
3101 * g_dbus_connection_remove_filter().
3106 g_dbus_connection_add_filter (GDBusConnection *connection,
3107 GDBusMessageFilterFunction filter_function,
3109 GDestroyNotify user_data_free_func)
3113 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3114 g_return_val_if_fail (filter_function != NULL, 0);
3115 g_return_val_if_fail (check_initialized (connection), 0);
3117 CONNECTION_LOCK (connection);
3118 data = g_new0 (FilterData, 1);
3119 data->id = _global_filter_id++; /* TODO: overflow etc. */
3120 data->filter_function = filter_function;
3121 data->user_data = user_data;
3122 data->user_data_free_func = user_data_free_func;
3123 g_ptr_array_add (connection->filters, data);
3124 CONNECTION_UNLOCK (connection);
3129 /* only called from finalize(), removes all filters */
3131 purge_all_filters (GDBusConnection *connection)
3134 for (n = 0; n < connection->filters->len; n++)
3136 FilterData *data = connection->filters->pdata[n];
3137 if (data->user_data_free_func != NULL)
3138 data->user_data_free_func (data->user_data);
3144 * g_dbus_connection_remove_filter:
3145 * @connection: a #GDBusConnection
3146 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3153 g_dbus_connection_remove_filter (GDBusConnection *connection,
3157 FilterData *to_destroy;
3159 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3160 g_return_if_fail (check_initialized (connection));
3162 CONNECTION_LOCK (connection);
3164 for (n = 0; n < connection->filters->len; n++)
3166 FilterData *data = connection->filters->pdata[n];
3167 if (data->id == filter_id)
3169 g_ptr_array_remove_index (connection->filters, n);
3174 CONNECTION_UNLOCK (connection);
3176 /* do free without holding lock */
3177 if (to_destroy != NULL)
3179 if (to_destroy->user_data_free_func != NULL)
3180 to_destroy->user_data_free_func (to_destroy->user_data);
3181 g_free (to_destroy);
3185 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3189 /* ---------------------------------------------------------------------------------------------------- */
3195 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3196 gchar *interface_name;
3200 GArray *subscribers;
3205 GDBusSignalCallback callback;
3207 GDestroyNotify user_data_free_func;
3209 GMainContext *context;
3213 signal_data_free (SignalData *signal_data)
3215 g_free (signal_data->rule);
3216 g_free (signal_data->sender);
3217 g_free (signal_data->sender_unique_name);
3218 g_free (signal_data->interface_name);
3219 g_free (signal_data->member);
3220 g_free (signal_data->object_path);
3221 g_free (signal_data->arg0);
3222 g_array_free (signal_data->subscribers, TRUE);
3223 g_free (signal_data);
3227 args_to_rule (const gchar *sender,
3228 const gchar *interface_name,
3229 const gchar *member,
3230 const gchar *object_path,
3236 rule = g_string_new ("type='signal'");
3238 g_string_prepend_c (rule, '-');
3240 g_string_append_printf (rule, ",sender='%s'", sender);
3241 if (interface_name != NULL)
3242 g_string_append_printf (rule, ",interface='%s'", interface_name);
3244 g_string_append_printf (rule, ",member='%s'", member);
3245 if (object_path != NULL)
3246 g_string_append_printf (rule, ",path='%s'", object_path);
3248 g_string_append_printf (rule, ",arg0='%s'", arg0);
3250 return g_string_free (rule, FALSE);
3253 static guint _global_subscriber_id = 1;
3254 static guint _global_registration_id = 1;
3255 static guint _global_subtree_registration_id = 1;
3257 /* ---------------------------------------------------------------------------------------------------- */
3259 /* Called in a user thread, lock is held */
3261 add_match_rule (GDBusConnection *connection,
3262 const gchar *match_rule)
3265 GDBusMessage *message;
3267 if (match_rule[0] == '-')
3270 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3271 "/org/freedesktop/DBus", /* path */
3272 "org.freedesktop.DBus", /* interface */
3274 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3276 if (!g_dbus_connection_send_message_unlocked (connection,
3278 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3282 g_critical ("Error while sending AddMatch() message: %s", error->message);
3283 g_error_free (error);
3285 g_object_unref (message);
3288 /* ---------------------------------------------------------------------------------------------------- */
3290 /* Called in a user thread, lock is held */
3292 remove_match_rule (GDBusConnection *connection,
3293 const gchar *match_rule)
3296 GDBusMessage *message;
3298 if (match_rule[0] == '-')
3301 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3302 "/org/freedesktop/DBus", /* path */
3303 "org.freedesktop.DBus", /* interface */
3305 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3308 if (!g_dbus_connection_send_message_unlocked (connection,
3310 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3314 /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
3315 * critical; but we're holding the lock, and our caller checked whether
3316 * we were already closed, so we can't get that error.
3318 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3319 g_error_free (error);
3321 g_object_unref (message);
3324 /* ---------------------------------------------------------------------------------------------------- */
3327 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3329 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3330 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3331 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3332 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3333 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3336 /* ---------------------------------------------------------------------------------------------------- */
3339 * g_dbus_connection_signal_subscribe:
3340 * @connection: A #GDBusConnection.
3341 * @sender: (allow-none): Sender name to match on (unique or well-known name)
3342 * or %NULL to listen from all senders.
3343 * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3344 * match on all interfaces.
3345 * @member: (allow-none): D-Bus signal name to match on or %NULL to match on all signals.
3346 * @object_path: (allow-none): Object path to match on or %NULL to match on all object paths.
3347 * @arg0: (allow-none): Contents of first string argument to match on or %NULL
3348 * to match on all kinds of arguments.
3349 * @flags: Flags describing how to subscribe to the signal (currently unused).
3350 * @callback: Callback to invoke when there is a signal matching the requested data.
3351 * @user_data: User data to pass to @callback.
3352 * @user_data_free_func: (allow-none): Function to free @user_data with when
3353 * subscription is removed or %NULL.
3355 * Subscribes to signals on @connection and invokes @callback with a
3356 * whenever the signal is received. Note that @callback
3357 * will be invoked in the <link
3358 * linkend="g-main-context-push-thread-default">thread-default main
3359 * loop</link> of the thread you are calling this method from.
3361 * If @connection is not a message bus connection, @sender must be
3364 * If @sender is a well-known name note that @callback is invoked with
3365 * the unique name for the owner of @sender, not the well-known name
3366 * as one would expect. This is because the message bus rewrites the
3367 * name. As such, to avoid certain race conditions, users should be
3368 * tracking the name owner of the well-known name and use that when
3369 * processing the received signal.
3371 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
3376 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3377 const gchar *sender,
3378 const gchar *interface_name,
3379 const gchar *member,
3380 const gchar *object_path,
3382 GDBusSignalFlags flags,
3383 GDBusSignalCallback callback,
3385 GDestroyNotify user_data_free_func)
3388 SignalData *signal_data;
3389 SignalSubscriber subscriber;
3390 GPtrArray *signal_data_array;
3391 const gchar *sender_unique_name;
3393 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3394 * an OOM condition. We might want to change that but that would involve making
3395 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3396 * handle that. And there's really no sensible way of handling this short of retrying
3397 * to add the match rule... and then there's the little thing that, hey, maybe there's
3398 * a reason the bus in an OOM condition.
3400 * Doable, but not really sure it's worth it...
3403 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3404 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3405 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3406 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3407 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3408 g_return_val_if_fail (callback != NULL, 0);
3409 g_return_val_if_fail (check_initialized (connection), 0);
3411 CONNECTION_LOCK (connection);
3413 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3414 * with a '-' character to prefix the rule (which will otherwise be
3417 * This allows us to hash the rule and do our lifecycle tracking in
3418 * the usual way, but the '-' prevents the match rule from ever
3419 * actually being send to the bus (either for add or remove).
3421 rule = args_to_rule (sender, interface_name, member, object_path, arg0,
3422 (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE) != 0);
3424 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3425 sender_unique_name = sender;
3427 sender_unique_name = "";
3429 subscriber.callback = callback;
3430 subscriber.user_data = user_data;
3431 subscriber.user_data_free_func = user_data_free_func;
3432 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3433 subscriber.context = g_main_context_ref_thread_default ();
3435 /* see if we've already have this rule */
3436 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3437 if (signal_data != NULL)
3439 g_array_append_val (signal_data->subscribers, subscriber);
3444 signal_data = g_new0 (SignalData, 1);
3445 signal_data->rule = rule;
3446 signal_data->sender = g_strdup (sender);
3447 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3448 signal_data->interface_name = g_strdup (interface_name);
3449 signal_data->member = g_strdup (member);
3450 signal_data->object_path = g_strdup (object_path);
3451 signal_data->arg0 = g_strdup (arg0);
3452 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3453 g_array_append_val (signal_data->subscribers, subscriber);
3455 g_hash_table_insert (connection->map_rule_to_signal_data,
3459 /* Add the match rule to the bus...
3461 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3462 * always send such messages to us.
3464 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3466 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3467 add_match_rule (connection, signal_data->rule);
3470 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3471 signal_data->sender_unique_name);
3472 if (signal_data_array == NULL)
3474 signal_data_array = g_ptr_array_new ();
3475 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3476 g_strdup (signal_data->sender_unique_name),
3479 g_ptr_array_add (signal_data_array, signal_data);
3482 g_hash_table_insert (connection->map_id_to_signal_data,
3483 GUINT_TO_POINTER (subscriber.id),
3486 CONNECTION_UNLOCK (connection);
3488 return subscriber.id;
3491 /* ---------------------------------------------------------------------------------------------------- */
3493 /* called in any thread */
3494 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3496 unsubscribe_id_internal (GDBusConnection *connection,
3497 guint subscription_id,
3498 GArray *out_removed_subscribers)
3500 SignalData *signal_data;
3501 GPtrArray *signal_data_array;
3504 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3505 GUINT_TO_POINTER (subscription_id));
3506 if (signal_data == NULL)
3508 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3512 for (n = 0; n < signal_data->subscribers->len; n++)
3514 SignalSubscriber *subscriber;
3516 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3517 if (subscriber->id != subscription_id)
3520 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3521 GUINT_TO_POINTER (subscription_id)));
3522 g_array_append_val (out_removed_subscribers, *subscriber);
3523 g_array_remove_index (signal_data->subscribers, n);
3525 if (signal_data->subscribers->len == 0)
3527 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3529 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3530 signal_data->sender_unique_name);
3531 g_warn_if_fail (signal_data_array != NULL);
3532 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3534 if (signal_data_array->len == 0)
3536 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3537 signal_data->sender_unique_name));
3540 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3541 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
3542 !is_signal_data_for_name_lost_or_acquired (signal_data) &&
3543 !g_dbus_connection_is_closed (connection) &&
3544 !connection->finalizing)
3546 /* The check for g_dbus_connection_is_closed() means that
3547 * sending the RemoveMatch message can't fail with
3548 * G_IO_ERROR_CLOSED, because we're holding the lock,
3549 * so on_worker_closed() can't happen between the check we just
3550 * did, and releasing the lock later.
3552 remove_match_rule (connection, signal_data->rule);
3555 signal_data_free (signal_data);
3561 g_assert_not_reached ();
3568 * g_dbus_connection_signal_unsubscribe:
3569 * @connection: A #GDBusConnection.
3570 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
3572 * Unsubscribes from signals.
3577 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3578 guint subscription_id)
3580 GArray *subscribers;
3583 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3584 g_return_if_fail (check_initialized (connection));
3586 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3588 CONNECTION_LOCK (connection);
3589 unsubscribe_id_internal (connection,
3592 CONNECTION_UNLOCK (connection);
3595 g_assert (subscribers->len == 0 || subscribers->len == 1);
3597 /* call GDestroyNotify without lock held */
3598 for (n = 0; n < subscribers->len; n++)
3600 SignalSubscriber *subscriber;
3601 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3602 call_destroy_notify (subscriber->context,
3603 subscriber->user_data_free_func,
3604 subscriber->user_data);
3605 g_main_context_unref (subscriber->context);
3608 g_array_free (subscribers, TRUE);
3611 /* ---------------------------------------------------------------------------------------------------- */
3615 guint subscription_id;
3616 GDBusSignalCallback callback;
3618 GDBusMessage *message;
3619 GDBusConnection *connection;
3620 const gchar *sender;
3622 const gchar *interface;
3623 const gchar *member;
3626 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3630 emit_signal_instance_in_idle_cb (gpointer data)
3632 SignalInstance *signal_instance = data;
3633 GVariant *parameters;
3634 gboolean has_subscription;
3636 parameters = g_dbus_message_get_body (signal_instance->message);
3637 if (parameters == NULL)
3639 parameters = g_variant_new ("()");
3640 g_variant_ref_sink (parameters);
3644 g_variant_ref_sink (parameters);
3648 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3649 signal_instance->subscription_id,
3650 signal_instance->sender,
3651 signal_instance->path,
3652 signal_instance->interface,
3653 signal_instance->member,
3654 g_variant_print (parameters, TRUE));
3657 /* Careful here, don't do the callback if we no longer has the subscription */
3658 CONNECTION_LOCK (signal_instance->connection);
3659 has_subscription = FALSE;
3660 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3661 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3662 has_subscription = TRUE;
3663 CONNECTION_UNLOCK (signal_instance->connection);
3665 if (has_subscription)
3666 signal_instance->callback (signal_instance->connection,
3667 signal_instance->sender,
3668 signal_instance->path,
3669 signal_instance->interface,
3670 signal_instance->member,
3672 signal_instance->user_data);
3674 g_variant_unref (parameters);
3680 signal_instance_free (SignalInstance *signal_instance)
3682 g_object_unref (signal_instance->message);
3683 g_object_unref (signal_instance->connection);
3684 g_free (signal_instance);
3687 /* called in GDBusWorker thread WITH lock held */
3689 schedule_callbacks (GDBusConnection *connection,
3690 GPtrArray *signal_data_array,
3691 GDBusMessage *message,
3692 const gchar *sender)
3695 const gchar *interface;
3696 const gchar *member;
3705 interface = g_dbus_message_get_interface (message);
3706 member = g_dbus_message_get_member (message);
3707 path = g_dbus_message_get_path (message);
3708 arg0 = g_dbus_message_get_arg0 (message);
3711 g_print ("In schedule_callbacks:\n"
3713 " interface = `%s'\n"
3724 /* TODO: if this is slow, then we can change signal_data_array into
3725 * map_object_path_to_signal_data_array or something.
3727 for (n = 0; n < signal_data_array->len; n++)
3729 SignalData *signal_data = signal_data_array->pdata[n];
3731 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3734 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3737 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3740 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
3743 for (m = 0; m < signal_data->subscribers->len; m++)
3745 SignalSubscriber *subscriber;
3746 GSource *idle_source;
3747 SignalInstance *signal_instance;
3749 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3751 signal_instance = g_new0 (SignalInstance, 1);
3752 signal_instance->subscription_id = subscriber->id;
3753 signal_instance->callback = subscriber->callback;
3754 signal_instance->user_data = subscriber->user_data;
3755 signal_instance->message = g_object_ref (message);
3756 signal_instance->connection = g_object_ref (connection);
3757 signal_instance->sender = sender;
3758 signal_instance->path = path;
3759 signal_instance->interface = interface;
3760 signal_instance->member = member;
3762 idle_source = g_idle_source_new ();
3763 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3764 g_source_set_callback (idle_source,
3765 emit_signal_instance_in_idle_cb,
3767 (GDestroyNotify) signal_instance_free);
3768 g_source_attach (idle_source, subscriber->context);
3769 g_source_unref (idle_source);
3774 /* called in GDBusWorker thread with lock held */
3776 distribute_signals (GDBusConnection *connection,
3777 GDBusMessage *message)
3779 GPtrArray *signal_data_array;
3780 const gchar *sender;
3782 sender = g_dbus_message_get_sender (message);
3784 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3786 _g_dbus_debug_print_lock ();
3787 g_print ("========================================================================\n"
3788 "GDBus-debug:Signal:\n"
3789 " <<<< RECEIVED SIGNAL %s.%s\n"
3791 " sent by name %s\n",
3792 g_dbus_message_get_interface (message),
3793 g_dbus_message_get_member (message),
3794 g_dbus_message_get_path (message),
3795 sender != NULL ? sender : "(none)");
3796 _g_dbus_debug_print_unlock ();
3799 /* collect subscribers that match on sender */
3802 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3803 if (signal_data_array != NULL)
3804 schedule_callbacks (connection, signal_data_array, message, sender);
3807 /* collect subscribers not matching on sender */
3808 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3809 if (signal_data_array != NULL)
3810 schedule_callbacks (connection, signal_data_array, message, sender);
3813 /* ---------------------------------------------------------------------------------------------------- */
3815 /* only called from finalize(), removes all subscriptions */
3817 purge_all_signal_subscriptions (GDBusConnection *connection)
3819 GHashTableIter iter;
3822 GArray *subscribers;
3825 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3826 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3827 while (g_hash_table_iter_next (&iter, &key, NULL))
3829 guint subscription_id = GPOINTER_TO_UINT (key);
3830 g_array_append_val (ids, subscription_id);
3833 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3834 for (n = 0; n < ids->len; n++)
3836 guint subscription_id = g_array_index (ids, guint, n);
3837 unsubscribe_id_internal (connection,
3841 g_array_free (ids, TRUE);
3843 /* call GDestroyNotify without lock held */
3844 for (n = 0; n < subscribers->len; n++)
3846 SignalSubscriber *subscriber;
3847 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3848 call_destroy_notify (subscriber->context,
3849 subscriber->user_data_free_func,
3850 subscriber->user_data);
3851 g_main_context_unref (subscriber->context);
3854 g_array_free (subscribers, TRUE);
3857 /* ---------------------------------------------------------------------------------------------------- */
3859 static GDBusInterfaceVTable *
3860 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3862 /* Don't waste memory by copying padding - remember to update this
3863 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3865 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3869 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
3874 /* ---------------------------------------------------------------------------------------------------- */
3876 static GDBusSubtreeVTable *
3877 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
3879 /* Don't waste memory by copying padding - remember to update this
3880 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
3882 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3886 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
3891 /* ---------------------------------------------------------------------------------------------------- */
3893 struct ExportedObject
3896 GDBusConnection *connection;
3898 /* maps gchar* -> ExportedInterface* */
3899 GHashTable *map_if_name_to_ei;
3902 /* only called with lock held */
3904 exported_object_free (ExportedObject *eo)
3906 g_free (eo->object_path);
3907 g_hash_table_unref (eo->map_if_name_to_ei);
3916 gchar *interface_name;
3917 GDBusInterfaceVTable *vtable;
3918 GDBusInterfaceInfo *interface_info;
3920 GMainContext *context;
3922 GDestroyNotify user_data_free_func;
3923 } ExportedInterface;
3925 /* called with lock held */
3927 exported_interface_free (ExportedInterface *ei)
3929 g_dbus_interface_info_cache_release (ei->interface_info);
3930 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
3932 call_destroy_notify (ei->context,
3933 ei->user_data_free_func,
3936 g_main_context_unref (ei->context);
3938 g_free (ei->interface_name);
3939 _g_dbus_interface_vtable_free (ei->vtable);
3943 /* ---------------------------------------------------------------------------------------------------- */
3945 /* Convenience function to check if @registration_id (if not zero) or
3946 * @subtree_registration_id (if not zero) has been unregistered. If
3947 * so, returns %TRUE.
3949 * May be called by any thread. Caller must *not* hold lock.
3952 has_object_been_unregistered (GDBusConnection *connection,
3953 guint registration_id,
3954 guint subtree_registration_id)
3958 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3962 CONNECTION_LOCK (connection);
3963 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
3964 GUINT_TO_POINTER (registration_id)) == NULL)
3968 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
3969 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
3973 CONNECTION_UNLOCK (connection);
3978 /* ---------------------------------------------------------------------------------------------------- */
3982 GDBusConnection *connection;
3983 GDBusMessage *message;
3985 const gchar *property_name;
3986 const GDBusInterfaceVTable *vtable;
3987 GDBusInterfaceInfo *interface_info;
3988 const GDBusPropertyInfo *property_info;
3989 guint registration_id;
3990 guint subtree_registration_id;
3994 property_data_free (PropertyData *data)
3996 g_object_unref (data->connection);
3997 g_object_unref (data->message);
4001 /* called in thread where object was registered - no locks held */
4003 invoke_get_property_in_idle_cb (gpointer _data)
4005 PropertyData *data = _data;
4008 GDBusMessage *reply;
4010 if (has_object_been_unregistered (data->connection,
4011 data->registration_id,
4012 data->subtree_registration_id))
4014 reply = g_dbus_message_new_method_error (data->message,
4015 "org.freedesktop.DBus.Error.UnknownMethod",
4016 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
4017 g_dbus_message_get_path (data->message));
4018 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4019 g_object_unref (reply);
4024 value = data->vtable->get_property (data->connection,
4025 g_dbus_message_get_sender (data->message),
4026 g_dbus_message_get_path (data->message),
4027 data->interface_info->name,
4028 data->property_name,
4035 g_assert_no_error (error);
4037 g_variant_take_ref (value);
4038 reply = g_dbus_message_new_method_reply (data->message);
4039 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4040 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4041 g_variant_unref (value);
4042 g_object_unref (reply);
4046 gchar *dbus_error_name;
4047 g_assert (error != NULL);
4048 dbus_error_name = g_dbus_error_encode_gerror (error);
4049 reply = g_dbus_message_new_method_error_literal (data->message,
4052 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4053 g_free (dbus_error_name);
4054 g_error_free (error);
4055 g_object_unref (reply);
4062 /* called in thread where object was registered - no locks held */
4064 invoke_set_property_in_idle_cb (gpointer _data)
4066 PropertyData *data = _data;
4068 GDBusMessage *reply;
4074 g_variant_get (g_dbus_message_get_body (data->message),
4080 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4081 * of the given value is wrong
4083 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
4085 reply = g_dbus_message_new_method_error (data->message,
4086 "org.freedesktop.DBus.Error.InvalidArgs",
4087 _("Error setting property `%s': Expected type `%s' but got `%s'"),
4088 data->property_info->name,
4089 data->property_info->signature,
4090 g_variant_get_type_string (value));
4094 if (!data->vtable->set_property (data->connection,
4095 g_dbus_message_get_sender (data->message),
4096 g_dbus_message_get_path (data->message),
4097 data->interface_info->name,
4098 data->property_name,
4103 gchar *dbus_error_name;
4104 g_assert (error != NULL);
4105 dbus_error_name = g_dbus_error_encode_gerror (error);
4106 reply = g_dbus_message_new_method_error_literal (data->message,
4109 g_free (dbus_error_name);
4110 g_error_free (error);
4114 reply = g_dbus_message_new_method_reply (data->message);
4118 g_assert (reply != NULL);
4119 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4120 g_object_unref (reply);
4121 g_variant_unref (value);
4126 /* called in any thread with connection's lock held */
4128 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4129 GDBusMessage *message,
4130 guint registration_id,
4131 guint subtree_registration_id,
4133 GDBusInterfaceInfo *interface_info,
4134 const GDBusInterfaceVTable *vtable,
4135 GMainContext *main_context,
4139 const char *interface_name;
4140 const char *property_name;
4141 const GDBusPropertyInfo *property_info;
4142 GSource *idle_source;
4143 PropertyData *property_data;
4144 GDBusMessage *reply;
4149 g_variant_get (g_dbus_message_get_body (message),
4154 g_variant_get (g_dbus_message_get_body (message),
4163 if (vtable == NULL || vtable->get_property == NULL)
4168 if (vtable == NULL || vtable->set_property == NULL)
4172 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4174 property_info = NULL;
4176 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4177 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4178 if (property_info == NULL)
4180 reply = g_dbus_message_new_method_error (message,
4181 "org.freedesktop.DBus.Error.InvalidArgs",
4182 _("No such property `%s'"),
4184 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4185 g_object_unref (reply);
4190 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4192 reply = g_dbus_message_new_method_error (message,
4193 "org.freedesktop.DBus.Error.InvalidArgs",
4194 _("Property `%s' is not readable"),
4196 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4197 g_object_unref (reply);
4201 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4203 reply = g_dbus_message_new_method_error (message,
4204 "org.freedesktop.DBus.Error.InvalidArgs",
4205 _("Property `%s' is not writable"),
4207 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4208 g_object_unref (reply);
4213 /* ok, got the property info - call user code in an idle handler */
4214 property_data = g_new0 (PropertyData, 1);
4215 property_data->connection = g_object_ref (connection);
4216 property_data->message = g_object_ref (message);
4217 property_data->user_data = user_data;
4218 property_data->property_name = property_name;
4219 property_data->vtable = vtable;
4220 property_data->interface_info = interface_info;
4221 property_data->property_info = property_info;
4222 property_data->registration_id = registration_id;
4223 property_data->subtree_registration_id = subtree_registration_id;
4225 idle_source = g_idle_source_new ();
4226 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4227 g_source_set_callback (idle_source,
4228 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4230 (GDestroyNotify) property_data_free);
4231 g_source_attach (idle_source, main_context);
4232 g_source_unref (idle_source);
4240 /* called in GDBusWorker thread with connection's lock held */
4242 handle_getset_property (GDBusConnection *connection,
4244 GDBusMessage *message,
4247 ExportedInterface *ei;
4249 const char *interface_name;
4250 const char *property_name;
4255 g_variant_get (g_dbus_message_get_body (message),
4260 g_variant_get (g_dbus_message_get_body (message),
4266 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4267 * no such interface registered
4269 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4272 GDBusMessage *reply;
4273 reply = g_dbus_message_new_method_error (message,
4274 "org.freedesktop.DBus.Error.InvalidArgs",
4275 _("No such interface `%s'"),
4277 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4278 g_object_unref (reply);
4283 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4296 /* ---------------------------------------------------------------------------------------------------- */
4300 GDBusConnection *connection;
4301 GDBusMessage *message;
4303 const GDBusInterfaceVTable *vtable;
4304 GDBusInterfaceInfo *interface_info;
4305 guint registration_id;
4306 guint subtree_registration_id;
4307 } PropertyGetAllData;
4310 property_get_all_data_free (PropertyData *data)
4312 g_object_unref (data->connection);
4313 g_object_unref (data->message);
4317 /* called in thread where object was registered - no locks held */
4319 invoke_get_all_properties_in_idle_cb (gpointer _data)
4321 PropertyGetAllData *data = _data;
4322 GVariantBuilder builder;
4323 GDBusMessage *reply;
4326 if (has_object_been_unregistered (data->connection,
4327 data->registration_id,
4328 data->subtree_registration_id))
4330 reply = g_dbus_message_new_method_error (data->message,
4331 "org.freedesktop.DBus.Error.UnknownMethod",
4332 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
4333 g_dbus_message_get_path (data->message));
4334 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4335 g_object_unref (reply);
4339 /* TODO: Right now we never fail this call - we just omit values if
4340 * a get_property() call is failing.
4342 * We could fail the whole call if just a single get_property() call
4343 * returns an error. We need clarification in the D-Bus spec about this.
4345 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4346 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4347 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4349 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4352 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4355 value = data->vtable->get_property (data->connection,
4356 g_dbus_message_get_sender (data->message),
4357 g_dbus_message_get_path (data->message),
4358 data->interface_info->name,
4359 property_info->name,
4366 g_variant_take_ref (value);
4367 g_variant_builder_add (&builder,
4369 property_info->name,
4371 g_variant_unref (value);
4373 g_variant_builder_close (&builder);
4375 reply = g_dbus_message_new_method_reply (data->message);
4376 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4377 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4378 g_object_unref (reply);
4384 /* called in any thread with connection's lock held */
4386 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4387 GDBusMessage *message,
4388 guint registration_id,
4389 guint subtree_registration_id,
4390 GDBusInterfaceInfo *interface_info,
4391 const GDBusInterfaceVTable *vtable,
4392 GMainContext *main_context,
4396 const char *interface_name;
4397 GSource *idle_source;
4398 PropertyGetAllData *property_get_all_data;
4402 g_variant_get (g_dbus_message_get_body (message),
4406 if (vtable == NULL || vtable->get_property == NULL)
4409 /* ok, got the property info - call user in an idle handler */
4410 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4411 property_get_all_data->connection = g_object_ref (connection);
4412 property_get_all_data->message = g_object_ref (message);
4413 property_get_all_data->user_data = user_data;
4414 property_get_all_data->vtable = vtable;
4415 property_get_all_data->interface_info = interface_info;
4416 property_get_all_data->registration_id = registration_id;
4417 property_get_all_data->subtree_registration_id = subtree_registration_id;
4419 idle_source = g_idle_source_new ();
4420 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4421 g_source_set_callback (idle_source,
4422 invoke_get_all_properties_in_idle_cb,
4423 property_get_all_data,
4424 (GDestroyNotify) property_get_all_data_free);
4425 g_source_attach (idle_source, main_context);
4426 g_source_unref (idle_source);
4434 /* called in GDBusWorker thread with connection's lock held */
4436 handle_get_all_properties (GDBusConnection *connection,
4438 GDBusMessage *message)
4440 ExportedInterface *ei;
4442 const char *interface_name;
4446 g_variant_get (g_dbus_message_get_body (message),
4450 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4451 * no such interface registered
4453 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4456 GDBusMessage *reply;
4457 reply = g_dbus_message_new_method_error (message,
4458 "org.freedesktop.DBus.Error.InvalidArgs",
4459 _("No such interface"),
4461 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4462 g_object_unref (reply);
4467 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4479 /* ---------------------------------------------------------------------------------------------------- */
4481 static const gchar introspect_header[] =
4482 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4483 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4484 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4487 static const gchar introspect_tail[] =
4490 static const gchar introspect_properties_interface[] =
4491 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4492 " <method name=\"Get\">\n"
4493 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4494 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4495 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4497 " <method name=\"GetAll\">\n"
4498 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4499 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4501 " <method name=\"Set\">\n"
4502 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4503 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4504 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4506 " <signal name=\"PropertiesChanged\">\n"
4507 " <arg type=\"s\" name=\"interface_name\"/>\n"
4508 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4509 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4513 static const gchar introspect_introspectable_interface[] =
4514 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4515 " <method name=\"Introspect\">\n"
4516 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4519 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4520 " <method name=\"Ping\"/>\n"
4521 " <method name=\"GetMachineId\">\n"
4522 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4527 introspect_append_header (GString *s)
4529 g_string_append (s, introspect_header);
4533 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4535 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4541 begin = object_path + path_len;
4542 end = strchr (begin, '/');
4544 s = g_strndup (begin, end - begin);
4546 s = g_strdup (begin);
4548 if (g_hash_table_lookup (set, s) == NULL)
4549 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
4555 /* TODO: we want a nicer public interface for this */
4556 /* called in any thread with connection's lock held */
4558 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4563 GHashTableIter hash_iter;
4564 const gchar *object_path;
4570 CONNECTION_ENSURE_LOCK (connection);
4572 path_len = strlen (path);
4576 set = g_hash_table_new (g_str_hash, g_str_equal);
4578 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4579 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4580 maybe_add_path (path, path_len, object_path, set);
4582 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4583 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4584 maybe_add_path (path, path_len, object_path, set);
4586 p = g_ptr_array_new ();
4587 keys = g_hash_table_get_keys (set);
4588 for (l = keys; l != NULL; l = l->next)
4589 g_ptr_array_add (p, l->data);
4590 g_hash_table_unref (set);
4593 g_ptr_array_add (p, NULL);
4594 ret = (gchar **) g_ptr_array_free (p, FALSE);
4598 /* called in any thread with connection's lock not held */
4600 g_dbus_connection_list_registered (GDBusConnection *connection,
4604 CONNECTION_LOCK (connection);
4605 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4606 CONNECTION_UNLOCK (connection);
4610 /* called in GDBusWorker thread with connection's lock held */
4612 handle_introspect (GDBusConnection *connection,
4614 GDBusMessage *message)
4618 GDBusMessage *reply;
4619 GHashTableIter hash_iter;
4620 ExportedInterface *ei;
4623 /* first the header with the standard interfaces */
4624 s = g_string_sized_new (sizeof (introspect_header) +
4625 sizeof (introspect_properties_interface) +
4626 sizeof (introspect_introspectable_interface) +
4627 sizeof (introspect_tail));
4628 introspect_append_header (s);
4629 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4630 "org.freedesktop.DBus.Properties"))
4631 g_string_append (s, introspect_properties_interface);
4633 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4634 "org.freedesktop.DBus.Introspectable"))
4635 g_string_append (s, introspect_introspectable_interface);
4637 /* then include the registered interfaces */
4638 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4639 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4640 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4642 /* finally include nodes registered below us */
4643 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4644 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4645 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4646 g_strfreev (registered);
4647 g_string_append (s, introspect_tail);
4649 reply = g_dbus_message_new_method_reply (message);
4650 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4651 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4652 g_object_unref (reply);
4653 g_string_free (s, TRUE);
4658 /* called in thread where object was registered - no locks held */
4660 call_in_idle_cb (gpointer user_data)
4662 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4663 GDBusInterfaceVTable *vtable;
4664 guint registration_id;
4665 guint subtree_registration_id;
4667 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4668 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4670 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4672 subtree_registration_id))
4674 GDBusMessage *reply;
4675 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4676 "org.freedesktop.DBus.Error.UnknownMethod",
4677 _("No such interface `%s' on object at path %s"),
4678 g_dbus_method_invocation_get_interface_name (invocation),
4679 g_dbus_method_invocation_get_object_path (invocation));
4680 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4681 g_object_unref (reply);
4685 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4686 g_assert (vtable != NULL && vtable->method_call != NULL);
4688 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4689 g_dbus_method_invocation_get_sender (invocation),
4690 g_dbus_method_invocation_get_object_path (invocation),
4691 g_dbus_method_invocation_get_interface_name (invocation),
4692 g_dbus_method_invocation_get_method_name (invocation),
4693 g_dbus_method_invocation_get_parameters (invocation),
4694 g_object_ref (invocation),
4695 g_dbus_method_invocation_get_user_data (invocation));
4701 /* called in GDBusWorker thread with connection's lock held */
4703 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4704 GDBusMessage *message,
4705 guint registration_id,
4706 guint subtree_registration_id,
4707 GDBusInterfaceInfo *interface_info,
4708 const GDBusInterfaceVTable *vtable,
4709 GMainContext *main_context,
4712 GDBusMethodInvocation *invocation;
4713 const GDBusMethodInfo *method_info;
4714 GDBusMessage *reply;
4715 GVariant *parameters;
4716 GSource *idle_source;
4718 GVariantType *in_type;
4722 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4723 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4725 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4726 * error to the caller
4728 if (method_info == NULL)
4730 reply = g_dbus_message_new_method_error (message,
4731 "org.freedesktop.DBus.Error.UnknownMethod",
4732 _("No such method `%s'"),
4733 g_dbus_message_get_member (message));
4734 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4735 g_object_unref (reply);
4740 parameters = g_dbus_message_get_body (message);
4741 if (parameters == NULL)
4743 parameters = g_variant_new ("()");
4744 g_variant_ref_sink (parameters);
4748 g_variant_ref (parameters);
4751 /* Check that the incoming args are of the right type - if they are not, return
4752 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4754 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4755 if (!g_variant_is_of_type (parameters, in_type))
4759 type_string = g_variant_type_dup_string (in_type);
4761 reply = g_dbus_message_new_method_error (message,
4762 "org.freedesktop.DBus.Error.InvalidArgs",
4763 _("Type of message, `%s', does not match expected type `%s'"),
4764 g_variant_get_type_string (parameters),
4766 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4767 g_variant_type_free (in_type);
4768 g_variant_unref (parameters);
4769 g_object_unref (reply);
4770 g_free (type_string);
4774 g_variant_type_free (in_type);
4776 /* schedule the call in idle */
4777 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4778 g_dbus_message_get_path (message),
4779 g_dbus_message_get_interface (message),
4780 g_dbus_message_get_member (message),
4786 g_variant_unref (parameters);
4788 /* TODO: would be nicer with a real MethodData like we already
4789 * have PropertyData and PropertyGetAllData... */
4790 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4791 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4792 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4794 idle_source = g_idle_source_new ();
4795 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4796 g_source_set_callback (idle_source,
4800 g_source_attach (idle_source, main_context);
4801 g_source_unref (idle_source);
4809 /* ---------------------------------------------------------------------------------------------------- */
4811 /* called in GDBusWorker thread with connection's lock held */
4813 obj_message_func (GDBusConnection *connection,
4815 GDBusMessage *message)
4817 const gchar *interface_name;
4818 const gchar *member;
4819 const gchar *signature;
4824 interface_name = g_dbus_message_get_interface (message);
4825 member = g_dbus_message_get_member (message);
4826 signature = g_dbus_message_get_signature (message);
4828 /* see if we have an interface for handling this call */
4829 if (interface_name != NULL)
4831 ExportedInterface *ei;
4832 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4835 /* we do - invoke the handler in idle in the right thread */
4837 /* handle no vtable or handler being present */
4838 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
4841 handled = validate_and_maybe_schedule_method_call (connection,
4853 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4854 g_strcmp0 (member, "Introspect") == 0 &&
4855 g_strcmp0 (signature, "") == 0)
4857 handled = handle_introspect (connection, eo, message);
4860 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4861 g_strcmp0 (member, "Get") == 0 &&
4862 g_strcmp0 (signature, "ss") == 0)
4864 handled = handle_getset_property (connection, eo, message, TRUE);
4867 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4868 g_strcmp0 (member, "Set") == 0 &&
4869 g_strcmp0 (signature, "ssv") == 0)
4871 handled = handle_getset_property (connection, eo, message, FALSE);
4874 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4875 g_strcmp0 (member, "GetAll") == 0 &&
4876 g_strcmp0 (signature, "s") == 0)
4878 handled = handle_get_all_properties (connection, eo, message);
4887 * g_dbus_connection_register_object:
4888 * @connection: A #GDBusConnection.
4889 * @object_path: The object path to register at.
4890 * @interface_info: Introspection data for the interface.
4891 * @vtable: (allow-none): A #GDBusInterfaceVTable to call into or %NULL.
4892 * @user_data: (allow-none): Data to pass to functions in @vtable.
4893 * @user_data_free_func: Function to call when the object path is unregistered.
4894 * @error: Return location for error or %NULL.
4896 * Registers callbacks for exported objects at @object_path with the
4897 * D-Bus interface that is described in @interface_info.
4899 * Calls to functions in @vtable (and @user_data_free_func) will
4900 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
4901 * loop</link> of the thread you are calling this method from.
4903 * Note that all #GVariant values passed to functions in @vtable will match
4904 * the signature given in @interface_info - if a remote caller passes
4905 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
4906 * is returned to the remote caller.
4908 * Additionally, if the remote caller attempts to invoke methods or
4909 * access properties not mentioned in @interface_info the
4910 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
4911 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
4912 * are returned to the caller.
4914 * It is considered a programming error if the
4915 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
4916 * #GVariant of incorrect type.
4918 * If an existing callback is already registered at @object_path and
4919 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
4921 * GDBus automatically implements the standard D-Bus interfaces
4922 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
4923 * and org.freedesktop.Peer, so you don't have to implement those for
4924 * the objects you export. You <emphasis>can</emphasis> implement
4925 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
4926 * and setting of properties asynchronously.
4928 * Note that the reference count on @interface_info will be
4929 * incremented by 1 (unless allocated statically, e.g. if the
4930 * reference count is -1, see g_dbus_interface_info_ref()) for as long
4931 * as the object is exported. Also note that @vtable will be copied.
4933 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
4935 * Returns: 0 if @error is set, otherwise a registration id (never 0)
4936 * that can be used with g_dbus_connection_unregister_object() .
4941 g_dbus_connection_register_object (GDBusConnection *connection,
4942 const gchar *object_path,
4943 GDBusInterfaceInfo *interface_info,
4944 const GDBusInterfaceVTable *vtable,
4946 GDestroyNotify user_data_free_func,
4950 ExportedInterface *ei;
4953 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4954 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4955 g_return_val_if_fail (interface_info != NULL, 0);
4956 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
4957 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4958 g_return_val_if_fail (check_initialized (connection), 0);
4962 CONNECTION_LOCK (connection);
4964 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
4967 eo = g_new0 (ExportedObject, 1);
4968 eo->object_path = g_strdup (object_path);
4969 eo->connection = connection;
4970 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
4973 (GDestroyNotify) exported_interface_free);
4974 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
4977 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
4983 _("An object is already exported for the interface %s at %s"),
4984 interface_info->name,
4989 ei = g_new0 (ExportedInterface, 1);
4990 ei->id = _global_registration_id++; /* TODO: overflow etc. */
4992 ei->user_data = user_data;
4993 ei->user_data_free_func = user_data_free_func;
4994 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
4995 ei->interface_info = g_dbus_interface_info_ref (interface_info);
4996 g_dbus_interface_info_cache_build (ei->interface_info);
4997 ei->interface_name = g_strdup (interface_info->name);
4998 ei->context = g_main_context_ref_thread_default ();
5000 g_hash_table_insert (eo->map_if_name_to_ei,
5001 (gpointer) ei->interface_name,
5003 g_hash_table_insert (connection->map_id_to_ei,
5004 GUINT_TO_POINTER (ei->id),
5010 CONNECTION_UNLOCK (connection);
5016 * g_dbus_connection_unregister_object:
5017 * @connection: A #GDBusConnection.
5018 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
5020 * Unregisters an object.
5022 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
5027 g_dbus_connection_unregister_object (GDBusConnection *connection,
5028 guint registration_id)
5030 ExportedInterface *ei;
5034 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5035 g_return_val_if_fail (check_initialized (connection), FALSE);
5039 CONNECTION_LOCK (connection);
5041 ei = g_hash_table_lookup (connection->map_id_to_ei,
5042 GUINT_TO_POINTER (registration_id));
5048 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5049 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5050 /* unregister object path if we have no more exported interfaces */
5051 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5052 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5058 CONNECTION_UNLOCK (connection);
5063 /* ---------------------------------------------------------------------------------------------------- */
5066 * g_dbus_connection_emit_signal:
5067 * @connection: A #GDBusConnection.
5068 * @destination_bus_name: (allow-none): The unique bus name for the destination
5069 * for the signal or %NULL to emit to all listeners.
5070 * @object_path: Path of remote object.
5071 * @interface_name: D-Bus interface to emit a signal on.
5072 * @signal_name: The name of the signal to emit.
5073 * @parameters: (allow-none): A #GVariant tuple with parameters for the signal
5074 * or %NULL if not passing parameters.
5075 * @error: Return location for error or %NULL.
5079 * If the parameters GVariant is floating, it is consumed.
5081 * This can only fail if @parameters is not compatible with the D-Bus protocol.
5083 * Returns: %TRUE unless @error is set.
5088 g_dbus_connection_emit_signal (GDBusConnection *connection,
5089 const gchar *destination_bus_name,
5090 const gchar *object_path,
5091 const gchar *interface_name,
5092 const gchar *signal_name,
5093 GVariant *parameters,
5096 GDBusMessage *message;
5102 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5103 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5104 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5105 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5106 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5107 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5108 g_return_val_if_fail (check_initialized (connection), FALSE);
5110 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5112 _g_dbus_debug_print_lock ();
5113 g_print ("========================================================================\n"
5114 "GDBus-debug:Emission:\n"
5115 " >>>> SIGNAL EMISSION %s.%s()\n"
5117 " destination %s\n",
5118 interface_name, signal_name,
5120 destination_bus_name != NULL ? destination_bus_name : "(none)");
5121 _g_dbus_debug_print_unlock ();
5124 message = g_dbus_message_new_signal (object_path,
5128 if (destination_bus_name != NULL)
5129 g_dbus_message_set_header (message,
5130 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5131 g_variant_new_string (destination_bus_name));
5133 if (parameters != NULL)
5134 g_dbus_message_set_body (message, parameters);
5136 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5137 g_object_unref (message);
5143 add_call_flags (GDBusMessage *message,
5144 GDBusCallFlags flags)
5146 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5147 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
5151 decode_method_reply (GDBusMessage *reply,
5152 const gchar *method_name,
5153 const GVariantType *reply_type,
5154 GUnixFDList **out_fd_list,
5160 switch (g_dbus_message_get_message_type (reply))
5162 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5163 result = g_dbus_message_get_body (reply);
5166 result = g_variant_new ("()");
5167 g_variant_ref_sink (result);
5171 g_variant_ref (result);
5174 if (!g_variant_is_of_type (result, reply_type))
5176 gchar *type_string = g_variant_type_dup_string (reply_type);
5180 G_IO_ERROR_INVALID_ARGUMENT,
5181 _("Method `%s' returned type `%s', but expected `%s'"),
5182 method_name, g_variant_get_type_string (result), type_string);
5184 g_variant_unref (result);
5185 g_free (type_string);
5192 if (out_fd_list != NULL)
5194 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5195 if (*out_fd_list != NULL)
5196 g_object_ref (*out_fd_list);
5202 case G_DBUS_MESSAGE_TYPE_ERROR:
5203 g_dbus_message_to_gerror (reply, error);
5207 g_assert_not_reached ();
5217 GSimpleAsyncResult *simple;
5218 GVariantType *reply_type;
5219 gchar *method_name; /* for error message */
5223 GUnixFDList *fd_list;
5227 call_state_free (CallState *state)
5229 g_variant_type_free (state->reply_type);
5230 g_free (state->method_name);
5232 if (state->value != NULL)
5233 g_variant_unref (state->value);
5234 if (state->fd_list != NULL)
5235 g_object_unref (state->fd_list);
5236 g_slice_free (CallState, state);
5239 /* called in any thread, with the connection's lock not held */
5241 g_dbus_connection_call_done (GObject *source,
5242 GAsyncResult *result,
5245 GSimpleAsyncResult *simple;
5246 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5247 CallState *state = user_data;
5249 GDBusMessage *reply;
5252 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5256 if (G_UNLIKELY (_g_dbus_debug_call ()))
5258 _g_dbus_debug_print_lock ();
5259 g_print ("========================================================================\n"
5260 "GDBus-debug:Call:\n"
5261 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5267 g_print ("SUCCESS\n");
5271 g_print ("FAILED: %s\n",
5274 _g_dbus_debug_print_unlock ();
5278 state->value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5280 simple = state->simple; /* why? because state is freed before we unref simple.. */
5283 g_simple_async_result_take_error (state->simple, error);
5284 g_simple_async_result_complete (state->simple);
5285 call_state_free (state);
5289 g_simple_async_result_set_op_res_gpointer (state->simple, state, (GDestroyNotify) call_state_free);
5290 g_simple_async_result_complete (state->simple);
5292 g_clear_object (&reply);
5293 g_object_unref (simple);
5296 /* called in any thread, with the connection's lock not held */
5298 g_dbus_connection_call_internal (GDBusConnection *connection,
5299 const gchar *bus_name,
5300 const gchar *object_path,
5301 const gchar *interface_name,
5302 const gchar *method_name,
5303 GVariant *parameters,
5304 const GVariantType *reply_type,
5305 GDBusCallFlags flags,
5307 GUnixFDList *fd_list,
5308 GCancellable *cancellable,
5309 GAsyncReadyCallback callback,
5312 GDBusMessage *message;
5315 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5316 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5317 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5318 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5319 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5320 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5321 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5322 g_return_if_fail (check_initialized (connection));
5324 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5326 g_return_if_fail (fd_list == NULL);
5329 message = g_dbus_message_new_method_call (bus_name,
5333 add_call_flags (message, flags);
5334 if (parameters != NULL)
5335 g_dbus_message_set_body (message, parameters);
5338 if (fd_list != NULL)
5339 g_dbus_message_set_unix_fd_list (message, fd_list);
5342 /* If the user has no callback then we can just send the message with
5343 * the G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set and skip all
5344 * the logic for processing the reply. If the service sends the reply
5345 * anyway then it will just be ignored.
5347 if (callback != NULL)
5351 state = g_slice_new0 (CallState);
5352 state->simple = g_simple_async_result_new (G_OBJECT (connection),
5353 callback, user_data,
5354 g_dbus_connection_call_internal);
5355 g_simple_async_result_set_check_cancellable (state->simple, cancellable);
5356 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5358 if (reply_type == NULL)
5359 reply_type = G_VARIANT_TYPE_ANY;
5361 state->reply_type = g_variant_type_copy (reply_type);
5363 g_dbus_connection_send_message_with_reply (connection,
5365 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5369 g_dbus_connection_call_done,
5371 serial = state->serial;
5375 GDBusMessageFlags flags;
5377 flags = g_dbus_message_get_flags (message);
5378 flags |= G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
5379 g_dbus_message_set_flags (message, flags);
5381 g_dbus_connection_send_message (connection,
5383 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5387 if (G_UNLIKELY (_g_dbus_debug_call ()))
5389 _g_dbus_debug_print_lock ();
5390 g_print ("========================================================================\n"
5391 "GDBus-debug:Call:\n"
5392 " >>>> ASYNC %s.%s()\n"
5394 " owned by name %s (serial %d)\n",
5398 bus_name != NULL ? bus_name : "(none)",
5400 _g_dbus_debug_print_unlock ();
5403 if (message != NULL)
5404 g_object_unref (message);
5407 /* called in any thread, with the connection's lock not held */
5409 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
5410 GUnixFDList **out_fd_list,
5414 GSimpleAsyncResult *simple;
5417 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5418 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
5419 g_dbus_connection_call_internal), NULL);
5420 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5422 simple = G_SIMPLE_ASYNC_RESULT (res);
5424 if (g_simple_async_result_propagate_error (simple, error))
5427 state = g_simple_async_result_get_op_res_gpointer (simple);
5428 if (out_fd_list != NULL)
5429 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
5430 return g_variant_ref (state->value);
5433 /* called in any user thread, with the connection's lock not held */
5435 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
5436 const gchar *bus_name,
5437 const gchar *object_path,
5438 const gchar *interface_name,
5439 const gchar *method_name,
5440 GVariant *parameters,
5441 const GVariantType *reply_type,
5442 GDBusCallFlags flags,
5444 GUnixFDList *fd_list,
5445 GUnixFDList **out_fd_list,
5446 GCancellable *cancellable,
5449 GDBusMessage *message;
5450 GDBusMessage *reply;
5452 GError *local_error;
5453 GDBusSendMessageFlags send_flags;
5459 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5460 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5461 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5462 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5463 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5464 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5465 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5467 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
5469 g_return_val_if_fail (fd_list == NULL, NULL);
5471 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5473 if (!(flags & CALL_FLAGS_INITIALIZING))
5474 g_return_val_if_fail (check_initialized (connection), FALSE);
5476 if (reply_type == NULL)
5477 reply_type = G_VARIANT_TYPE_ANY;
5479 message = g_dbus_message_new_method_call (bus_name,
5483 add_call_flags (message, flags);
5484 if (parameters != NULL)
5485 g_dbus_message_set_body (message, parameters);
5488 if (fd_list != NULL)
5489 g_dbus_message_set_unix_fd_list (message, fd_list);
5492 if (G_UNLIKELY (_g_dbus_debug_call ()))
5494 _g_dbus_debug_print_lock ();
5495 g_print ("========================================================================\n"
5496 "GDBus-debug:Call:\n"
5497 " >>>> SYNC %s.%s()\n"
5499 " owned by name %s\n",
5503 bus_name != NULL ? bus_name : "(none)");
5504 _g_dbus_debug_print_unlock ();
5509 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
5511 /* translate from one flavour of flags to another... */
5512 if (flags & CALL_FLAGS_INITIALIZING)
5513 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
5515 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5519 NULL, /* volatile guint32 *out_serial */
5523 if (G_UNLIKELY (_g_dbus_debug_call ()))
5525 _g_dbus_debug_print_lock ();
5526 g_print ("========================================================================\n"
5527 "GDBus-debug:Call:\n"
5528 " <<<< SYNC COMPLETE %s.%s()\n"
5534 g_print ("SUCCESS\n");
5538 g_print ("FAILED: %s\n",
5539 local_error->message);
5541 _g_dbus_debug_print_unlock ();
5547 *error = local_error;
5549 g_error_free (local_error);
5553 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
5556 if (message != NULL)
5557 g_object_unref (message);
5559 g_object_unref (reply);
5564 /* ---------------------------------------------------------------------------------------------------- */
5567 * g_dbus_connection_call:
5568 * @connection: A #GDBusConnection.
5569 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5570 * @connection is not a message bus connection.
5571 * @object_path: Path of remote object.
5572 * @interface_name: D-Bus interface to invoke method on.
5573 * @method_name: The name of the method to invoke.
5574 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5575 * or %NULL if not passing parameters.
5576 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5577 * @flags: Flags from the #GDBusCallFlags enumeration.
5578 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5579 * timeout or %G_MAXINT for no timeout.
5580 * @cancellable: (allow-none): A #GCancellable or %NULL.
5581 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5582 * satisfied or %NULL if you don't care about the result of the
5583 * method invocation.
5584 * @user_data: The data to pass to @callback.
5586 * Asynchronously invokes the @method_name method on the
5587 * @interface_name D-Bus interface on the remote object at
5588 * @object_path owned by @bus_name.
5590 * If @connection is closed then the operation will fail with
5591 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
5592 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
5593 * not compatible with the D-Bus protocol, the operation fails with
5594 * %G_IO_ERROR_INVALID_ARGUMENT.
5596 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
5597 * error will be raised if it does not match. Said another way, if you give a @reply_type
5598 * then any non-%NULL return value will be of this type.
5600 * If the @parameters #GVariant is floating, it is consumed. This allows
5601 * convenient 'inline' use of g_variant_new(), e.g.:
5603 * g_dbus_connection_call (connection,
5604 * "org.freedesktop.StringThings",
5605 * "/org/freedesktop/StringThings",
5606 * "org.freedesktop.StringThings",
5608 * g_variant_new ("(ss)",
5612 * G_DBUS_CALL_FLAGS_NONE,
5615 * (GAsyncReadyCallback) two_strings_done,
5619 * This is an asynchronous method. When the operation is finished, @callback will be invoked
5620 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
5621 * of the thread you are calling this method from. You can then call
5622 * g_dbus_connection_call_finish() to get the result of the operation.
5623 * See g_dbus_connection_call_sync() for the synchronous version of this
5626 * If @callback is %NULL then the D-Bus method call message will be sent with
5627 * the %G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set.
5632 g_dbus_connection_call (GDBusConnection *connection,
5633 const gchar *bus_name,
5634 const gchar *object_path,
5635 const gchar *interface_name,
5636 const gchar *method_name,
5637 GVariant *parameters,
5638 const GVariantType *reply_type,
5639 GDBusCallFlags flags,
5641 GCancellable *cancellable,
5642 GAsyncReadyCallback callback,
5645 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);
5649 * g_dbus_connection_call_finish:
5650 * @connection: A #GDBusConnection.
5651 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
5652 * @error: Return location for error or %NULL.
5654 * Finishes an operation started with g_dbus_connection_call().
5656 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5657 * return values. Free with g_variant_unref().
5662 g_dbus_connection_call_finish (GDBusConnection *connection,
5666 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
5670 * g_dbus_connection_call_sync:
5671 * @connection: A #GDBusConnection.
5672 * @bus_name: A unique or well-known bus name.
5673 * @object_path: Path of remote object.
5674 * @interface_name: D-Bus interface to invoke method on.
5675 * @method_name: The name of the method to invoke.
5676 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5677 * or %NULL if not passing parameters.
5678 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5679 * @flags: Flags from the #GDBusCallFlags enumeration.
5680 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5681 * timeout or %G_MAXINT for no timeout.
5682 * @cancellable: (allow-none): A #GCancellable or %NULL.
5683 * @error: Return location for error or %NULL.
5685 * Synchronously invokes the @method_name method on the
5686 * @interface_name D-Bus interface on the remote object at
5687 * @object_path owned by @bus_name.
5689 * If @connection is closed then the operation will fail with
5690 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
5691 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
5692 * contains a value not compatible with the D-Bus protocol, the operation
5693 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
5695 * If @reply_type is non-%NULL then the reply will be checked for having
5696 * this type and an error will be raised if it does not match. Said
5697 * another way, if you give a @reply_type then any non-%NULL return
5698 * value will be of this type.
5700 * If the @parameters #GVariant is floating, it is consumed.
5701 * This allows convenient 'inline' use of g_variant_new(), e.g.:
5703 * g_dbus_connection_call_sync (connection,
5704 * "org.freedesktop.StringThings",
5705 * "/org/freedesktop/StringThings",
5706 * "org.freedesktop.StringThings",
5708 * g_variant_new ("(ss)",
5712 * G_DBUS_CALL_FLAGS_NONE,
5718 * The calling thread is blocked until a reply is received. See
5719 * g_dbus_connection_call() for the asynchronous version of
5722 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5723 * return values. Free with g_variant_unref().
5728 g_dbus_connection_call_sync (GDBusConnection *connection,
5729 const gchar *bus_name,
5730 const gchar *object_path,
5731 const gchar *interface_name,
5732 const gchar *method_name,
5733 GVariant *parameters,
5734 const GVariantType *reply_type,
5735 GDBusCallFlags flags,
5737 GCancellable *cancellable,
5740 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);
5743 /* ---------------------------------------------------------------------------------------------------- */
5748 * g_dbus_connection_call_with_unix_fd_list:
5749 * @connection: A #GDBusConnection.
5750 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5751 * @connection is not a message bus connection.
5752 * @object_path: Path of remote object.
5753 * @interface_name: D-Bus interface to invoke method on.
5754 * @method_name: The name of the method to invoke.
5755 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5756 * or %NULL if not passing parameters.
5757 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5758 * @flags: Flags from the #GDBusCallFlags enumeration.
5759 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5760 * timeout or %G_MAXINT for no timeout.
5761 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
5762 * @cancellable: (allow-none): A #GCancellable or %NULL.
5763 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5764 * satisfied or %NULL if you don't * care about the result of the
5765 * method invocation.
5766 * @user_data: The data to pass to @callback.
5768 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
5770 * This method is only available on UNIX.
5775 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
5776 const gchar *bus_name,
5777 const gchar *object_path,
5778 const gchar *interface_name,
5779 const gchar *method_name,
5780 GVariant *parameters,
5781 const GVariantType *reply_type,
5782 GDBusCallFlags flags,
5784 GUnixFDList *fd_list,
5785 GCancellable *cancellable,
5786 GAsyncReadyCallback callback,
5789 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);
5793 * g_dbus_connection_call_with_unix_fd_list_finish:
5794 * @connection: A #GDBusConnection.
5795 * @out_fd_list: (out) (allow-none): Return location for a #GUnixFDList or %NULL.
5796 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call_with_unix_fd_list().
5797 * @error: Return location for error or %NULL.
5799 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
5801 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5802 * return values. Free with g_variant_unref().
5807 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
5808 GUnixFDList **out_fd_list,
5812 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
5816 * g_dbus_connection_call_with_unix_fd_list_sync:
5817 * @connection: A #GDBusConnection.
5818 * @bus_name: A unique or well-known bus name.
5819 * @object_path: Path of remote object.
5820 * @interface_name: D-Bus interface to invoke method on.
5821 * @method_name: The name of the method to invoke.
5822 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5823 * or %NULL if not passing parameters.
5824 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5825 * @flags: Flags from the #GDBusCallFlags enumeration.
5826 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5827 * timeout or %G_MAXINT for no timeout.
5828 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
5829 * @out_fd_list: (out) (allow-none): Return location for a #GUnixFDList or %NULL.
5830 * @cancellable: (allow-none): A #GCancellable or %NULL.
5831 * @error: Return location for error or %NULL.
5833 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
5835 * This method is only available on UNIX.
5837 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5838 * return values. Free with g_variant_unref().
5843 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
5844 const gchar *bus_name,
5845 const gchar *object_path,
5846 const gchar *interface_name,
5847 const gchar *method_name,
5848 GVariant *parameters,
5849 const GVariantType *reply_type,
5850 GDBusCallFlags flags,
5852 GUnixFDList *fd_list,
5853 GUnixFDList **out_fd_list,
5854 GCancellable *cancellable,
5857 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);
5860 #endif /* G_OS_UNIX */
5862 /* ---------------------------------------------------------------------------------------------------- */
5864 struct ExportedSubtree
5868 GDBusConnection *connection;
5869 GDBusSubtreeVTable *vtable;
5870 GDBusSubtreeFlags flags;
5872 GMainContext *context;
5874 GDestroyNotify user_data_free_func;
5878 exported_subtree_free (ExportedSubtree *es)
5880 call_destroy_notify (es->context,
5881 es->user_data_free_func,
5884 g_main_context_unref (es->context);
5886 _g_dbus_subtree_vtable_free (es->vtable);
5887 g_free (es->object_path);
5891 /* called without lock held in the thread where the caller registered
5895 handle_subtree_introspect (GDBusConnection *connection,
5896 ExportedSubtree *es,
5897 GDBusMessage *message)
5901 GDBusMessage *reply;
5904 const gchar *sender;
5905 const gchar *requested_object_path;
5906 const gchar *requested_node;
5907 GDBusInterfaceInfo **interfaces;
5909 gchar **subnode_paths;
5910 gboolean has_properties_interface;
5911 gboolean has_introspectable_interface;
5915 requested_object_path = g_dbus_message_get_path (message);
5916 sender = g_dbus_message_get_sender (message);
5917 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5919 s = g_string_new (NULL);
5920 introspect_append_header (s);
5922 /* Strictly we don't need the children in dynamic mode, but we avoid the
5923 * conditionals to preserve code clarity
5925 children = es->vtable->enumerate (es->connection,
5932 requested_node = strrchr (requested_object_path, '/') + 1;
5934 /* Assert existence of object if we are not dynamic */
5935 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
5936 !_g_strv_has_string ((const gchar * const *) children, requested_node))
5941 requested_node = NULL;
5944 interfaces = es->vtable->introspect (es->connection,
5949 if (interfaces != NULL)
5951 has_properties_interface = FALSE;
5952 has_introspectable_interface = FALSE;
5954 for (n = 0; interfaces[n] != NULL; n++)
5956 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
5957 has_properties_interface = TRUE;
5958 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
5959 has_introspectable_interface = TRUE;
5961 if (!has_properties_interface)
5962 g_string_append (s, introspect_properties_interface);
5963 if (!has_introspectable_interface)
5964 g_string_append (s, introspect_introspectable_interface);
5966 for (n = 0; interfaces[n] != NULL; n++)
5968 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
5969 g_dbus_interface_info_unref (interfaces[n]);
5971 g_free (interfaces);
5974 /* then include <node> entries from the Subtree for the root */
5977 for (n = 0; children != NULL && children[n] != NULL; n++)
5978 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
5981 /* finally include nodes registered below us */
5982 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
5983 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
5984 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
5985 g_strfreev (subnode_paths);
5987 g_string_append (s, "</node>\n");
5989 reply = g_dbus_message_new_method_reply (message);
5990 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5991 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5992 g_object_unref (reply);
5997 g_string_free (s, TRUE);
5998 g_strfreev (children);
6002 /* called without lock held in the thread where the caller registered
6006 handle_subtree_method_invocation (GDBusConnection *connection,
6007 ExportedSubtree *es,
6008 GDBusMessage *message)
6011 const gchar *sender;
6012 const gchar *interface_name;
6013 const gchar *member;
6014 const gchar *signature;
6015 const gchar *requested_object_path;
6016 const gchar *requested_node;
6018 GDBusInterfaceInfo *interface_info;
6019 const GDBusInterfaceVTable *interface_vtable;
6020 gpointer interface_user_data;
6022 GDBusInterfaceInfo **interfaces;
6023 gboolean is_property_get;
6024 gboolean is_property_set;
6025 gboolean is_property_get_all;
6030 requested_object_path = g_dbus_message_get_path (message);
6031 sender = g_dbus_message_get_sender (message);
6032 interface_name = g_dbus_message_get_interface (message);
6033 member = g_dbus_message_get_member (message);
6034 signature = g_dbus_message_get_signature (message);
6035 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6037 is_property_get = FALSE;
6038 is_property_set = FALSE;
6039 is_property_get_all = FALSE;
6040 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6042 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6043 is_property_get = TRUE;
6044 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6045 is_property_set = TRUE;
6046 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6047 is_property_get_all = TRUE;
6052 requested_node = strrchr (requested_object_path, '/') + 1;
6054 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6056 /* We don't want to dispatch to unenumerated
6057 * nodes, so ensure that the child exists.
6062 children = es->vtable->enumerate (es->connection,
6067 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6068 g_strfreev (children);
6076 requested_node = NULL;
6079 /* get introspection data for the node */
6080 interfaces = es->vtable->introspect (es->connection,
6082 requested_object_path,
6086 if (interfaces == NULL)
6089 interface_info = NULL;
6090 for (n = 0; interfaces[n] != NULL; n++)
6092 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6093 interface_info = interfaces[n];
6096 /* dispatch the call if the user wants to handle it */
6097 if (interface_info != NULL)
6099 /* figure out where to dispatch the method call */
6100 interface_user_data = NULL;
6101 interface_vtable = es->vtable->dispatch (es->connection,
6106 &interface_user_data,
6108 if (interface_vtable == NULL)
6111 CONNECTION_LOCK (connection);
6112 handled = validate_and_maybe_schedule_method_call (es->connection,
6119 interface_user_data);
6120 CONNECTION_UNLOCK (connection);
6122 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6123 else if (is_property_get || is_property_set || is_property_get_all)
6125 if (is_property_get)
6126 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6127 else if (is_property_set)
6128 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6129 else if (is_property_get_all)
6130 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6132 g_assert_not_reached ();
6134 /* see if the object supports this interface at all */
6135 for (n = 0; interfaces[n] != NULL; n++)
6137 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6138 interface_info = interfaces[n];
6141 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6142 * claims it won't support the interface
6144 if (interface_info == NULL)
6146 GDBusMessage *reply;
6147 reply = g_dbus_message_new_method_error (message,
6148 "org.freedesktop.DBus.Error.InvalidArgs",
6149 _("No such interface `%s'"),
6151 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6152 g_object_unref (reply);
6157 /* figure out where to dispatch the property get/set/getall calls */
6158 interface_user_data = NULL;
6159 interface_vtable = es->vtable->dispatch (es->connection,
6164 &interface_user_data,
6166 if (interface_vtable == NULL)
6168 g_warning ("The subtree introspection function indicates that '%s' "
6169 "is a valid interface name, but calling the dispatch "
6170 "function on that interface gave us NULL", interface_name);
6174 if (is_property_get || is_property_set)
6176 CONNECTION_LOCK (connection);
6177 handled = validate_and_maybe_schedule_property_getset (es->connection,
6185 interface_user_data);
6186 CONNECTION_UNLOCK (connection);
6188 else if (is_property_get_all)
6190 CONNECTION_LOCK (connection);
6191 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6198 interface_user_data);
6199 CONNECTION_UNLOCK (connection);
6204 if (interfaces != NULL)
6206 for (n = 0; interfaces[n] != NULL; n++)
6207 g_dbus_interface_info_unref (interfaces[n]);
6208 g_free (interfaces);
6216 GDBusMessage *message;
6217 ExportedSubtree *es;
6218 } SubtreeDeferredData;
6221 subtree_deferred_data_free (SubtreeDeferredData *data)
6223 g_object_unref (data->message);
6227 /* called without lock held in the thread where the caller registered the subtree */
6229 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6231 SubtreeDeferredData *data = _data;
6236 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6237 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6238 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6239 handled = handle_subtree_introspect (data->es->connection,
6243 handled = handle_subtree_method_invocation (data->es->connection,
6249 CONNECTION_LOCK (data->es->connection);
6250 handled = handle_generic_unlocked (data->es->connection, data->message);
6251 CONNECTION_UNLOCK (data->es->connection);
6254 /* if we couldn't handle the request, just bail with the UnknownMethod error */
6257 GDBusMessage *reply;
6258 reply = g_dbus_message_new_method_error (data->message,
6259 "org.freedesktop.DBus.Error.UnknownMethod",
6260 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
6261 g_dbus_message_get_member (data->message),
6262 g_dbus_message_get_interface (data->message),
6263 g_dbus_message_get_signature (data->message));
6264 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6265 g_object_unref (reply);
6271 /* called in GDBusWorker thread with connection's lock held */
6273 subtree_message_func (GDBusConnection *connection,
6274 ExportedSubtree *es,
6275 GDBusMessage *message)
6277 GSource *idle_source;
6278 SubtreeDeferredData *data;
6280 data = g_new0 (SubtreeDeferredData, 1);
6281 data->message = g_object_ref (message);
6284 /* defer this call to an idle handler in the right thread */
6285 idle_source = g_idle_source_new ();
6286 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
6287 g_source_set_callback (idle_source,
6288 process_subtree_vtable_message_in_idle_cb,
6290 (GDestroyNotify) subtree_deferred_data_free);
6291 g_source_attach (idle_source, es->context);
6292 g_source_unref (idle_source);
6294 /* since we own the entire subtree, handlers for objects not in the subtree have been
6295 * tried already by libdbus-1 - so we just need to ensure that we're always going
6296 * to reply to the message
6302 * g_dbus_connection_register_subtree:
6303 * @connection: A #GDBusConnection.
6304 * @object_path: The object path to register the subtree at.
6305 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
6306 * @flags: Flags used to fine tune the behavior of the subtree.
6307 * @user_data: Data to pass to functions in @vtable.
6308 * @user_data_free_func: Function to call when the subtree is unregistered.
6309 * @error: Return location for error or %NULL.
6311 * Registers a whole subtree of <quote>dynamic</quote> objects.
6313 * The @enumerate and @introspection functions in @vtable are used to
6314 * convey, to remote callers, what nodes exist in the subtree rooted
6317 * When handling remote calls into any node in the subtree, first the
6318 * @enumerate function is used to check if the node exists. If the node exists
6319 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6320 * the @introspection function is used to check if the node supports the
6321 * requested method. If so, the @dispatch function is used to determine
6322 * where to dispatch the call. The collected #GDBusInterfaceVTable and
6323 * #gpointer will be used to call into the interface vtable for processing
6326 * All calls into user-provided code will be invoked in the <link
6327 * linkend="g-main-context-push-thread-default">thread-default main
6328 * loop</link> of the thread you are calling this method from.
6330 * If an existing subtree is already registered at @object_path or
6331 * then @error is set to #G_IO_ERROR_EXISTS.
6333 * Note that it is valid to register regular objects (using
6334 * g_dbus_connection_register_object()) in a subtree registered with
6335 * g_dbus_connection_register_subtree() - if so, the subtree handler
6336 * is tried as the last resort. One way to think about a subtree
6337 * handler is to consider it a <quote>fallback handler</quote>
6338 * for object paths not registered via g_dbus_connection_register_object()
6339 * or other bindings.
6341 * Note that @vtable will be copied so you cannot change it after
6344 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
6346 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
6347 * that can be used with g_dbus_connection_unregister_subtree() .
6352 g_dbus_connection_register_subtree (GDBusConnection *connection,
6353 const gchar *object_path,
6354 const GDBusSubtreeVTable *vtable,
6355 GDBusSubtreeFlags flags,
6357 GDestroyNotify user_data_free_func,
6361 ExportedSubtree *es;
6363 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
6364 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
6365 g_return_val_if_fail (vtable != NULL, 0);
6366 g_return_val_if_fail (error == NULL || *error == NULL, 0);
6367 g_return_val_if_fail (check_initialized (connection), 0);
6371 CONNECTION_LOCK (connection);
6373 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6379 _("A subtree is already exported for %s"),
6384 es = g_new0 (ExportedSubtree, 1);
6385 es->object_path = g_strdup (object_path);
6386 es->connection = connection;
6388 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
6390 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
6391 es->user_data = user_data;
6392 es->user_data_free_func = user_data_free_func;
6393 es->context = g_main_context_ref_thread_default ();
6395 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
6396 g_hash_table_insert (connection->map_id_to_es,
6397 GUINT_TO_POINTER (es->id),
6403 CONNECTION_UNLOCK (connection);
6408 /* ---------------------------------------------------------------------------------------------------- */
6411 * g_dbus_connection_unregister_subtree:
6412 * @connection: A #GDBusConnection.
6413 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
6415 * Unregisters a subtree.
6417 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
6422 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
6423 guint registration_id)
6425 ExportedSubtree *es;
6428 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
6429 g_return_val_if_fail (check_initialized (connection), FALSE);
6433 CONNECTION_LOCK (connection);
6435 es = g_hash_table_lookup (connection->map_id_to_es,
6436 GUINT_TO_POINTER (registration_id));
6440 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
6441 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
6446 CONNECTION_UNLOCK (connection);
6451 /* ---------------------------------------------------------------------------------------------------- */
6453 /* may be called in any thread, with connection's lock held */
6455 handle_generic_ping_unlocked (GDBusConnection *connection,
6456 const gchar *object_path,
6457 GDBusMessage *message)
6459 GDBusMessage *reply;
6460 reply = g_dbus_message_new_method_reply (message);
6461 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6462 g_object_unref (reply);
6465 /* may be called in any thread, with connection's lock held */
6467 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
6468 const gchar *object_path,
6469 GDBusMessage *message)
6471 GDBusMessage *reply;
6474 if (connection->machine_id == NULL)
6479 connection->machine_id = _g_dbus_get_machine_id (&error);
6480 if (connection->machine_id == NULL)
6482 reply = g_dbus_message_new_method_error_literal (message,
6483 "org.freedesktop.DBus.Error.Failed",
6485 g_error_free (error);
6491 reply = g_dbus_message_new_method_reply (message);
6492 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
6494 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6495 g_object_unref (reply);
6498 /* may be called in any thread, with connection's lock held */
6500 handle_generic_introspect_unlocked (GDBusConnection *connection,
6501 const gchar *object_path,
6502 GDBusMessage *message)
6507 GDBusMessage *reply;
6509 /* first the header */
6510 s = g_string_new (NULL);
6511 introspect_append_header (s);
6513 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
6514 for (n = 0; registered != NULL && registered[n] != NULL; n++)
6515 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
6516 g_strfreev (registered);
6517 g_string_append (s, "</node>\n");
6519 reply = g_dbus_message_new_method_reply (message);
6520 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6521 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6522 g_object_unref (reply);
6523 g_string_free (s, TRUE);
6526 /* may be called in any thread, with connection's lock held */
6528 handle_generic_unlocked (GDBusConnection *connection,
6529 GDBusMessage *message)
6532 const gchar *interface_name;
6533 const gchar *member;
6534 const gchar *signature;
6537 CONNECTION_ENSURE_LOCK (connection);
6541 interface_name = g_dbus_message_get_interface (message);
6542 member = g_dbus_message_get_member (message);
6543 signature = g_dbus_message_get_signature (message);
6544 path = g_dbus_message_get_path (message);
6546 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
6547 g_strcmp0 (member, "Introspect") == 0 &&
6548 g_strcmp0 (signature, "") == 0)
6550 handle_generic_introspect_unlocked (connection, path, message);
6553 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6554 g_strcmp0 (member, "Ping") == 0 &&
6555 g_strcmp0 (signature, "") == 0)
6557 handle_generic_ping_unlocked (connection, path, message);
6560 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6561 g_strcmp0 (member, "GetMachineId") == 0 &&
6562 g_strcmp0 (signature, "") == 0)
6564 handle_generic_get_machine_id_unlocked (connection, path, message);
6571 /* ---------------------------------------------------------------------------------------------------- */
6573 /* called in GDBusWorker thread with connection's lock held */
6575 distribute_method_call (GDBusConnection *connection,
6576 GDBusMessage *message)
6578 GDBusMessage *reply;
6580 ExportedSubtree *es;
6581 const gchar *object_path;
6582 const gchar *interface_name;
6583 const gchar *member;
6585 gchar *subtree_path;
6588 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
6590 interface_name = g_dbus_message_get_interface (message);
6591 member = g_dbus_message_get_member (message);
6592 path = g_dbus_message_get_path (message);
6593 subtree_path = g_strdup (path);
6594 needle = strrchr (subtree_path, '/');
6595 if (needle != NULL && needle != subtree_path)
6601 g_free (subtree_path);
6602 subtree_path = NULL;
6606 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
6608 _g_dbus_debug_print_lock ();
6609 g_print ("========================================================================\n"
6610 "GDBus-debug:Incoming:\n"
6611 " <<<< METHOD INVOCATION %s.%s()\n"
6613 " invoked by name %s\n"
6615 interface_name, member,
6617 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
6618 g_dbus_message_get_serial (message));
6619 _g_dbus_debug_print_unlock ();
6622 object_path = g_dbus_message_get_path (message);
6623 g_assert (object_path != NULL);
6625 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
6628 if (obj_message_func (connection, eo, message))
6632 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6635 if (subtree_message_func (connection, es, message))
6639 if (subtree_path != NULL)
6641 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
6644 if (subtree_message_func (connection, es, message))
6649 if (handle_generic_unlocked (connection, message))
6652 /* if we end up here, the message has not been not handled - so return an error saying this */
6653 reply = g_dbus_message_new_method_error (message,
6654 "org.freedesktop.DBus.Error.UnknownMethod",
6655 _("No such interface `%s' on object at path %s"),
6658 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6659 g_object_unref (reply);
6662 g_free (subtree_path);
6665 /* ---------------------------------------------------------------------------------------------------- */
6667 /* Called in any user thread, with the message_bus_lock held. */
6669 message_bus_get_singleton (GBusType bus_type,
6673 const gchar *starter_bus;
6679 case G_BUS_TYPE_SESSION:
6680 ret = &the_session_bus;
6683 case G_BUS_TYPE_SYSTEM:
6684 ret = &the_system_bus;
6687 case G_BUS_TYPE_STARTER:
6688 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
6689 if (g_strcmp0 (starter_bus, "session") == 0)
6691 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
6694 else if (g_strcmp0 (starter_bus, "system") == 0)
6696 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
6701 if (starter_bus != NULL)
6705 G_IO_ERROR_INVALID_ARGUMENT,
6706 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
6707 " - unknown value `%s'"),
6712 g_set_error_literal (error,
6714 G_IO_ERROR_INVALID_ARGUMENT,
6715 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
6716 "variable is not set"));
6722 g_assert_not_reached ();
6730 /* Called in any user thread, without holding locks. */
6731 static GDBusConnection *
6732 get_uninitialized_connection (GBusType bus_type,
6733 GCancellable *cancellable,
6736 GWeakRef *singleton;
6737 GDBusConnection *ret;
6741 G_LOCK (message_bus_lock);
6742 singleton = message_bus_get_singleton (bus_type, error);
6743 if (singleton == NULL)
6746 ret = g_weak_ref_get (singleton);
6751 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
6752 if (address == NULL)
6754 ret = g_object_new (G_TYPE_DBUS_CONNECTION,
6756 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
6757 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
6758 "exit-on-close", TRUE,
6761 g_weak_ref_set (singleton, ret);
6765 g_assert (ret != NULL);
6768 G_UNLOCK (message_bus_lock);
6772 /* Called in any user thread, without holding locks. */
6774 _g_bus_get_singleton_if_exists (GBusType bus_type)
6776 GWeakRef *singleton;
6777 GDBusConnection *ret = NULL;
6779 G_LOCK (message_bus_lock);
6780 singleton = message_bus_get_singleton (bus_type, NULL);
6781 if (singleton == NULL)
6784 ret = g_weak_ref_get (singleton);
6787 G_UNLOCK (message_bus_lock);
6793 * @bus_type: A #GBusType.
6794 * @cancellable: (allow-none): A #GCancellable or %NULL.
6795 * @error: Return location for error or %NULL.
6797 * Synchronously connects to the message bus specified by @bus_type.
6798 * Note that the returned object may shared with other callers,
6799 * e.g. if two separate parts of a process calls this function with
6800 * the same @bus_type, they will share the same object.
6802 * This is a synchronous failable function. See g_bus_get() and
6803 * g_bus_get_finish() for the asynchronous version.
6805 * The returned object is a singleton, that is, shared with other
6806 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6807 * event that you need a private message bus connection, use
6808 * g_dbus_address_get_for_bus_sync() and
6809 * g_dbus_connection_new_for_address().
6811 * Note that the returned #GDBusConnection object will (usually) have
6812 * the #GDBusConnection:exit-on-close property set to %TRUE.
6814 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6819 g_bus_get_sync (GBusType bus_type,
6820 GCancellable *cancellable,
6823 GDBusConnection *connection;
6825 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6827 connection = get_uninitialized_connection (bus_type, cancellable, error);
6828 if (connection == NULL)
6831 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
6833 g_object_unref (connection);
6842 bus_get_async_initable_cb (GObject *source_object,
6846 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
6850 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
6854 g_assert (error != NULL);
6855 g_simple_async_result_take_error (simple, error);
6856 g_object_unref (source_object);
6860 g_simple_async_result_set_op_res_gpointer (simple,
6864 g_simple_async_result_complete_in_idle (simple);
6865 g_object_unref (simple);
6870 * @bus_type: A #GBusType.
6871 * @cancellable: (allow-none): A #GCancellable or %NULL.
6872 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
6873 * @user_data: The data to pass to @callback.
6875 * Asynchronously connects to the message bus specified by @bus_type.
6877 * When the operation is finished, @callback will be invoked. You can
6878 * then call g_bus_get_finish() to get the result of the operation.
6880 * This is a asynchronous failable function. See g_bus_get_sync() for
6881 * the synchronous version.
6886 g_bus_get (GBusType bus_type,
6887 GCancellable *cancellable,
6888 GAsyncReadyCallback callback,
6891 GDBusConnection *connection;
6892 GSimpleAsyncResult *simple;
6895 simple = g_simple_async_result_new (NULL,
6899 g_simple_async_result_set_check_cancellable (simple, cancellable);
6902 connection = get_uninitialized_connection (bus_type, cancellable, &error);
6903 if (connection == NULL)
6905 g_assert (error != NULL);
6906 g_simple_async_result_take_error (simple, error);
6907 g_simple_async_result_complete_in_idle (simple);
6908 g_object_unref (simple);
6912 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
6915 bus_get_async_initable_cb,
6922 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
6923 * @error: Return location for error or %NULL.
6925 * Finishes an operation started with g_bus_get().
6927 * The returned object is a singleton, that is, shared with other
6928 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6929 * event that you need a private message bus connection, use
6930 * g_dbus_address_get_for_bus_sync() and
6931 * g_dbus_connection_new_for_address().
6933 * Note that the returned #GDBusConnection object will (usually) have
6934 * the #GDBusConnection:exit-on-close property set to %TRUE.
6936 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6941 g_bus_get_finish (GAsyncResult *res,
6944 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
6946 GDBusConnection *ret;
6948 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6950 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
6954 if (g_simple_async_result_propagate_error (simple, error))
6957 object = g_simple_async_result_get_op_res_gpointer (simple);
6958 g_assert (object != NULL);
6959 ret = g_object_ref (G_DBUS_CONNECTION (object));
6965 /* ---------------------------------------------------------------------------------------------------- */