1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
18 * Author: David Zeuthen <davidz@redhat.com>
24 * - would be nice to expose GDBusAuthMechanism and an extension point
26 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
27 * the mechanism VFuncs need to be able to set an error.
29 * - Need to document other mechanisms/sources for determining the D-Bus
30 * address of a well-known bus.
32 * - e.g. on Win32 we need code like from here
34 * http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
36 * that was never copied over here because it originally was copy-paste
37 * from the GPLv2 / AFL 2.1 libdbus sources.
39 * - on OS X we need to look in launchd for the address
41 * https://bugs.freedesktop.org/show_bug.cgi?id=14259
43 * - on X11 we need to look in a X11 property on the X server
44 * - (we can also just use dbus-launch(1) from the D-Bus
47 * - (ideally) this requires D-Bus spec work because none of
48 * this has never really been specced out properly (except
51 * - Related to the above, we also need to be able to launch a message bus
52 * instance.... Since we don't want to write our own bus daemon we should
53 * launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
55 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
56 * to specify where the nonce is stored. This will allow people to use
57 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
58 * to easily achieve secure RPC via nonce-tcp.
60 * - need to expose an extension point for resolving D-Bus address and
61 * turning them into GIOStream objects. This will allow us to implement
62 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
64 * - see g_dbus_address_connect() in gdbusaddress.c
66 * - would be cute to use kernel-specific APIs to resolve fds for
67 * debug output when using G_DBUS_DEBUG=message, e.g. in addition to
69 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
71 * maybe we can show more information about what fd 21 really is.
72 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
73 * Initial experiments on Linux 2.6 suggests that the symlink looks
78 * e.g. not of much use.
80 * - GDBus High-Level docs
81 * - Proxy: properties, signals...
82 * - Connection: IOStream based, ::close, connection setup steps
83 * mainloop integration, threading
84 * - Differences from libdbus (extend "Migrating from")
85 * - the message handling thread
86 * - Using GVariant instead of GValue
87 * - Explain why the high-level API is a good thing and what
88 * kind of pitfalls it avoids
89 * - Export objects before claiming names
90 * - Talk about auto-starting services (cf. GBusNameWatcherFlags)
92 * - use abstract sockets in test code
93 * - right now it doesn't work, dbus-daemon(1) fails with
95 * /gdbus/connection/filter: Failed to start message bus: Failed to bind
96 * socket "/tmp/g-dbus-tests-pid-28531": Address already in use
97 * ** WARNING **: Error reading address from dbus daemon, 0 bytes read
107 #include "gdbusauth.h"
108 #include "gdbusutils.h"
109 #include "gdbusaddress.h"
110 #include "gdbusmessage.h"
111 #include "gdbusconnection.h"
112 #include "gdbuserror.h"
113 #include "gioenumtypes.h"
114 #include "gdbusintrospection.h"
115 #include "gdbusmethodinvocation.h"
116 #include "gdbusprivate.h"
117 #include "gdbusauthobserver.h"
118 #include "ginitable.h"
119 #include "gasyncinitable.h"
120 #include "giostream.h"
121 #include "gasyncresult.h"
125 #include "gunixconnection.h"
126 #include "gunixfdmessage.h"
129 #include "glibintl.h"
132 * SECTION:gdbusconnection
133 * @short_description: D-Bus Connections
134 * @include: gio/gio.h
136 * The #GDBusConnection type is used for D-Bus connections to remote
137 * peers such as a message buses. It is a low-level API that offers a
138 * lot of flexibility. For instance, it lets you establish a connection
139 * over any transport that can by represented as an #GIOStream.
141 * This class is rarely used directly in D-Bus clients. If you are writing
142 * a D-Bus client, it is often easier to use the g_bus_own_name(),
143 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
145 * As an exception to the usual GLib rule that a particular object must not
146 * be used by two threads at the same time, #GDBusConnection's methods may be
147 * called from any thread. This is so that g_bus_get() and g_bus_get_sync()
148 * can safely return the same #GDBusConnection when called from any thread.
150 * Most of the ways to obtain a #GDBusConnection automatically initialize it
151 * (i.e. connect to D-Bus): for instance, g_dbus_connection_new() and
152 * g_bus_get(), and the synchronous versions of those methods, give you an
153 * initialized connection. Language bindings for GIO should use
154 * g_initable_new() or g_async_initable_new_async(), which also initialize the
157 * If you construct an uninitialized #GDBusConnection, such as via
158 * g_object_new(), you must initialize it via g_initable_init() or
159 * g_async_initable_init_async() before using its methods or properties.
160 * Calling methods or accessing properties on a #GDBusConnection that has not
161 * completed initialization successfully is considered to be invalid, and leads
162 * to undefined behaviour. In particular, if initialization fails with a
163 * #GError, the only valid thing you can do with that #GDBusConnection is to
164 * free it with g_object_unref().
166 * ## An example D-Bus server # {#gdbus-server}
168 * Here is an example for a D-Bus server:
169 * [gdbus-example-server.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-server.c)
171 * ## An example for exporting a subtree # {#gdbus-subtree-server}
173 * Here is an example for exporting a subtree:
174 * [gdbus-example-subtree.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-subtree.c)
176 * ## An example for file descriptor passing # {#gdbus-unix-fd-client}
178 * Here is an example for passing UNIX file descriptors:
179 * [gdbus-unix-fd-client.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-unix-fd-client.c)
181 * ## An example for exporting a GObject # {#gdbus-export}
183 * Here is an example for exporting a #GObject:
184 * [gdbus-example-export.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-export.c)
187 /* ---------------------------------------------------------------------------------------------------- */
189 typedef struct _GDBusConnectionClass GDBusConnectionClass;
192 * GDBusConnectionClass:
193 * @closed: Signal class handler for the #GDBusConnection::closed signal.
195 * Class structure for #GDBusConnection.
199 struct _GDBusConnectionClass
202 GObjectClass parent_class;
206 void (*closed) (GDBusConnection *connection,
207 gboolean remote_peer_vanished,
211 G_LOCK_DEFINE_STATIC (message_bus_lock);
213 static GWeakRef the_session_bus;
214 static GWeakRef the_system_bus;
216 /* Extra pseudo-member of GDBusSendMessageFlags.
217 * Set by initable_init() to indicate that despite not being initialized yet,
218 * enough of the only-valid-after-init members are set that we can send a
219 * message, and we're being called from its thread, so no memory barrier is
220 * required before accessing them.
222 #define SEND_MESSAGE_FLAGS_INITIALIZING (1<<31)
224 /* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
225 #define CALL_FLAGS_INITIALIZING (1<<31)
227 /* ---------------------------------------------------------------------------------------------------- */
231 GDestroyNotify callback;
233 GMainContext *context;
234 } CallDestroyNotifyData;
237 call_destroy_notify_data_in_idle (gpointer user_data)
239 CallDestroyNotifyData *data = user_data;
240 data->callback (data->user_data);
245 call_destroy_notify_data_free (CallDestroyNotifyData *data)
247 if (data->context != NULL)
248 g_main_context_unref (data->context);
253 * call_destroy_notify: <internal>
254 * @context: (allow-none): A #GMainContext or %NULL.
255 * @callback: (allow-none): A #GDestroyNotify or %NULL.
256 * @user_data: Data to pass to @callback.
258 * Schedules @callback to run in @context.
261 call_destroy_notify (GMainContext *context,
262 GDestroyNotify callback,
265 GSource *idle_source;
266 CallDestroyNotifyData *data;
268 if (callback == NULL)
271 data = g_new0 (CallDestroyNotifyData, 1);
272 data->callback = callback;
273 data->user_data = user_data;
274 data->context = context;
275 if (data->context != NULL)
276 g_main_context_ref (data->context);
278 idle_source = g_idle_source_new ();
279 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
280 g_source_set_callback (idle_source,
281 call_destroy_notify_data_in_idle,
283 (GDestroyNotify) call_destroy_notify_data_free);
284 g_source_set_name (idle_source, "[gio] call_destroy_notify_data_in_idle");
285 g_source_attach (idle_source, data->context);
286 g_source_unref (idle_source);
292 /* ---------------------------------------------------------------------------------------------------- */
295 _g_strv_has_string (const gchar* const *haystack,
300 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
302 if (g_strcmp0 (haystack[n], needle) == 0)
308 /* ---------------------------------------------------------------------------------------------------- */
311 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
313 // TODO: for some reason this doesn't work on Windows
314 #define CONNECTION_ENSURE_LOCK(obj) do { \
315 if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock))) \
317 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
318 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
323 #define CONNECTION_LOCK(obj) do { \
324 g_mutex_lock (&(obj)->lock); \
327 #define CONNECTION_UNLOCK(obj) do { \
328 g_mutex_unlock (&(obj)->lock); \
331 /* Flags in connection->atomic_flags */
333 FLAG_INITIALIZED = 1 << 0,
334 FLAG_EXIT_ON_CLOSE = 1 << 1,
341 * The #GDBusConnection structure contains only private data and
342 * should only be accessed using the provided API.
346 struct _GDBusConnection
349 GObject parent_instance;
351 /* ------------------------------------------------------------------------ */
352 /* -- General object state ------------------------------------------------ */
353 /* ------------------------------------------------------------------------ */
355 /* General-purpose lock for most fields */
358 /* A lock used in the init() method of the GInitable interface - see comments
359 * in initable_init() for why a separate lock is needed.
361 * If you need both @lock and @init_lock, you must take @init_lock first.
365 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
366 * someone calls org.freedesktop.DBus.Peer.GetMachineId(). Protected by @lock.
370 /* The underlying stream used for communication
371 * Read-only after initable_init(), so it may be read if you either
372 * hold @init_lock or check for initialization first.
376 /* The object used for authentication (if any).
377 * Read-only after initable_init(), so it may be read if you either
378 * hold @init_lock or check for initialization first.
382 /* Last serial used. Protected by @lock. */
385 /* The object used to send/receive messages.
386 * Read-only after initable_init(), so it may be read if you either
387 * hold @init_lock or check for initialization first.
391 /* If connected to a message bus, this contains the unique name assigned to
392 * us by the bus (e.g. ":1.42").
393 * Read-only after initable_init(), so it may be read if you either
394 * hold @init_lock or check for initialization first.
396 gchar *bus_unique_name;
398 /* The GUID returned by the other side if we authenticed as a client or
399 * the GUID to use if authenticating as a server.
400 * Read-only after initable_init(), so it may be read if you either
401 * hold @init_lock or check for initialization first.
405 /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
406 * Inspect @initialization_error to see whether it succeeded or failed.
408 * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
410 * FLAG_CLOSED is the closed property. It may be read at any time, but
411 * may only be written while holding @lock.
413 volatile gint atomic_flags;
415 /* If the connection could not be established during initable_init(),
416 * this GError will be set.
417 * Read-only after initable_init(), so it may be read if you either
418 * hold @init_lock or check for initialization first.
420 GError *initialization_error;
422 /* The result of g_main_context_ref_thread_default() when the object
423 * was created (the GObject _init() function) - this is used for delivery
424 * of the :closed GObject signal.
426 * Only set in the GObject init function, so no locks are needed.
428 GMainContext *main_context_at_construction;
430 /* Read-only construct properties, no locks needed */
432 GDBusConnectionFlags flags;
434 /* Map used for managing method replies, protected by @lock */
435 GHashTable *map_method_serial_to_task; /* guint32 -> GTask* */
437 /* Maps used for managing signal subscription, protected by @lock */
438 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
439 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
440 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
442 /* Maps used for managing exported objects and subtrees,
445 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
446 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
447 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
448 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
450 /* Map used for storing last used serials for each thread, protected by @lock */
451 GHashTable *map_thread_to_last_serial;
453 /* Structure used for message filters, protected by @lock */
456 /* Capabilities negotiated during authentication
457 * Read-only after initable_init(), so it may be read without holding a
458 * lock, if you check for initialization first.
460 GDBusCapabilityFlags capabilities;
462 /* Protected by @init_lock */
463 GDBusAuthObserver *authentication_observer;
465 /* Read-only after initable_init(), so it may be read if you either
466 * hold @init_lock or check for initialization first.
468 GCredentials *credentials;
470 /* set to TRUE when finalizing */
474 typedef struct ExportedObject ExportedObject;
475 static void exported_object_free (ExportedObject *eo);
477 typedef struct ExportedSubtree ExportedSubtree;
478 static void exported_subtree_free (ExportedSubtree *es);
496 PROP_CAPABILITY_FLAGS,
497 PROP_AUTHENTICATION_OBSERVER,
500 static void distribute_signals (GDBusConnection *connection,
501 GDBusMessage *message);
503 static void distribute_method_call (GDBusConnection *connection,
504 GDBusMessage *message);
506 static gboolean handle_generic_unlocked (GDBusConnection *connection,
507 GDBusMessage *message);
510 static void purge_all_signal_subscriptions (GDBusConnection *connection);
511 static void purge_all_filters (GDBusConnection *connection);
513 static void schedule_method_call (GDBusConnection *connection,
514 GDBusMessage *message,
515 guint registration_id,
516 guint subtree_registration_id,
517 const GDBusInterfaceInfo *interface_info,
518 const GDBusMethodInfo *method_info,
519 const GDBusPropertyInfo *property_info,
520 GVariant *parameters,
521 const GDBusInterfaceVTable *vtable,
522 GMainContext *main_context,
525 #define _G_ENSURE_LOCK(name) do { \
526 if (G_UNLIKELY (G_TRYLOCK(name))) \
528 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
529 "_G_ENSURE_LOCK: Lock '" #name "' is not locked"); \
533 static guint signals[LAST_SIGNAL] = { 0 };
535 static void initable_iface_init (GInitableIface *initable_iface);
536 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
538 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
539 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
540 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
544 * Check that all members of @connection that can only be accessed after
545 * the connection is initialized can safely be accessed. If not,
546 * log a critical warning. This function is a memory barrier.
548 * Returns: %TRUE if initialized
551 check_initialized (GDBusConnection *connection)
553 /* The access to @atomic_flags isn't conditional, so that this function
554 * provides a memory barrier for thread-safety even if checks are disabled.
555 * (If you don't want this stricter guarantee, you can call
556 * g_return_if_fail (check_initialized (c)).)
558 * This isn't strictly necessary now that we've decided use of an
559 * uninitialized GDBusConnection is undefined behaviour, but it seems
560 * better to be as deterministic as is feasible.
562 * (Anything that could suffer a crash from seeing undefined values
563 * must have a race condition - thread A initializes the connection while
564 * thread B calls a method without initialization, hoping that thread A will
565 * win the race - so its behaviour is undefined anyway.)
567 gint flags = g_atomic_int_get (&connection->atomic_flags);
569 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
571 /* We can safely access this, due to the memory barrier above */
572 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
578 MAY_BE_UNINITIALIZED = (1<<1)
579 } CheckUnclosedFlags;
582 * Check the same thing as check_initialized(), and also that the
583 * connection is not closed. If the connection is uninitialized,
584 * raise a critical warning (it's programmer error); if it's closed,
585 * raise a recoverable GError (it's a runtime error).
587 * This function is a memory barrier.
589 * Returns: %TRUE if initialized and not closed
592 check_unclosed (GDBusConnection *connection,
593 CheckUnclosedFlags check,
596 /* check_initialized() is effectively inlined, so we don't waste time
597 * doing two memory barriers
599 gint flags = g_atomic_int_get (&connection->atomic_flags);
601 if (!(check & MAY_BE_UNINITIALIZED))
603 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
604 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
607 if (flags & FLAG_CLOSED)
609 g_set_error_literal (error,
612 _("The connection is closed"));
619 static GHashTable *alive_connections = NULL;
622 g_dbus_connection_dispose (GObject *object)
624 GDBusConnection *connection = G_DBUS_CONNECTION (object);
626 G_LOCK (message_bus_lock);
627 CONNECTION_LOCK (connection);
628 if (connection->worker != NULL)
630 _g_dbus_worker_stop (connection->worker);
631 connection->worker = NULL;
632 if (alive_connections != NULL)
633 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
637 if (alive_connections != NULL)
638 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
640 CONNECTION_UNLOCK (connection);
641 G_UNLOCK (message_bus_lock);
643 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
644 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
648 g_dbus_connection_finalize (GObject *object)
650 GDBusConnection *connection = G_DBUS_CONNECTION (object);
652 connection->finalizing = TRUE;
654 purge_all_signal_subscriptions (connection);
656 purge_all_filters (connection);
657 g_ptr_array_unref (connection->filters);
659 if (connection->authentication_observer != NULL)
660 g_object_unref (connection->authentication_observer);
662 if (connection->auth != NULL)
663 g_object_unref (connection->auth);
665 if (connection->credentials)
666 g_object_unref (connection->credentials);
668 if (connection->stream != NULL)
670 g_object_unref (connection->stream);
671 connection->stream = NULL;
674 g_free (connection->address);
676 g_free (connection->guid);
677 g_free (connection->bus_unique_name);
679 if (connection->initialization_error != NULL)
680 g_error_free (connection->initialization_error);
682 g_hash_table_unref (connection->map_method_serial_to_task);
684 g_hash_table_unref (connection->map_rule_to_signal_data);
685 g_hash_table_unref (connection->map_id_to_signal_data);
686 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
688 g_hash_table_unref (connection->map_id_to_ei);
689 g_hash_table_unref (connection->map_object_path_to_eo);
690 g_hash_table_unref (connection->map_id_to_es);
691 g_hash_table_unref (connection->map_object_path_to_es);
693 g_hash_table_unref (connection->map_thread_to_last_serial);
695 g_main_context_unref (connection->main_context_at_construction);
697 g_free (connection->machine_id);
699 g_mutex_clear (&connection->init_lock);
700 g_mutex_clear (&connection->lock);
702 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
705 /* called in any user thread, with the connection's lock not held */
707 g_dbus_connection_get_property (GObject *object,
712 GDBusConnection *connection = G_DBUS_CONNECTION (object);
717 g_value_set_object (value, g_dbus_connection_get_stream (connection));
721 g_value_set_string (value, g_dbus_connection_get_guid (connection));
724 case PROP_UNIQUE_NAME:
725 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
729 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
732 case PROP_EXIT_ON_CLOSE:
733 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
736 case PROP_CAPABILITY_FLAGS:
737 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
741 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
746 /* called in any user thread, with the connection's lock not held */
748 g_dbus_connection_set_property (GObject *object,
753 GDBusConnection *connection = G_DBUS_CONNECTION (object);
758 connection->stream = g_value_dup_object (value);
762 connection->guid = g_value_dup_string (value);
766 connection->address = g_value_dup_string (value);
770 connection->flags = g_value_get_flags (value);
773 case PROP_EXIT_ON_CLOSE:
774 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
777 case PROP_AUTHENTICATION_OBSERVER:
778 connection->authentication_observer = g_value_dup_object (value);
782 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
787 /* Base-class implementation of GDBusConnection::closed.
789 * Called in a user thread, by the main context that was thread-default when
790 * the object was constructed.
793 g_dbus_connection_real_closed (GDBusConnection *connection,
794 gboolean remote_peer_vanished,
797 gint flags = g_atomic_int_get (&connection->atomic_flags);
799 /* Because atomic int access is a memory barrier, we can safely read
800 * initialization_error without a lock, as long as we do it afterwards.
802 if (remote_peer_vanished &&
803 (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
804 (flags & FLAG_INITIALIZED) != 0 &&
805 connection->initialization_error == NULL)
809 g_printerr ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
812 g_quark_to_string (error->domain), error->code);
816 g_printerr ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
823 g_dbus_connection_class_init (GDBusConnectionClass *klass)
825 GObjectClass *gobject_class;
827 gobject_class = G_OBJECT_CLASS (klass);
829 gobject_class->finalize = g_dbus_connection_finalize;
830 gobject_class->dispose = g_dbus_connection_dispose;
831 gobject_class->set_property = g_dbus_connection_set_property;
832 gobject_class->get_property = g_dbus_connection_get_property;
834 klass->closed = g_dbus_connection_real_closed;
837 * GDBusConnection:stream:
839 * The underlying #GIOStream used for I/O.
841 * If this is passed on construction and is a #GSocketConnection,
842 * then the corresponding #GSocket will be put into non-blocking mode.
844 * While the #GDBusConnection is active, it will interact with this
845 * stream from a worker thread, so it is not safe to interact with
846 * the stream directly.
850 g_object_class_install_property (gobject_class,
852 g_param_spec_object ("stream",
854 P_("The underlying streams used for I/O"),
858 G_PARAM_CONSTRUCT_ONLY |
859 G_PARAM_STATIC_NAME |
860 G_PARAM_STATIC_BLURB |
861 G_PARAM_STATIC_NICK));
864 * GDBusConnection:address:
866 * A D-Bus address specifying potential endpoints that can be used
867 * when establishing the connection.
871 g_object_class_install_property (gobject_class,
873 g_param_spec_string ("address",
875 P_("D-Bus address specifying potential socket endpoints"),
878 G_PARAM_CONSTRUCT_ONLY |
879 G_PARAM_STATIC_NAME |
880 G_PARAM_STATIC_BLURB |
881 G_PARAM_STATIC_NICK));
884 * GDBusConnection:flags:
886 * Flags from the #GDBusConnectionFlags enumeration.
890 g_object_class_install_property (gobject_class,
892 g_param_spec_flags ("flags",
895 G_TYPE_DBUS_CONNECTION_FLAGS,
896 G_DBUS_CONNECTION_FLAGS_NONE,
898 G_PARAM_CONSTRUCT_ONLY |
899 G_PARAM_STATIC_NAME |
900 G_PARAM_STATIC_BLURB |
901 G_PARAM_STATIC_NICK));
904 * GDBusConnection:guid:
906 * The GUID of the peer performing the role of server when
909 * If you are constructing a #GDBusConnection and pass
910 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
911 * #GDBusConnection:flags property then you MUST also set this
912 * property to a valid guid.
914 * If you are constructing a #GDBusConnection and pass
915 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
916 * #GDBusConnection:flags property you will be able to read the GUID
917 * of the other peer here after the connection has been successfully
922 g_object_class_install_property (gobject_class,
924 g_param_spec_string ("guid",
926 P_("GUID of the server peer"),
930 G_PARAM_CONSTRUCT_ONLY |
931 G_PARAM_STATIC_NAME |
932 G_PARAM_STATIC_BLURB |
933 G_PARAM_STATIC_NICK));
936 * GDBusConnection:unique-name:
938 * The unique name as assigned by the message bus or %NULL if the
939 * connection is not open or not a message bus connection.
943 g_object_class_install_property (gobject_class,
945 g_param_spec_string ("unique-name",
947 P_("Unique name of bus connection"),
950 G_PARAM_STATIC_NAME |
951 G_PARAM_STATIC_BLURB |
952 G_PARAM_STATIC_NICK));
955 * GDBusConnection:closed:
957 * A boolean specifying whether the connection has been closed.
961 g_object_class_install_property (gobject_class,
963 g_param_spec_boolean ("closed",
965 P_("Whether the connection is closed"),
968 G_PARAM_STATIC_NAME |
969 G_PARAM_STATIC_BLURB |
970 G_PARAM_STATIC_NICK));
973 * GDBusConnection:exit-on-close:
975 * A boolean specifying whether the process will be terminated (by
976 * calling `raise(SIGTERM)`) if the connection is closed by the
979 * Note that #GDBusConnection objects returned by g_bus_get_finish()
980 * and g_bus_get_sync() will (usually) have this property set to %TRUE.
984 g_object_class_install_property (gobject_class,
986 g_param_spec_boolean ("exit-on-close",
988 P_("Whether the process is terminated when the connection is closed"),
992 G_PARAM_STATIC_NAME |
993 G_PARAM_STATIC_BLURB |
994 G_PARAM_STATIC_NICK));
997 * GDBusConnection:capabilities:
999 * Flags from the #GDBusCapabilityFlags enumeration
1000 * representing connection features negotiated with the other peer.
1004 g_object_class_install_property (gobject_class,
1005 PROP_CAPABILITY_FLAGS,
1006 g_param_spec_flags ("capabilities",
1009 G_TYPE_DBUS_CAPABILITY_FLAGS,
1010 G_DBUS_CAPABILITY_FLAGS_NONE,
1012 G_PARAM_STATIC_NAME |
1013 G_PARAM_STATIC_BLURB |
1014 G_PARAM_STATIC_NICK));
1017 * GDBusConnection:authentication-observer:
1019 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
1023 g_object_class_install_property (gobject_class,
1024 PROP_AUTHENTICATION_OBSERVER,
1025 g_param_spec_object ("authentication-observer",
1026 P_("Authentication Observer"),
1027 P_("Object used to assist in the authentication process"),
1028 G_TYPE_DBUS_AUTH_OBSERVER,
1030 G_PARAM_CONSTRUCT_ONLY |
1031 G_PARAM_STATIC_NAME |
1032 G_PARAM_STATIC_BLURB |
1033 G_PARAM_STATIC_NICK));
1036 * GDBusConnection::closed:
1037 * @connection: the #GDBusConnection emitting the signal
1038 * @remote_peer_vanished: %TRUE if @connection is closed because the
1039 * remote peer closed its end of the connection
1040 * @error: (allow-none): a #GError with more details about the event or %NULL
1042 * Emitted when the connection is closed.
1044 * The cause of this event can be
1046 * - If g_dbus_connection_close() is called. In this case
1047 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
1049 * - If the remote peer closes the connection. In this case
1050 * @remote_peer_vanished is set to %TRUE and @error is set.
1052 * - If the remote peer sends invalid or malformed data. In this
1053 * case @remote_peer_vanished is set to %FALSE and @error is set.
1055 * Upon receiving this signal, you should give up your reference to
1056 * @connection. You are guaranteed that this signal is emitted only
1061 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
1062 G_TYPE_DBUS_CONNECTION,
1064 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1075 g_dbus_connection_init (GDBusConnection *connection)
1077 g_mutex_init (&connection->lock);
1078 g_mutex_init (&connection->init_lock);
1080 connection->map_method_serial_to_task = g_hash_table_new (g_direct_hash, g_direct_equal);
1082 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1084 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1086 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1089 (GDestroyNotify) g_ptr_array_unref);
1091 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1094 (GDestroyNotify) exported_object_free);
1096 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1099 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1102 (GDestroyNotify) exported_subtree_free);
1104 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1107 connection->map_thread_to_last_serial = g_hash_table_new (g_direct_hash,
1110 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1112 connection->filters = g_ptr_array_new ();
1116 * g_dbus_connection_get_stream:
1117 * @connection: a #GDBusConnection
1119 * Gets the underlying stream used for IO.
1121 * While the #GDBusConnection is active, it will interact with this
1122 * stream from a worker thread, so it is not safe to interact with
1123 * the stream directly.
1125 * Returns: (transfer none): the stream used for IO
1130 g_dbus_connection_get_stream (GDBusConnection *connection)
1132 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1134 /* do not use g_return_val_if_fail(), we want the memory barrier */
1135 if (!check_initialized (connection))
1138 return connection->stream;
1142 * g_dbus_connection_start_message_processing:
1143 * @connection: a #GDBusConnection
1145 * If @connection was created with
1146 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1147 * starts processing messages. Does nothing on if @connection wasn't
1148 * created with this flag or if the method has already been called.
1153 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1155 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1157 /* do not use g_return_val_if_fail(), we want the memory barrier */
1158 if (!check_initialized (connection))
1161 g_assert (connection->worker != NULL);
1162 _g_dbus_worker_unfreeze (connection->worker);
1166 * g_dbus_connection_is_closed:
1167 * @connection: a #GDBusConnection
1169 * Gets whether @connection is closed.
1171 * Returns: %TRUE if the connection is closed, %FALSE otherwise
1176 g_dbus_connection_is_closed (GDBusConnection *connection)
1180 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1182 flags = g_atomic_int_get (&connection->atomic_flags);
1184 return (flags & FLAG_CLOSED) ? TRUE : FALSE;
1188 * g_dbus_connection_get_capabilities:
1189 * @connection: a #GDBusConnection
1191 * Gets the capabilities negotiated with the remote peer
1193 * Returns: zero or more flags from the #GDBusCapabilityFlags enumeration
1197 GDBusCapabilityFlags
1198 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1200 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1202 /* do not use g_return_val_if_fail(), we want the memory barrier */
1203 if (!check_initialized (connection))
1204 return G_DBUS_CAPABILITY_FLAGS_NONE;
1206 return connection->capabilities;
1209 /* ---------------------------------------------------------------------------------------------------- */
1211 /* Called in a temporary thread without holding locks. */
1213 flush_in_thread_func (GTask *task,
1214 gpointer source_object,
1216 GCancellable *cancellable)
1218 GError *error = NULL;
1220 if (g_dbus_connection_flush_sync (source_object,
1223 g_task_return_boolean (task, TRUE);
1225 g_task_return_error (task, error);
1229 * g_dbus_connection_flush:
1230 * @connection: a #GDBusConnection
1231 * @cancellable: (allow-none): a #GCancellable or %NULL
1232 * @callback: (allow-none): a #GAsyncReadyCallback to call when the
1233 * request is satisfied or %NULL if you don't care about the result
1234 * @user_data: The data to pass to @callback
1236 * Asynchronously flushes @connection, that is, writes all queued
1237 * outgoing message to the transport and then flushes the transport
1238 * (using g_output_stream_flush_async()). This is useful in programs
1239 * that wants to emit a D-Bus signal and then exit immediately. Without
1240 * flushing the connection, there is no guaranteed that the message has
1241 * been sent to the networking buffers in the OS kernel.
1243 * This is an asynchronous method. When the operation is finished,
1244 * @callback will be invoked in the
1245 * [thread-default main context][g-main-context-push-thread-default]
1246 * of the thread you are calling this method from. You can
1247 * then call g_dbus_connection_flush_finish() to get the result of the
1248 * operation. See g_dbus_connection_flush_sync() for the synchronous
1254 g_dbus_connection_flush (GDBusConnection *connection,
1255 GCancellable *cancellable,
1256 GAsyncReadyCallback callback,
1261 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1263 task = g_task_new (connection, cancellable, callback, user_data);
1264 g_task_run_in_thread (task, flush_in_thread_func);
1265 g_object_unref (task);
1269 * g_dbus_connection_flush_finish:
1270 * @connection: a #GDBusConnection
1271 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1272 * to g_dbus_connection_flush()
1273 * @error: return location for error or %NULL
1275 * Finishes an operation started with g_dbus_connection_flush().
1277 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1282 g_dbus_connection_flush_finish (GDBusConnection *connection,
1286 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1287 g_return_val_if_fail (g_task_is_valid (res, connection), FALSE);
1288 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1290 return g_task_propagate_boolean (G_TASK (res), error);
1294 * g_dbus_connection_flush_sync:
1295 * @connection: a #GDBusConnection
1296 * @cancellable: (allow-none): a #GCancellable or %NULL
1297 * @error: return location for error or %NULL
1299 * Synchronously flushes @connection. The calling thread is blocked
1300 * until this is done. See g_dbus_connection_flush() for the
1301 * asynchronous version of this method and more details about what it
1304 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1309 g_dbus_connection_flush_sync (GDBusConnection *connection,
1310 GCancellable *cancellable,
1315 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1316 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1320 /* This is only a best-effort attempt to see whether the connection is
1321 * closed, so it doesn't need the lock. If the connection closes just
1322 * after this check, but before scheduling the flush operation, the
1323 * result will be more or less the same as if the connection closed while
1324 * the flush operation was pending - it'll fail with either CLOSED or
1327 if (!check_unclosed (connection, 0, error))
1330 g_assert (connection->worker != NULL);
1332 ret = _g_dbus_worker_flush_sync (connection->worker,
1340 /* ---------------------------------------------------------------------------------------------------- */
1344 GDBusConnection *connection;
1346 gboolean remote_peer_vanished;
1350 emit_closed_data_free (EmitClosedData *data)
1352 g_object_unref (data->connection);
1353 if (data->error != NULL)
1354 g_error_free (data->error);
1358 /* Called in a user thread that has acquired the main context that was
1359 * thread-default when the object was constructed
1362 emit_closed_in_idle (gpointer user_data)
1364 EmitClosedData *data = user_data;
1367 g_object_notify (G_OBJECT (data->connection), "closed");
1368 g_signal_emit (data->connection,
1369 signals[CLOSED_SIGNAL],
1371 data->remote_peer_vanished,
1377 /* Can be called from any thread, must hold lock.
1378 * FLAG_CLOSED must already have been set.
1381 schedule_closed_unlocked (GDBusConnection *connection,
1382 gboolean remote_peer_vanished,
1385 GSource *idle_source;
1386 EmitClosedData *data;
1388 CONNECTION_ENSURE_LOCK (connection);
1390 data = g_new0 (EmitClosedData, 1);
1391 data->connection = g_object_ref (connection);
1392 data->remote_peer_vanished = remote_peer_vanished;
1393 data->error = error != NULL ? g_error_copy (error) : NULL;
1395 idle_source = g_idle_source_new ();
1396 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1397 g_source_set_callback (idle_source,
1398 emit_closed_in_idle,
1400 (GDestroyNotify) emit_closed_data_free);
1401 g_source_set_name (idle_source, "[gio] emit_closed_in_idle");
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
1430 * [thread-default main context][g-main-context-push-thread-default]
1431 * 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
1435 * [thread-default main context][g-main-context-push-thread-default]
1436 * 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,
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 task = g_task_new (connection, cancellable, callback, user_data);
1460 _g_dbus_worker_close (connection->worker, task);
1461 g_object_unref (task);
1465 * g_dbus_connection_close_finish:
1466 * @connection: a #GDBusConnection
1467 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1468 * to g_dbus_connection_close()
1469 * @error: return location for error or %NULL
1471 * Finishes an operation started with g_dbus_connection_close().
1473 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1478 g_dbus_connection_close_finish (GDBusConnection *connection,
1482 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1483 g_return_val_if_fail (g_task_is_valid (res, connection), FALSE);
1484 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1486 return g_task_propagate_boolean (G_TASK (res), error);
1491 GAsyncResult *result;
1494 /* Can be called by any thread, without the connection lock */
1496 sync_close_cb (GObject *source_object,
1500 SyncCloseData *data = user_data;
1502 data->result = g_object_ref (res);
1503 g_main_loop_quit (data->loop);
1507 * g_dbus_connection_close_sync:
1508 * @connection: a #GDBusConnection
1509 * @cancellable: (allow-none): a #GCancellable or %NULL
1510 * @error: return location for error or %NULL
1512 * Synchronously closees @connection. The calling thread is blocked
1513 * until this is done. See g_dbus_connection_close() for the
1514 * asynchronous version of this method and more details about what it
1517 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1522 g_dbus_connection_close_sync (GDBusConnection *connection,
1523 GCancellable *cancellable,
1528 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1529 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1533 if (check_unclosed (connection, 0, error))
1535 GMainContext *context;
1538 context = g_main_context_new ();
1539 g_main_context_push_thread_default (context);
1540 data.loop = g_main_loop_new (context, TRUE);
1543 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1544 g_main_loop_run (data.loop);
1545 ret = g_dbus_connection_close_finish (connection, data.result, error);
1547 g_object_unref (data.result);
1548 g_main_loop_unref (data.loop);
1549 g_main_context_pop_thread_default (context);
1550 g_main_context_unref (context);
1556 /* ---------------------------------------------------------------------------------------------------- */
1559 * g_dbus_connection_get_last_serial:
1560 * @connection: a #GDBusConnection
1562 * Retrieves the last serial number assigned to a #GDBusMessage on
1563 * the current thread. This includes messages sent via both low-level
1564 * API such as g_dbus_connection_send_message() as well as
1565 * high-level API such as g_dbus_connection_emit_signal(),
1566 * g_dbus_connection_call() or g_dbus_proxy_call().
1568 * Returns: the last used serial or zero when no message has been sent
1569 * within the current thread
1574 g_dbus_connection_get_last_serial (GDBusConnection *connection)
1578 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
1580 CONNECTION_LOCK (connection);
1581 ret = GPOINTER_TO_UINT (g_hash_table_lookup (connection->map_thread_to_last_serial,
1583 CONNECTION_UNLOCK (connection);
1588 /* ---------------------------------------------------------------------------------------------------- */
1590 /* Can be called by any thread, with the connection lock held */
1592 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1593 GDBusMessage *message,
1594 GDBusSendMessageFlags flags,
1595 volatile guint32 *out_serial,
1600 guint32 serial_to_use;
1603 CONNECTION_ENSURE_LOCK (connection);
1605 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1606 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1608 /* TODO: check all necessary headers are present */
1613 if (out_serial != NULL)
1616 /* If we're in initable_init(), don't check for being initialized, to avoid
1617 * chicken-and-egg problems. initable_init() is responsible for setting up
1618 * our prerequisites (mainly connection->worker), and only calling us
1619 * from its own thread (so no memory barrier is needed).
1621 if (!check_unclosed (connection,
1622 (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
1626 blob = g_dbus_message_to_blob (message,
1628 connection->capabilities,
1633 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1634 serial_to_use = g_dbus_message_get_serial (message);
1636 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1641 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1644 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1647 g_assert_not_reached ();
1652 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1653 blob_size, serial_to_use, connection);
1654 g_printerr ("----\n");
1655 hexdump (blob, blob_size);
1656 g_printerr ("----\n");
1659 /* TODO: use connection->auth to encode the blob */
1661 if (out_serial != NULL)
1662 *out_serial = serial_to_use;
1664 /* store used serial for the current thread */
1665 /* TODO: watch the thread disposal and remove associated record
1667 * - see https://bugzilla.gnome.org/show_bug.cgi?id=676825#c7
1669 g_hash_table_replace (connection->map_thread_to_last_serial,
1671 GUINT_TO_POINTER (serial_to_use));
1673 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
1674 g_dbus_message_set_serial (message, serial_to_use);
1676 g_dbus_message_lock (message);
1677 _g_dbus_worker_send_message (connection->worker,
1681 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1692 * g_dbus_connection_send_message:
1693 * @connection: a #GDBusConnection
1694 * @message: a #GDBusMessage
1695 * @flags: flags affecting how the message is sent
1696 * @out_serial: (out) (allow-none): return location for serial number assigned
1697 * to @message when sending it or %NULL
1698 * @error: Return location for error or %NULL
1700 * Asynchronously sends @message to the peer represented by @connection.
1702 * Unless @flags contain the
1703 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1704 * will be assigned by @connection and set on @message via
1705 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1706 * serial number used will be written to this location prior to
1707 * submitting the message to the underlying transport.
1709 * If @connection is closed then the operation will fail with
1710 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1711 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1713 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
1714 * for an example of how to use this low-level API to send and receive
1715 * UNIX file descriptors.
1717 * Note that @message must be unlocked, unless @flags contain the
1718 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1720 * Returns: %TRUE if the message was well-formed and queued for
1721 * transmission, %FALSE if @error is set
1726 g_dbus_connection_send_message (GDBusConnection *connection,
1727 GDBusMessage *message,
1728 GDBusSendMessageFlags flags,
1729 volatile guint32 *out_serial,
1734 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1735 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1736 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1737 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1739 CONNECTION_LOCK (connection);
1740 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1741 CONNECTION_UNLOCK (connection);
1745 /* ---------------------------------------------------------------------------------------------------- */
1751 gulong cancellable_handler_id;
1753 GSource *timeout_source;
1758 /* Can be called from any thread with or without lock held */
1760 send_message_data_free (SendMessageData *data)
1762 g_assert (data->timeout_source == NULL);
1763 g_assert (data->cancellable_handler_id == 0);
1765 g_slice_free (SendMessageData, data);
1768 /* ---------------------------------------------------------------------------------------------------- */
1770 /* can be called from any thread with lock held */
1772 send_message_with_reply_cleanup (GTask *task, gboolean remove)
1774 GDBusConnection *connection = g_task_get_source_object (task);
1775 SendMessageData *data = g_task_get_task_data (task);
1777 CONNECTION_ENSURE_LOCK (connection);
1779 g_assert (!data->delivered);
1781 data->delivered = TRUE;
1783 if (data->timeout_source != NULL)
1785 g_source_destroy (data->timeout_source);
1786 data->timeout_source = NULL;
1788 if (data->cancellable_handler_id > 0)
1790 g_cancellable_disconnect (g_task_get_cancellable (task), data->cancellable_handler_id);
1791 data->cancellable_handler_id = 0;
1796 gboolean removed = g_hash_table_remove (connection->map_method_serial_to_task,
1797 GUINT_TO_POINTER (data->serial));
1798 g_warn_if_fail (removed);
1801 g_object_unref (task);
1804 /* ---------------------------------------------------------------------------------------------------- */
1806 /* Can be called from any thread with lock held */
1808 send_message_data_deliver_reply_unlocked (GTask *task,
1809 GDBusMessage *reply)
1811 SendMessageData *data = g_task_get_task_data (task);
1813 if (data->delivered)
1816 g_task_return_pointer (task, g_object_ref (reply), g_object_unref);
1818 send_message_with_reply_cleanup (task, TRUE);
1824 /* ---------------------------------------------------------------------------------------------------- */
1826 /* Called from a user thread, lock is not held */
1828 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1830 GTask *task = user_data;
1831 GDBusConnection *connection = g_task_get_source_object (task);
1832 SendMessageData *data = g_task_get_task_data (task);
1834 CONNECTION_LOCK (connection);
1835 if (data->delivered)
1838 g_task_return_new_error (task,
1840 G_IO_ERROR_CANCELLED,
1841 _("Operation was cancelled"));
1843 send_message_with_reply_cleanup (task, TRUE);
1846 CONNECTION_UNLOCK (connection);
1850 /* Can be called from any thread with or without lock held */
1852 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1855 GTask *task = user_data;
1856 GSource *idle_source;
1858 /* postpone cancellation to idle handler since we may be called directly
1859 * via g_cancellable_connect() (e.g. holding lock)
1861 idle_source = g_idle_source_new ();
1862 g_source_set_name (idle_source, "[gio] send_message_with_reply_cancelled_idle_cb");
1863 g_task_attach_source (task, idle_source, send_message_with_reply_cancelled_idle_cb);
1864 g_source_unref (idle_source);
1867 /* ---------------------------------------------------------------------------------------------------- */
1869 /* Called from a user thread, lock is not held */
1871 send_message_with_reply_timeout_cb (gpointer user_data)
1873 GTask *task = user_data;
1874 GDBusConnection *connection = g_task_get_source_object (task);
1875 SendMessageData *data = g_task_get_task_data (task);
1877 CONNECTION_LOCK (connection);
1878 if (data->delivered)
1881 g_task_return_new_error (task,
1883 G_IO_ERROR_TIMED_OUT,
1884 _("Timeout was reached"));
1886 send_message_with_reply_cleanup (task, TRUE);
1889 CONNECTION_UNLOCK (connection);
1894 /* ---------------------------------------------------------------------------------------------------- */
1896 /* Called from a user thread, connection's lock is held */
1898 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1899 GDBusMessage *message,
1900 GDBusSendMessageFlags flags,
1902 volatile guint32 *out_serial,
1903 GCancellable *cancellable,
1904 GAsyncReadyCallback callback,
1908 SendMessageData *data;
1909 GError *error = NULL;
1910 volatile guint32 serial;
1912 if (out_serial == NULL)
1913 out_serial = &serial;
1915 if (timeout_msec == -1)
1916 timeout_msec = 25 * 1000;
1918 data = g_slice_new0 (SendMessageData);
1919 task = g_task_new (connection, cancellable, callback, user_data);
1920 g_task_set_task_data (task, data, (GDestroyNotify) send_message_data_free);
1922 if (g_task_return_error_if_cancelled (task))
1924 g_object_unref (task);
1928 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1930 g_task_return_error (task, error);
1931 g_object_unref (task);
1934 data->serial = *out_serial;
1936 if (cancellable != NULL)
1938 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1939 G_CALLBACK (send_message_with_reply_cancelled_cb),
1940 g_object_ref (task),
1944 if (timeout_msec != G_MAXINT)
1946 data->timeout_source = g_timeout_source_new (timeout_msec);
1947 g_task_attach_source (task, data->timeout_source,
1948 (GSourceFunc) send_message_with_reply_timeout_cb);
1949 g_source_unref (data->timeout_source);
1952 g_hash_table_insert (connection->map_method_serial_to_task,
1953 GUINT_TO_POINTER (*out_serial),
1958 * g_dbus_connection_send_message_with_reply:
1959 * @connection: a #GDBusConnection
1960 * @message: a #GDBusMessage
1961 * @flags: flags affecting how the message is sent
1962 * @timeout_msec: the timeout in milliseconds, -1 to use the default
1963 * timeout or %G_MAXINT for no timeout
1964 * @out_serial: (out) (allow-none): return location for serial number assigned
1965 * to @message when sending it or %NULL
1966 * @cancellable: (allow-none): a #GCancellable or %NULL
1967 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request
1968 * is satisfied or %NULL if you don't care about the result
1969 * @user_data: The data to pass to @callback
1971 * Asynchronously sends @message to the peer represented by @connection.
1973 * Unless @flags contain the
1974 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1975 * will be assigned by @connection and set on @message via
1976 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1977 * serial number used will be written to this location prior to
1978 * submitting the message to the underlying transport.
1980 * If @connection is closed then the operation will fail with
1981 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1982 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1983 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1985 * This is an asynchronous method. When the operation is finished, @callback
1986 * will be invoked in the
1987 * [thread-default main context][g-main-context-push-thread-default]
1988 * of the thread you are calling this method from. You can then call
1989 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1990 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
1992 * Note that @message must be unlocked, unless @flags contain the
1993 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1995 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
1996 * for an example of how to use this low-level API to send and receive
1997 * UNIX file descriptors.
2002 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
2003 GDBusMessage *message,
2004 GDBusSendMessageFlags flags,
2006 volatile guint32 *out_serial,
2007 GCancellable *cancellable,
2008 GAsyncReadyCallback callback,
2011 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2012 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2013 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2014 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2016 CONNECTION_LOCK (connection);
2017 g_dbus_connection_send_message_with_reply_unlocked (connection,
2025 CONNECTION_UNLOCK (connection);
2029 * g_dbus_connection_send_message_with_reply_finish:
2030 * @connection: a #GDBusConnection
2031 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
2032 * g_dbus_connection_send_message_with_reply()
2033 * @error: teturn location for error or %NULL
2035 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2037 * Note that @error is only set if a local in-process error
2038 * occurred. That is to say that the returned #GDBusMessage object may
2039 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2040 * g_dbus_message_to_gerror() to transcode this to a #GError.
2042 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2043 * for an example of how to use this low-level API to send and receive
2044 * UNIX file descriptors.
2046 * Returns: (transfer full): a locked #GDBusMessage or %NULL if @error is set
2051 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2055 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2056 g_return_val_if_fail (g_task_is_valid (res, connection), NULL);
2057 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2059 return g_task_propagate_pointer (G_TASK (res), error);
2062 /* ---------------------------------------------------------------------------------------------------- */
2067 GMainContext *context;
2069 } SendMessageSyncData;
2071 /* Called from a user thread, lock is not held */
2073 send_message_with_reply_sync_cb (GDBusConnection *connection,
2077 SendMessageSyncData *data = user_data;
2078 data->res = g_object_ref (res);
2079 g_main_loop_quit (data->loop);
2083 * g_dbus_connection_send_message_with_reply_sync:
2084 * @connection: a #GDBusConnection
2085 * @message: a #GDBusMessage
2086 * @flags: flags affecting how the message is sent.
2087 * @timeout_msec: the timeout in milliseconds, -1 to use the default
2088 * timeout or %G_MAXINT for no timeout
2089 * @out_serial: (out) (allow-none): return location for serial number
2090 * assigned to @message when sending it or %NULL
2091 * @cancellable: (allow-none): a #GCancellable or %NULL
2092 * @error: return location for error or %NULL
2094 * Synchronously sends @message to the peer represented by @connection
2095 * and blocks the calling thread until a reply is received or the
2096 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2097 * for the asynchronous version of this method.
2099 * Unless @flags contain the
2100 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2101 * will be assigned by @connection and set on @message via
2102 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2103 * serial number used will be written to this location prior to
2104 * submitting the message to the underlying transport.
2106 * If @connection is closed then the operation will fail with
2107 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2108 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2109 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2111 * Note that @error is only set if a local in-process error
2112 * occurred. That is to say that the returned #GDBusMessage object may
2113 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2114 * g_dbus_message_to_gerror() to transcode this to a #GError.
2116 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2117 * for an example of how to use this low-level API to send and receive
2118 * UNIX file descriptors.
2120 * Note that @message must be unlocked, unless @flags contain the
2121 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2123 * Returns: (transfer full): a locked #GDBusMessage that is the reply
2124 * to @message or %NULL if @error is set
2129 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2130 GDBusMessage *message,
2131 GDBusSendMessageFlags flags,
2133 volatile guint32 *out_serial,
2134 GCancellable *cancellable,
2137 SendMessageSyncData data;
2138 GDBusMessage *reply;
2140 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2141 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2142 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2143 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2144 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2147 data.context = g_main_context_new ();
2148 data.loop = g_main_loop_new (data.context, FALSE);
2150 g_main_context_push_thread_default (data.context);
2152 g_dbus_connection_send_message_with_reply (connection,
2158 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2160 g_main_loop_run (data.loop);
2161 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2165 g_main_context_pop_thread_default (data.context);
2167 g_main_context_unref (data.context);
2168 g_main_loop_unref (data.loop);
2170 g_object_unref (data.res);
2175 /* ---------------------------------------------------------------------------------------------------- */
2179 GDBusMessageFilterFunction func;
2186 GDBusMessageFilterFunction filter_function;
2188 GDestroyNotify user_data_free_func;
2191 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2193 on_worker_message_received (GDBusWorker *worker,
2194 GDBusMessage *message,
2197 GDBusConnection *connection;
2198 FilterCallback *filters;
2203 G_LOCK (message_bus_lock);
2204 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2207 G_UNLOCK (message_bus_lock);
2210 connection = G_DBUS_CONNECTION (user_data);
2211 g_object_ref (connection);
2212 G_UNLOCK (message_bus_lock);
2214 //g_debug ("in on_worker_message_received");
2216 g_object_ref (message);
2217 g_dbus_message_lock (message);
2219 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2221 /* First collect the set of callback functions */
2222 CONNECTION_LOCK (connection);
2223 num_filters = connection->filters->len;
2224 filters = g_new0 (FilterCallback, num_filters);
2225 for (n = 0; n < num_filters; n++)
2227 FilterData *data = connection->filters->pdata[n];
2228 filters[n].func = data->filter_function;
2229 filters[n].user_data = data->user_data;
2231 CONNECTION_UNLOCK (connection);
2233 /* then call the filters in order (without holding the lock) */
2234 for (n = 0; n < num_filters; n++)
2236 message = filters[n].func (connection,
2239 filters[n].user_data);
2240 if (message == NULL)
2242 g_dbus_message_lock (message);
2245 /* Standard dispatch unless the filter ate the message - no need to
2246 * do anything if the message was altered
2248 if (message != NULL)
2250 GDBusMessageType message_type;
2252 message_type = g_dbus_message_get_message_type (message);
2253 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2255 guint32 reply_serial;
2258 reply_serial = g_dbus_message_get_reply_serial (message);
2259 CONNECTION_LOCK (connection);
2260 task = g_hash_table_lookup (connection->map_method_serial_to_task,
2261 GUINT_TO_POINTER (reply_serial));
2264 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2265 send_message_data_deliver_reply_unlocked (task, message);
2269 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2271 CONNECTION_UNLOCK (connection);
2273 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2275 CONNECTION_LOCK (connection);
2276 distribute_signals (connection, message);
2277 CONNECTION_UNLOCK (connection);
2279 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2281 CONNECTION_LOCK (connection);
2282 distribute_method_call (connection, message);
2283 CONNECTION_UNLOCK (connection);
2287 if (message != NULL)
2288 g_object_unref (message);
2289 g_object_unref (connection);
2293 /* Called in GDBusWorker's thread, lock is not held */
2294 static GDBusMessage *
2295 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2296 GDBusMessage *message,
2299 GDBusConnection *connection;
2300 FilterCallback *filters;
2305 G_LOCK (message_bus_lock);
2306 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2309 G_UNLOCK (message_bus_lock);
2312 connection = G_DBUS_CONNECTION (user_data);
2313 g_object_ref (connection);
2314 G_UNLOCK (message_bus_lock);
2316 //g_debug ("in on_worker_message_about_to_be_sent");
2318 /* First collect the set of callback functions */
2319 CONNECTION_LOCK (connection);
2320 num_filters = connection->filters->len;
2321 filters = g_new0 (FilterCallback, num_filters);
2322 for (n = 0; n < num_filters; n++)
2324 FilterData *data = connection->filters->pdata[n];
2325 filters[n].func = data->filter_function;
2326 filters[n].user_data = data->user_data;
2328 CONNECTION_UNLOCK (connection);
2330 /* then call the filters in order (without holding the lock) */
2331 for (n = 0; n < num_filters; n++)
2333 g_dbus_message_lock (message);
2334 message = filters[n].func (connection,
2337 filters[n].user_data);
2338 if (message == NULL)
2342 g_object_unref (connection);
2348 /* called with connection lock held, in GDBusWorker thread */
2350 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2352 GTask *task = value;
2353 SendMessageData *data = g_task_get_task_data (task);
2355 if (data->delivered)
2358 g_task_return_new_error (task,
2361 _("The connection is closed"));
2363 /* Ask send_message_with_reply_cleanup not to remove the element from the
2364 * hash table - we're in the middle of a foreach; that would be unsafe.
2365 * Instead, return TRUE from this function so that it gets removed safely.
2367 send_message_with_reply_cleanup (task, FALSE);
2371 /* Called in GDBusWorker's thread - we must not block - without lock held */
2373 on_worker_closed (GDBusWorker *worker,
2374 gboolean remote_peer_vanished,
2378 GDBusConnection *connection;
2380 guint old_atomic_flags;
2382 G_LOCK (message_bus_lock);
2383 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2386 G_UNLOCK (message_bus_lock);
2389 connection = G_DBUS_CONNECTION (user_data);
2390 g_object_ref (connection);
2391 G_UNLOCK (message_bus_lock);
2393 //g_debug ("in on_worker_closed: %s", error->message);
2395 CONNECTION_LOCK (connection);
2396 /* Even though this is atomic, we do it inside the lock to avoid breaking
2397 * assumptions in remove_match_rule(). We'd need the lock in a moment
2398 * anyway, so, no loss.
2400 old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
2402 if (!(old_atomic_flags & FLAG_CLOSED))
2404 g_hash_table_foreach_remove (connection->map_method_serial_to_task, cancel_method_on_close, NULL);
2405 schedule_closed_unlocked (connection, remote_peer_vanished, error);
2407 CONNECTION_UNLOCK (connection);
2409 g_object_unref (connection);
2412 /* ---------------------------------------------------------------------------------------------------- */
2414 /* Determines the biggest set of capabilities we can support on this
2417 * Called with the init_lock held.
2419 static GDBusCapabilityFlags
2420 get_offered_capabilities_max (GDBusConnection *connection)
2422 GDBusCapabilityFlags ret;
2423 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2425 if (G_IS_UNIX_CONNECTION (connection->stream))
2426 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2431 /* Called in a user thread, lock is not held */
2433 initable_init (GInitable *initable,
2434 GCancellable *cancellable,
2437 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2440 /* This method needs to be idempotent to work with the singleton
2441 * pattern. See the docs for g_initable_init(). We implement this by
2444 * Unfortunately we can't use the main lock since the on_worker_*()
2445 * callbacks above needs the lock during initialization (for message
2446 * bus connections we do a synchronous Hello() call on the bus).
2448 g_mutex_lock (&connection->init_lock);
2452 /* Make this a no-op if we're already initialized (successfully or
2455 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
2457 ret = (connection->initialization_error == NULL);
2461 /* Because of init_lock, we can't get here twice in different threads */
2462 g_assert (connection->initialization_error == NULL);
2464 /* The user can pass multiple (but mutally exclusive) construct
2467 * - stream (of type GIOStream)
2468 * - address (of type gchar*)
2470 * At the end of the day we end up with a non-NULL GIOStream
2471 * object in connection->stream.
2473 if (connection->address != NULL)
2475 g_assert (connection->stream == NULL);
2477 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2478 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2480 g_set_error_literal (&connection->initialization_error,
2482 G_IO_ERROR_INVALID_ARGUMENT,
2483 _("Unsupported flags encountered when constructing a client-side connection"));
2487 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2488 NULL, /* TODO: out_guid */
2490 &connection->initialization_error);
2491 if (connection->stream == NULL)
2494 else if (connection->stream != NULL)
2500 g_assert_not_reached ();
2503 /* Authenticate the connection */
2504 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2506 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2507 g_assert (connection->guid != NULL);
2508 connection->auth = _g_dbus_auth_new (connection->stream);
2509 if (!_g_dbus_auth_run_server (connection->auth,
2510 connection->authentication_observer,
2512 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2513 get_offered_capabilities_max (connection),
2514 &connection->capabilities,
2515 &connection->credentials,
2517 &connection->initialization_error))
2520 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2522 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2523 g_assert (connection->guid == NULL);
2524 connection->auth = _g_dbus_auth_new (connection->stream);
2525 connection->guid = _g_dbus_auth_run_client (connection->auth,
2526 connection->authentication_observer,
2527 get_offered_capabilities_max (connection),
2528 &connection->capabilities,
2530 &connection->initialization_error);
2531 if (connection->guid == NULL)
2535 if (connection->authentication_observer != NULL)
2537 g_object_unref (connection->authentication_observer);
2538 connection->authentication_observer = NULL;
2541 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2543 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2546 /* We want all IO operations to be non-blocking since they happen in
2547 * the worker thread which is shared by _all_ connections.
2549 if (G_IS_SOCKET_CONNECTION (connection->stream))
2551 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2555 G_LOCK (message_bus_lock);
2556 if (alive_connections == NULL)
2557 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2558 g_hash_table_insert (alive_connections, connection, connection);
2559 G_UNLOCK (message_bus_lock);
2561 connection->worker = _g_dbus_worker_new (connection->stream,
2562 connection->capabilities,
2563 ((connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) != 0),
2564 on_worker_message_received,
2565 on_worker_message_about_to_be_sent,
2569 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2570 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2572 GVariant *hello_result;
2574 /* we could lift this restriction by adding code in gdbusprivate.c */
2575 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2577 g_set_error_literal (&connection->initialization_error,
2580 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2584 hello_result = g_dbus_connection_call_sync (connection,
2585 "org.freedesktop.DBus", /* name */
2586 "/org/freedesktop/DBus", /* path */
2587 "org.freedesktop.DBus", /* interface */
2589 NULL, /* parameters */
2590 G_VARIANT_TYPE ("(s)"),
2591 CALL_FLAGS_INITIALIZING,
2593 NULL, /* TODO: cancellable */
2594 &connection->initialization_error);
2595 if (hello_result == NULL)
2598 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2599 g_variant_unref (hello_result);
2600 //g_debug ("unique name is '%s'", connection->bus_unique_name);
2607 g_assert (connection->initialization_error != NULL);
2608 g_propagate_error (error, g_error_copy (connection->initialization_error));
2611 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
2612 g_mutex_unlock (&connection->init_lock);
2618 initable_iface_init (GInitableIface *initable_iface)
2620 initable_iface->init = initable_init;
2623 /* ---------------------------------------------------------------------------------------------------- */
2626 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2631 /* ---------------------------------------------------------------------------------------------------- */
2634 * g_dbus_connection_new:
2635 * @stream: a #GIOStream
2636 * @guid: (allow-none): the GUID to use if a authenticating as a server or %NULL
2637 * @flags: flags describing how to make the connection
2638 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
2639 * @cancellable: (allow-none): a #GCancellable or %NULL
2640 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
2641 * @user_data: the data to pass to @callback
2643 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2644 * with the end represented by @stream.
2646 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2647 * will be put into non-blocking mode.
2649 * The D-Bus connection will interact with @stream from a worker thread.
2650 * As a result, the caller should not interact with @stream after this
2651 * method has been called, except by calling g_object_unref() on it.
2653 * If @observer is not %NULL it may be used to control the
2654 * authentication process.
2656 * When the operation is finished, @callback will be invoked. You can
2657 * then call g_dbus_connection_new_finish() to get the result of the
2660 * This is a asynchronous failable constructor. See
2661 * g_dbus_connection_new_sync() for the synchronous
2667 g_dbus_connection_new (GIOStream *stream,
2669 GDBusConnectionFlags flags,
2670 GDBusAuthObserver *observer,
2671 GCancellable *cancellable,
2672 GAsyncReadyCallback callback,
2675 g_return_if_fail (G_IS_IO_STREAM (stream));
2676 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2684 "authentication-observer", observer,
2689 * g_dbus_connection_new_finish:
2690 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback
2691 * passed to g_dbus_connection_new().
2692 * @error: return location for error or %NULL
2694 * Finishes an operation started with g_dbus_connection_new().
2696 * Returns: a #GDBusConnection or %NULL if @error is set. Free
2697 * with g_object_unref().
2702 g_dbus_connection_new_finish (GAsyncResult *res,
2706 GObject *source_object;
2708 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2709 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2711 source_object = g_async_result_get_source_object (res);
2712 g_assert (source_object != NULL);
2713 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2716 g_object_unref (source_object);
2718 return G_DBUS_CONNECTION (object);
2724 * g_dbus_connection_new_sync:
2725 * @stream: a #GIOStream
2726 * @guid: (allow-none): the GUID to use if a authenticating as a server or %NULL
2727 * @flags: flags describing how to make the connection
2728 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
2729 * @cancellable: (allow-none): a #GCancellable or %NULL
2730 * @error: return location for error or %NULL
2732 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2733 * with the end represented by @stream.
2735 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2736 * will be put into non-blocking mode.
2738 * The D-Bus connection will interact with @stream from a worker thread.
2739 * As a result, the caller should not interact with @stream after this
2740 * method has been called, except by calling g_object_unref() on it.
2742 * If @observer is not %NULL it may be used to control the
2743 * authentication process.
2745 * This is a synchronous failable constructor. See
2746 * g_dbus_connection_new() for the asynchronous version.
2748 * Returns: a #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2753 g_dbus_connection_new_sync (GIOStream *stream,
2755 GDBusConnectionFlags flags,
2756 GDBusAuthObserver *observer,
2757 GCancellable *cancellable,
2760 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2761 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2762 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2768 "authentication-observer", observer,
2772 /* ---------------------------------------------------------------------------------------------------- */
2775 * g_dbus_connection_new_for_address:
2776 * @address: a D-Bus address
2777 * @flags: flags describing how to make the connection
2778 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
2779 * @cancellable: (allow-none): a #GCancellable or %NULL
2780 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
2781 * @user_data: the data to pass to @callback
2783 * Asynchronously connects and sets up a D-Bus client connection for
2784 * exchanging D-Bus messages with an endpoint specified by @address
2785 * which must be in the D-Bus address format.
2787 * This constructor can only be used to initiate client-side
2788 * connections - use g_dbus_connection_new() if you need to act as the
2789 * server. In particular, @flags cannot contain the
2790 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2791 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2793 * When the operation is finished, @callback will be invoked. You can
2794 * then call g_dbus_connection_new_finish() to get the result of the
2797 * If @observer is not %NULL it may be used to control the
2798 * authentication process.
2800 * This is a asynchronous failable constructor. See
2801 * g_dbus_connection_new_for_address_sync() for the synchronous
2807 g_dbus_connection_new_for_address (const gchar *address,
2808 GDBusConnectionFlags flags,
2809 GDBusAuthObserver *observer,
2810 GCancellable *cancellable,
2811 GAsyncReadyCallback callback,
2814 g_return_if_fail (address != NULL);
2815 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2822 "authentication-observer", observer,
2827 * g_dbus_connection_new_for_address_finish:
2828 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
2829 * to g_dbus_connection_new()
2830 * @error: return location for error or %NULL
2832 * Finishes an operation started with g_dbus_connection_new_for_address().
2834 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
2840 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2844 GObject *source_object;
2846 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2847 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2849 source_object = g_async_result_get_source_object (res);
2850 g_assert (source_object != NULL);
2851 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2854 g_object_unref (source_object);
2856 return G_DBUS_CONNECTION (object);
2862 * g_dbus_connection_new_for_address_sync:
2863 * @address: a D-Bus address
2864 * @flags: flags describing how to make the connection
2865 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
2866 * @cancellable: (allow-none): a #GCancellable or %NULL
2867 * @error: return location for error or %NULL
2869 * Synchronously connects and sets up a D-Bus client connection for
2870 * exchanging D-Bus messages with an endpoint specified by @address
2871 * which must be in the D-Bus address format.
2873 * This constructor can only be used to initiate client-side
2874 * connections - use g_dbus_connection_new_sync() if you need to act
2875 * as the server. In particular, @flags cannot contain the
2876 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2877 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2879 * This is a synchronous failable constructor. See
2880 * g_dbus_connection_new_for_address() for the asynchronous version.
2882 * If @observer is not %NULL it may be used to control the
2883 * authentication process.
2885 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
2891 g_dbus_connection_new_for_address_sync (const gchar *address,
2892 GDBusConnectionFlags flags,
2893 GDBusAuthObserver *observer,
2894 GCancellable *cancellable,
2897 g_return_val_if_fail (address != NULL, NULL);
2898 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2899 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2904 "authentication-observer", observer,
2908 /* ---------------------------------------------------------------------------------------------------- */
2911 * g_dbus_connection_set_exit_on_close:
2912 * @connection: a #GDBusConnection
2913 * @exit_on_close: whether the process should be terminated
2914 * when @connection is closed by the remote peer
2916 * Sets whether the process should be terminated when @connection is
2917 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2920 * Note that this function should be used with care. Most modern UNIX
2921 * desktops tie the notion of a user session the session bus, and expect
2922 * all of a users applications to quit when their bus connection goes away.
2923 * If you are setting @exit_on_close to %FALSE for the shared session
2924 * bus connection, you should make sure that your application exits
2925 * when the user session ends.
2930 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2931 gboolean exit_on_close)
2933 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2936 g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
2938 g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
2943 * g_dbus_connection_get_exit_on_close:
2944 * @connection: a #GDBusConnection
2946 * Gets whether the process is terminated when @connection is
2947 * closed by the remote peer. See
2948 * #GDBusConnection:exit-on-close for more details.
2950 * Returns: whether the process is terminated when @connection is
2951 * closed by the remote peer
2956 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2958 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2960 if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
2967 * g_dbus_connection_get_guid:
2968 * @connection: a #GDBusConnection
2970 * The GUID of the peer performing the role of server when
2971 * authenticating. See #GDBusConnection:guid for more details.
2973 * Returns: The GUID. Do not free this string, it is owned by
2979 g_dbus_connection_get_guid (GDBusConnection *connection)
2981 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2982 return connection->guid;
2986 * g_dbus_connection_get_unique_name:
2987 * @connection: a #GDBusConnection
2989 * Gets the unique name of @connection as assigned by the message
2990 * bus. This can also be used to figure out if @connection is a
2991 * message bus connection.
2993 * Returns: the unique name or %NULL if @connection is not a message
2994 * bus connection. Do not free this string, it is owned by
3000 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3002 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3004 /* do not use g_return_val_if_fail(), we want the memory barrier */
3005 if (!check_initialized (connection))
3008 return connection->bus_unique_name;
3012 * g_dbus_connection_get_peer_credentials:
3013 * @connection: a #GDBusConnection
3015 * Gets the credentials of the authenticated peer. This will always
3016 * return %NULL unless @connection acted as a server
3017 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3018 * when set up and the client passed credentials as part of the
3019 * authentication process.
3021 * In a message bus setup, the message bus is always the server and
3022 * each application is a client. So this method will always return
3023 * %NULL for message bus clients.
3025 * Returns: (transfer none): a #GCredentials or %NULL if not available.
3026 * Do not free this object, it is owned by @connection.
3031 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3033 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3035 /* do not use g_return_val_if_fail(), we want the memory barrier */
3036 if (!check_initialized (connection))
3039 return connection->credentials;
3042 /* ---------------------------------------------------------------------------------------------------- */
3044 static guint _global_filter_id = 1;
3047 * g_dbus_connection_add_filter:
3048 * @connection: a #GDBusConnection
3049 * @filter_function: a filter function
3050 * @user_data: user data to pass to @filter_function
3051 * @user_data_free_func: function to free @user_data with when filter
3052 * is removed or %NULL
3054 * Adds a message filter. Filters are handlers that are run on all
3055 * incoming and outgoing messages, prior to standard dispatch. Filters
3056 * are run in the order that they were added. The same handler can be
3057 * added as a filter more than once, in which case it will be run more
3058 * than once. Filters added during a filter callback won't be run on
3059 * the message being processed. Filter functions are allowed to modify
3060 * and even drop messages.
3062 * Note that filters are run in a dedicated message handling thread so
3063 * they can't block and, generally, can't do anything but signal a
3064 * worker thread. Also note that filters are rarely needed - use API
3065 * such as g_dbus_connection_send_message_with_reply(),
3066 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3068 * If a filter consumes an incoming message the message is not
3069 * dispatched anywhere else - not even the standard dispatch machinery
3070 * (that API such as g_dbus_connection_signal_subscribe() and
3071 * g_dbus_connection_send_message_with_reply() relies on) will see the
3072 * message. Similary, if a filter consumes an outgoing message, the
3073 * message will not be sent to the other peer.
3075 * Returns: a filter identifier that can be used with
3076 * g_dbus_connection_remove_filter()
3081 g_dbus_connection_add_filter (GDBusConnection *connection,
3082 GDBusMessageFilterFunction filter_function,
3084 GDestroyNotify user_data_free_func)
3088 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3089 g_return_val_if_fail (filter_function != NULL, 0);
3090 g_return_val_if_fail (check_initialized (connection), 0);
3092 CONNECTION_LOCK (connection);
3093 data = g_new0 (FilterData, 1);
3094 data->id = _global_filter_id++; /* TODO: overflow etc. */
3095 data->filter_function = filter_function;
3096 data->user_data = user_data;
3097 data->user_data_free_func = user_data_free_func;
3098 g_ptr_array_add (connection->filters, data);
3099 CONNECTION_UNLOCK (connection);
3104 /* only called from finalize(), removes all filters */
3106 purge_all_filters (GDBusConnection *connection)
3109 for (n = 0; n < connection->filters->len; n++)
3111 FilterData *data = connection->filters->pdata[n];
3112 if (data->user_data_free_func != NULL)
3113 data->user_data_free_func (data->user_data);
3119 * g_dbus_connection_remove_filter:
3120 * @connection: a #GDBusConnection
3121 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3128 g_dbus_connection_remove_filter (GDBusConnection *connection,
3132 FilterData *to_destroy;
3134 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3135 g_return_if_fail (check_initialized (connection));
3137 CONNECTION_LOCK (connection);
3139 for (n = 0; n < connection->filters->len; n++)
3141 FilterData *data = connection->filters->pdata[n];
3142 if (data->id == filter_id)
3144 g_ptr_array_remove_index (connection->filters, n);
3149 CONNECTION_UNLOCK (connection);
3151 /* do free without holding lock */
3152 if (to_destroy != NULL)
3154 if (to_destroy->user_data_free_func != NULL)
3155 to_destroy->user_data_free_func (to_destroy->user_data);
3156 g_free (to_destroy);
3160 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3164 /* ---------------------------------------------------------------------------------------------------- */
3170 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3171 gchar *interface_name;
3175 GDBusSignalFlags flags;
3176 GArray *subscribers;
3181 GDBusSignalCallback callback;
3183 GDestroyNotify user_data_free_func;
3185 GMainContext *context;
3189 signal_data_free (SignalData *signal_data)
3191 g_free (signal_data->rule);
3192 g_free (signal_data->sender);
3193 g_free (signal_data->sender_unique_name);
3194 g_free (signal_data->interface_name);
3195 g_free (signal_data->member);
3196 g_free (signal_data->object_path);
3197 g_free (signal_data->arg0);
3198 g_array_free (signal_data->subscribers, TRUE);
3199 g_free (signal_data);
3203 args_to_rule (const gchar *sender,
3204 const gchar *interface_name,
3205 const gchar *member,
3206 const gchar *object_path,
3208 GDBusSignalFlags flags)
3212 rule = g_string_new ("type='signal'");
3213 if (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE)
3214 g_string_prepend_c (rule, '-');
3216 g_string_append_printf (rule, ",sender='%s'", sender);
3217 if (interface_name != NULL)
3218 g_string_append_printf (rule, ",interface='%s'", interface_name);
3220 g_string_append_printf (rule, ",member='%s'", member);
3221 if (object_path != NULL)
3222 g_string_append_printf (rule, ",path='%s'", object_path);
3226 if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3227 g_string_append_printf (rule, ",arg0path='%s'", arg0);
3228 else if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3229 g_string_append_printf (rule, ",arg0namespace='%s'", arg0);
3231 g_string_append_printf (rule, ",arg0='%s'", arg0);
3234 return g_string_free (rule, FALSE);
3237 static guint _global_subscriber_id = 1;
3238 static guint _global_registration_id = 1;
3239 static guint _global_subtree_registration_id = 1;
3241 /* ---------------------------------------------------------------------------------------------------- */
3243 /* Called in a user thread, lock is held */
3245 add_match_rule (GDBusConnection *connection,
3246 const gchar *match_rule)
3249 GDBusMessage *message;
3251 if (match_rule[0] == '-')
3254 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3255 "/org/freedesktop/DBus", /* path */
3256 "org.freedesktop.DBus", /* interface */
3258 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3260 if (!g_dbus_connection_send_message_unlocked (connection,
3262 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3266 g_critical ("Error while sending AddMatch() message: %s", error->message);
3267 g_error_free (error);
3269 g_object_unref (message);
3272 /* ---------------------------------------------------------------------------------------------------- */
3274 /* Called in a user thread, lock is held */
3276 remove_match_rule (GDBusConnection *connection,
3277 const gchar *match_rule)
3280 GDBusMessage *message;
3282 if (match_rule[0] == '-')
3285 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3286 "/org/freedesktop/DBus", /* path */
3287 "org.freedesktop.DBus", /* interface */
3289 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3292 if (!g_dbus_connection_send_message_unlocked (connection,
3294 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3298 /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
3299 * critical; but we're holding the lock, and our caller checked whether
3300 * we were already closed, so we can't get that error.
3302 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3303 g_error_free (error);
3305 g_object_unref (message);
3308 /* ---------------------------------------------------------------------------------------------------- */
3311 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3313 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3314 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3315 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3316 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3317 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3320 /* ---------------------------------------------------------------------------------------------------- */
3323 * g_dbus_connection_signal_subscribe:
3324 * @connection: a #GDBusConnection
3325 * @sender: (allow-none): sender name to match on (unique or well-known name)
3326 * or %NULL to listen from all senders
3327 * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3328 * match on all interfaces
3329 * @member: (allow-none): D-Bus signal name to match on or %NULL to match on
3331 * @object_path: (allow-none): object path to match on or %NULL to match on
3333 * @arg0: (allow-none): contents of first string argument to match on or %NULL
3334 * to match on all kinds of arguments
3335 * @flags: flags describing how to subscribe to the signal (currently unused)
3336 * @callback: callback to invoke when there is a signal matching the requested data
3337 * @user_data: user data to pass to @callback
3338 * @user_data_free_func: (allow-none): function to free @user_data with when
3339 * subscription is removed or %NULL
3341 * Subscribes to signals on @connection and invokes @callback with a whenever
3342 * the signal is received. Note that @callback will be invoked in the
3343 * [thread-default main context][g-main-context-push-thread-default]
3344 * of the thread you are calling this method from.
3346 * If @connection is not a message bus connection, @sender must be
3349 * If @sender is a well-known name note that @callback is invoked with
3350 * the unique name for the owner of @sender, not the well-known name
3351 * as one would expect. This is because the message bus rewrites the
3352 * name. As such, to avoid certain race conditions, users should be
3353 * tracking the name owner of the well-known name and use that when
3354 * processing the received signal.
3356 * If one of %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE or
3357 * %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH are given, @arg0 is
3358 * interpreted as part of a namespace or path. The first argument
3359 * of a signal is matched against that part as specified by D-Bus.
3361 * Returns: a subscription identifier that can be used with g_dbus_connection_signal_unsubscribe()
3366 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3367 const gchar *sender,
3368 const gchar *interface_name,
3369 const gchar *member,
3370 const gchar *object_path,
3372 GDBusSignalFlags flags,
3373 GDBusSignalCallback callback,
3375 GDestroyNotify user_data_free_func)
3378 SignalData *signal_data;
3379 SignalSubscriber subscriber;
3380 GPtrArray *signal_data_array;
3381 const gchar *sender_unique_name;
3383 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3384 * an OOM condition. We might want to change that but that would involve making
3385 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3386 * handle that. And there's really no sensible way of handling this short of retrying
3387 * to add the match rule... and then there's the little thing that, hey, maybe there's
3388 * a reason the bus in an OOM condition.
3390 * Doable, but not really sure it's worth it...
3393 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3394 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3395 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3396 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3397 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3398 g_return_val_if_fail (callback != NULL, 0);
3399 g_return_val_if_fail (check_initialized (connection), 0);
3400 g_return_val_if_fail (!((flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH) && (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)), 0);
3401 g_return_val_if_fail (!(arg0 == NULL && (flags & (G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH | G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE))), 0);
3403 CONNECTION_LOCK (connection);
3405 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3406 * with a '-' character to prefix the rule (which will otherwise be
3409 * This allows us to hash the rule and do our lifecycle tracking in
3410 * the usual way, but the '-' prevents the match rule from ever
3411 * actually being send to the bus (either for add or remove).
3413 rule = args_to_rule (sender, interface_name, member, object_path, arg0, flags);
3415 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3416 sender_unique_name = sender;
3418 sender_unique_name = "";
3420 subscriber.callback = callback;
3421 subscriber.user_data = user_data;
3422 subscriber.user_data_free_func = user_data_free_func;
3423 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3424 subscriber.context = g_main_context_ref_thread_default ();
3426 /* see if we've already have this rule */
3427 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3428 if (signal_data != NULL)
3430 g_array_append_val (signal_data->subscribers, subscriber);
3435 signal_data = g_new0 (SignalData, 1);
3436 signal_data->rule = rule;
3437 signal_data->sender = g_strdup (sender);
3438 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3439 signal_data->interface_name = g_strdup (interface_name);
3440 signal_data->member = g_strdup (member);
3441 signal_data->object_path = g_strdup (object_path);
3442 signal_data->arg0 = g_strdup (arg0);
3443 signal_data->flags = flags;
3444 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3445 g_array_append_val (signal_data->subscribers, subscriber);
3447 g_hash_table_insert (connection->map_rule_to_signal_data,
3451 /* Add the match rule to the bus...
3453 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3454 * always send such messages to us.
3456 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3458 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3459 add_match_rule (connection, signal_data->rule);
3462 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3463 signal_data->sender_unique_name);
3464 if (signal_data_array == NULL)
3466 signal_data_array = g_ptr_array_new ();
3467 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3468 g_strdup (signal_data->sender_unique_name),
3471 g_ptr_array_add (signal_data_array, signal_data);
3474 g_hash_table_insert (connection->map_id_to_signal_data,
3475 GUINT_TO_POINTER (subscriber.id),
3478 CONNECTION_UNLOCK (connection);
3480 return subscriber.id;
3483 /* ---------------------------------------------------------------------------------------------------- */
3485 /* called in any thread */
3486 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3488 unsubscribe_id_internal (GDBusConnection *connection,
3489 guint subscription_id,
3490 GArray *out_removed_subscribers)
3492 SignalData *signal_data;
3493 GPtrArray *signal_data_array;
3496 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3497 GUINT_TO_POINTER (subscription_id));
3498 if (signal_data == NULL)
3500 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3504 for (n = 0; n < signal_data->subscribers->len; n++)
3506 SignalSubscriber *subscriber;
3508 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3509 if (subscriber->id != subscription_id)
3512 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3513 GUINT_TO_POINTER (subscription_id)));
3514 g_array_append_val (out_removed_subscribers, *subscriber);
3515 g_array_remove_index (signal_data->subscribers, n);
3517 if (signal_data->subscribers->len == 0)
3519 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3521 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3522 signal_data->sender_unique_name);
3523 g_warn_if_fail (signal_data_array != NULL);
3524 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3526 if (signal_data_array->len == 0)
3528 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3529 signal_data->sender_unique_name));
3532 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3533 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
3534 !is_signal_data_for_name_lost_or_acquired (signal_data) &&
3535 !g_dbus_connection_is_closed (connection) &&
3536 !connection->finalizing)
3538 /* The check for g_dbus_connection_is_closed() means that
3539 * sending the RemoveMatch message can't fail with
3540 * G_IO_ERROR_CLOSED, because we're holding the lock,
3541 * so on_worker_closed() can't happen between the check we just
3542 * did, and releasing the lock later.
3544 remove_match_rule (connection, signal_data->rule);
3547 signal_data_free (signal_data);
3553 g_assert_not_reached ();
3560 * g_dbus_connection_signal_unsubscribe:
3561 * @connection: a #GDBusConnection
3562 * @subscription_id: a subscription id obtained from
3563 * g_dbus_connection_signal_subscribe()
3565 * Unsubscribes from signals.
3570 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3571 guint subscription_id)
3573 GArray *subscribers;
3576 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3577 g_return_if_fail (check_initialized (connection));
3579 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3581 CONNECTION_LOCK (connection);
3582 unsubscribe_id_internal (connection,
3585 CONNECTION_UNLOCK (connection);
3588 g_assert (subscribers->len == 0 || subscribers->len == 1);
3590 /* call GDestroyNotify without lock held */
3591 for (n = 0; n < subscribers->len; n++)
3593 SignalSubscriber *subscriber;
3594 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3595 call_destroy_notify (subscriber->context,
3596 subscriber->user_data_free_func,
3597 subscriber->user_data);
3598 g_main_context_unref (subscriber->context);
3601 g_array_free (subscribers, TRUE);
3604 /* ---------------------------------------------------------------------------------------------------- */
3608 guint subscription_id;
3609 GDBusSignalCallback callback;
3611 GDBusMessage *message;
3612 GDBusConnection *connection;
3613 const gchar *sender;
3615 const gchar *interface;
3616 const gchar *member;
3619 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3623 emit_signal_instance_in_idle_cb (gpointer data)
3625 SignalInstance *signal_instance = data;
3626 GVariant *parameters;
3627 gboolean has_subscription;
3629 parameters = g_dbus_message_get_body (signal_instance->message);
3630 if (parameters == NULL)
3632 parameters = g_variant_new ("()");
3633 g_variant_ref_sink (parameters);
3637 g_variant_ref_sink (parameters);
3641 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3642 signal_instance->subscription_id,
3643 signal_instance->sender,
3644 signal_instance->path,
3645 signal_instance->interface,
3646 signal_instance->member,
3647 g_variant_print (parameters, TRUE));
3650 /* Careful here, don't do the callback if we no longer has the subscription */
3651 CONNECTION_LOCK (signal_instance->connection);
3652 has_subscription = FALSE;
3653 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3654 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3655 has_subscription = TRUE;
3656 CONNECTION_UNLOCK (signal_instance->connection);
3658 if (has_subscription)
3659 signal_instance->callback (signal_instance->connection,
3660 signal_instance->sender,
3661 signal_instance->path,
3662 signal_instance->interface,
3663 signal_instance->member,
3665 signal_instance->user_data);
3667 g_variant_unref (parameters);
3673 signal_instance_free (SignalInstance *signal_instance)
3675 g_object_unref (signal_instance->message);
3676 g_object_unref (signal_instance->connection);
3677 g_free (signal_instance);
3681 namespace_rule_matches (const gchar *namespace,
3687 len_namespace = strlen (namespace);
3688 len_name = strlen (name);
3690 if (len_name < len_namespace)
3693 if (memcmp (namespace, name, len_namespace) != 0)
3696 return len_namespace == len_name || name[len_namespace] == '.';
3700 path_rule_matches (const gchar *path_a,
3701 const gchar *path_b)
3705 len_a = strlen (path_a);
3706 len_b = strlen (path_b);
3708 if (len_a < len_b && path_a[len_a - 1] != '/')
3711 if (len_b < len_a && path_b[len_b - 1] != '/')
3714 return memcmp (path_a, path_b, MIN (len_a, len_b)) == 0;
3717 /* called in GDBusWorker thread WITH lock held */
3719 schedule_callbacks (GDBusConnection *connection,
3720 GPtrArray *signal_data_array,
3721 GDBusMessage *message,
3722 const gchar *sender)
3725 const gchar *interface;
3726 const gchar *member;
3735 interface = g_dbus_message_get_interface (message);
3736 member = g_dbus_message_get_member (message);
3737 path = g_dbus_message_get_path (message);
3738 arg0 = g_dbus_message_get_arg0 (message);
3741 g_print ("In schedule_callbacks:\n"
3743 " interface = '%s'\n"
3754 /* TODO: if this is slow, then we can change signal_data_array into
3755 * map_object_path_to_signal_data_array or something.
3757 for (n = 0; n < signal_data_array->len; n++)
3759 SignalData *signal_data = signal_data_array->pdata[n];
3761 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3764 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3767 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3770 if (signal_data->arg0 != NULL)
3775 if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3777 if (!namespace_rule_matches (signal_data->arg0, arg0))
3780 else if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3782 if (!path_rule_matches (signal_data->arg0, arg0))
3785 else if (!g_str_equal (signal_data->arg0, arg0))
3789 for (m = 0; m < signal_data->subscribers->len; m++)
3791 SignalSubscriber *subscriber;
3792 GSource *idle_source;
3793 SignalInstance *signal_instance;
3795 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3797 signal_instance = g_new0 (SignalInstance, 1);
3798 signal_instance->subscription_id = subscriber->id;
3799 signal_instance->callback = subscriber->callback;
3800 signal_instance->user_data = subscriber->user_data;
3801 signal_instance->message = g_object_ref (message);
3802 signal_instance->connection = g_object_ref (connection);
3803 signal_instance->sender = sender;
3804 signal_instance->path = path;
3805 signal_instance->interface = interface;
3806 signal_instance->member = member;
3808 idle_source = g_idle_source_new ();
3809 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3810 g_source_set_callback (idle_source,
3811 emit_signal_instance_in_idle_cb,
3813 (GDestroyNotify) signal_instance_free);
3814 g_source_set_name (idle_source, "[gio] emit_signal_instance_in_idle_cb");
3815 g_source_attach (idle_source, subscriber->context);
3816 g_source_unref (idle_source);
3821 /* called in GDBusWorker thread with lock held */
3823 distribute_signals (GDBusConnection *connection,
3824 GDBusMessage *message)
3826 GPtrArray *signal_data_array;
3827 const gchar *sender;
3829 sender = g_dbus_message_get_sender (message);
3831 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3833 _g_dbus_debug_print_lock ();
3834 g_print ("========================================================================\n"
3835 "GDBus-debug:Signal:\n"
3836 " <<<< RECEIVED SIGNAL %s.%s\n"
3838 " sent by name %s\n",
3839 g_dbus_message_get_interface (message),
3840 g_dbus_message_get_member (message),
3841 g_dbus_message_get_path (message),
3842 sender != NULL ? sender : "(none)");
3843 _g_dbus_debug_print_unlock ();
3846 /* collect subscribers that match on sender */
3849 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3850 if (signal_data_array != NULL)
3851 schedule_callbacks (connection, signal_data_array, message, sender);
3854 /* collect subscribers not matching on sender */
3855 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3856 if (signal_data_array != NULL)
3857 schedule_callbacks (connection, signal_data_array, message, sender);
3860 /* ---------------------------------------------------------------------------------------------------- */
3862 /* only called from finalize(), removes all subscriptions */
3864 purge_all_signal_subscriptions (GDBusConnection *connection)
3866 GHashTableIter iter;
3869 GArray *subscribers;
3872 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3873 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3874 while (g_hash_table_iter_next (&iter, &key, NULL))
3876 guint subscription_id = GPOINTER_TO_UINT (key);
3877 g_array_append_val (ids, subscription_id);
3880 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3881 for (n = 0; n < ids->len; n++)
3883 guint subscription_id = g_array_index (ids, guint, n);
3884 unsubscribe_id_internal (connection,
3888 g_array_free (ids, TRUE);
3890 /* call GDestroyNotify without lock held */
3891 for (n = 0; n < subscribers->len; n++)
3893 SignalSubscriber *subscriber;
3894 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3895 call_destroy_notify (subscriber->context,
3896 subscriber->user_data_free_func,
3897 subscriber->user_data);
3898 g_main_context_unref (subscriber->context);
3901 g_array_free (subscribers, TRUE);
3904 /* ---------------------------------------------------------------------------------------------------- */
3906 static GDBusInterfaceVTable *
3907 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3909 /* Don't waste memory by copying padding - remember to update this
3910 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3912 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3916 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
3921 /* ---------------------------------------------------------------------------------------------------- */
3923 static GDBusSubtreeVTable *
3924 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
3926 /* Don't waste memory by copying padding - remember to update this
3927 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
3929 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3933 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
3938 /* ---------------------------------------------------------------------------------------------------- */
3940 struct ExportedObject
3943 GDBusConnection *connection;
3945 /* maps gchar* -> ExportedInterface* */
3946 GHashTable *map_if_name_to_ei;
3949 /* only called with lock held */
3951 exported_object_free (ExportedObject *eo)
3953 g_free (eo->object_path);
3954 g_hash_table_unref (eo->map_if_name_to_ei);
3963 gchar *interface_name;
3964 GDBusInterfaceVTable *vtable;
3965 GDBusInterfaceInfo *interface_info;
3967 GMainContext *context;
3969 GDestroyNotify user_data_free_func;
3970 } ExportedInterface;
3972 /* called with lock held */
3974 exported_interface_free (ExportedInterface *ei)
3976 g_dbus_interface_info_cache_release (ei->interface_info);
3977 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
3979 call_destroy_notify (ei->context,
3980 ei->user_data_free_func,
3983 g_main_context_unref (ei->context);
3985 g_free (ei->interface_name);
3986 _g_dbus_interface_vtable_free (ei->vtable);
3990 /* ---------------------------------------------------------------------------------------------------- */
3992 /* Convenience function to check if @registration_id (if not zero) or
3993 * @subtree_registration_id (if not zero) has been unregistered. If
3994 * so, returns %TRUE.
3996 * May be called by any thread. Caller must *not* hold lock.
3999 has_object_been_unregistered (GDBusConnection *connection,
4000 guint registration_id,
4001 guint subtree_registration_id)
4005 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4009 CONNECTION_LOCK (connection);
4010 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
4011 GUINT_TO_POINTER (registration_id)) == NULL)
4015 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
4016 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
4020 CONNECTION_UNLOCK (connection);
4025 /* ---------------------------------------------------------------------------------------------------- */
4029 GDBusConnection *connection;
4030 GDBusMessage *message;
4032 const gchar *property_name;
4033 const GDBusInterfaceVTable *vtable;
4034 GDBusInterfaceInfo *interface_info;
4035 const GDBusPropertyInfo *property_info;
4036 guint registration_id;
4037 guint subtree_registration_id;
4041 property_data_free (PropertyData *data)
4043 g_object_unref (data->connection);
4044 g_object_unref (data->message);
4048 /* called in thread where object was registered - no locks held */
4050 invoke_get_property_in_idle_cb (gpointer _data)
4052 PropertyData *data = _data;
4055 GDBusMessage *reply;
4057 if (has_object_been_unregistered (data->connection,
4058 data->registration_id,
4059 data->subtree_registration_id))
4061 reply = g_dbus_message_new_method_error (data->message,
4062 "org.freedesktop.DBus.Error.UnknownMethod",
4063 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4064 g_dbus_message_get_path (data->message));
4065 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4066 g_object_unref (reply);
4071 value = data->vtable->get_property (data->connection,
4072 g_dbus_message_get_sender (data->message),
4073 g_dbus_message_get_path (data->message),
4074 data->interface_info->name,
4075 data->property_name,
4082 g_assert_no_error (error);
4084 g_variant_take_ref (value);
4085 reply = g_dbus_message_new_method_reply (data->message);
4086 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4087 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4088 g_variant_unref (value);
4089 g_object_unref (reply);
4093 gchar *dbus_error_name;
4094 g_assert (error != NULL);
4095 dbus_error_name = g_dbus_error_encode_gerror (error);
4096 reply = g_dbus_message_new_method_error_literal (data->message,
4099 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4100 g_free (dbus_error_name);
4101 g_error_free (error);
4102 g_object_unref (reply);
4109 /* called in thread where object was registered - no locks held */
4111 invoke_set_property_in_idle_cb (gpointer _data)
4113 PropertyData *data = _data;
4115 GDBusMessage *reply;
4121 g_variant_get (g_dbus_message_get_body (data->message),
4127 if (!data->vtable->set_property (data->connection,
4128 g_dbus_message_get_sender (data->message),
4129 g_dbus_message_get_path (data->message),
4130 data->interface_info->name,
4131 data->property_name,
4136 gchar *dbus_error_name;
4137 g_assert (error != NULL);
4138 dbus_error_name = g_dbus_error_encode_gerror (error);
4139 reply = g_dbus_message_new_method_error_literal (data->message,
4142 g_free (dbus_error_name);
4143 g_error_free (error);
4147 reply = g_dbus_message_new_method_reply (data->message);
4150 g_assert (reply != NULL);
4151 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4152 g_object_unref (reply);
4153 g_variant_unref (value);
4158 /* called in any thread with connection's lock held */
4160 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4161 GDBusMessage *message,
4162 guint registration_id,
4163 guint subtree_registration_id,
4165 GDBusInterfaceInfo *interface_info,
4166 const GDBusInterfaceVTable *vtable,
4167 GMainContext *main_context,
4171 const char *interface_name;
4172 const char *property_name;
4173 const GDBusPropertyInfo *property_info;
4174 GSource *idle_source;
4175 PropertyData *property_data;
4176 GDBusMessage *reply;
4181 g_variant_get (g_dbus_message_get_body (message),
4186 g_variant_get (g_dbus_message_get_body (message),
4195 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4197 property_info = NULL;
4199 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4200 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4201 if (property_info == NULL)
4203 reply = g_dbus_message_new_method_error (message,
4204 "org.freedesktop.DBus.Error.InvalidArgs",
4205 _("No such property '%s'"),
4207 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4208 g_object_unref (reply);
4213 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4215 reply = g_dbus_message_new_method_error (message,
4216 "org.freedesktop.DBus.Error.InvalidArgs",
4217 _("Property '%s' is not readable"),
4219 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4220 g_object_unref (reply);
4224 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4226 reply = g_dbus_message_new_method_error (message,
4227 "org.freedesktop.DBus.Error.InvalidArgs",
4228 _("Property '%s' is not writable"),
4230 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4231 g_object_unref (reply);
4240 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4241 * of the given value is wrong
4243 g_variant_get_child (g_dbus_message_get_body (message), 2, "v", &value);
4244 if (g_strcmp0 (g_variant_get_type_string (value), property_info->signature) != 0)
4246 reply = g_dbus_message_new_method_error (message,
4247 "org.freedesktop.DBus.Error.InvalidArgs",
4248 _("Error setting property '%s': Expected type '%s' but got '%s'"),
4249 property_name, property_info->signature,
4250 g_variant_get_type_string (value));
4251 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4252 g_variant_unref (value);
4253 g_object_unref (reply);
4258 g_variant_unref (value);
4261 /* If the vtable pointer for get_property() resp. set_property() is
4262 * NULL then dispatch the call via the method_call() handler.
4266 if (vtable->get_property == NULL)
4268 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4269 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4270 vtable, main_context, user_data);
4277 if (vtable->set_property == NULL)
4279 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4280 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4281 vtable, main_context, user_data);
4287 /* ok, got the property info - call user code in an idle handler */
4288 property_data = g_new0 (PropertyData, 1);
4289 property_data->connection = g_object_ref (connection);
4290 property_data->message = g_object_ref (message);
4291 property_data->user_data = user_data;
4292 property_data->property_name = property_name;
4293 property_data->vtable = vtable;
4294 property_data->interface_info = interface_info;
4295 property_data->property_info = property_info;
4296 property_data->registration_id = registration_id;
4297 property_data->subtree_registration_id = subtree_registration_id;
4299 idle_source = g_idle_source_new ();
4300 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4301 g_source_set_callback (idle_source,
4302 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4304 (GDestroyNotify) property_data_free);
4306 g_source_set_name (idle_source, "[gio] invoke_get_property_in_idle_cb");
4308 g_source_set_name (idle_source, "[gio] invoke_set_property_in_idle_cb");
4309 g_source_attach (idle_source, main_context);
4310 g_source_unref (idle_source);
4318 /* called in GDBusWorker thread with connection's lock held */
4320 handle_getset_property (GDBusConnection *connection,
4322 GDBusMessage *message,
4325 ExportedInterface *ei;
4327 const char *interface_name;
4328 const char *property_name;
4333 g_variant_get (g_dbus_message_get_body (message),
4338 g_variant_get (g_dbus_message_get_body (message),
4344 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4345 * no such interface registered
4347 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4350 GDBusMessage *reply;
4351 reply = g_dbus_message_new_method_error (message,
4352 "org.freedesktop.DBus.Error.InvalidArgs",
4353 _("No such interface '%s'"),
4355 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4356 g_object_unref (reply);
4361 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4374 /* ---------------------------------------------------------------------------------------------------- */
4378 GDBusConnection *connection;
4379 GDBusMessage *message;
4381 const GDBusInterfaceVTable *vtable;
4382 GDBusInterfaceInfo *interface_info;
4383 guint registration_id;
4384 guint subtree_registration_id;
4385 } PropertyGetAllData;
4388 property_get_all_data_free (PropertyData *data)
4390 g_object_unref (data->connection);
4391 g_object_unref (data->message);
4395 /* called in thread where object was registered - no locks held */
4397 invoke_get_all_properties_in_idle_cb (gpointer _data)
4399 PropertyGetAllData *data = _data;
4400 GVariantBuilder builder;
4401 GDBusMessage *reply;
4404 if (has_object_been_unregistered (data->connection,
4405 data->registration_id,
4406 data->subtree_registration_id))
4408 reply = g_dbus_message_new_method_error (data->message,
4409 "org.freedesktop.DBus.Error.UnknownMethod",
4410 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4411 g_dbus_message_get_path (data->message));
4412 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4413 g_object_unref (reply);
4417 /* TODO: Right now we never fail this call - we just omit values if
4418 * a get_property() call is failing.
4420 * We could fail the whole call if just a single get_property() call
4421 * returns an error. We need clarification in the D-Bus spec about this.
4423 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4424 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4425 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4427 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4430 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4433 value = data->vtable->get_property (data->connection,
4434 g_dbus_message_get_sender (data->message),
4435 g_dbus_message_get_path (data->message),
4436 data->interface_info->name,
4437 property_info->name,
4444 g_variant_take_ref (value);
4445 g_variant_builder_add (&builder,
4447 property_info->name,
4449 g_variant_unref (value);
4451 g_variant_builder_close (&builder);
4453 reply = g_dbus_message_new_method_reply (data->message);
4454 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4455 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4456 g_object_unref (reply);
4463 interface_has_readable_properties (GDBusInterfaceInfo *interface_info)
4467 if (!interface_info->properties)
4470 for (i = 0; interface_info->properties[i]; i++)
4471 if (interface_info->properties[i]->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE)
4477 /* called in any thread with connection's lock held */
4479 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4480 GDBusMessage *message,
4481 guint registration_id,
4482 guint subtree_registration_id,
4483 GDBusInterfaceInfo *interface_info,
4484 const GDBusInterfaceVTable *vtable,
4485 GMainContext *main_context,
4489 GSource *idle_source;
4490 PropertyGetAllData *property_get_all_data;
4497 /* If the vtable pointer for get_property() is NULL but we have a
4498 * non-zero number of readable properties, then dispatch the call via
4499 * the method_call() handler.
4501 if (vtable->get_property == NULL && interface_has_readable_properties (interface_info))
4503 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4504 interface_info, NULL, NULL, g_dbus_message_get_body (message),
4505 vtable, main_context, user_data);
4510 /* ok, got the property info - call user in an idle handler */
4511 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4512 property_get_all_data->connection = g_object_ref (connection);
4513 property_get_all_data->message = g_object_ref (message);
4514 property_get_all_data->user_data = user_data;
4515 property_get_all_data->vtable = vtable;
4516 property_get_all_data->interface_info = interface_info;
4517 property_get_all_data->registration_id = registration_id;
4518 property_get_all_data->subtree_registration_id = subtree_registration_id;
4520 idle_source = g_idle_source_new ();
4521 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4522 g_source_set_callback (idle_source,
4523 invoke_get_all_properties_in_idle_cb,
4524 property_get_all_data,
4525 (GDestroyNotify) property_get_all_data_free);
4526 g_source_set_name (idle_source, "[gio] invoke_get_all_properties_in_idle_cb");
4527 g_source_attach (idle_source, main_context);
4528 g_source_unref (idle_source);
4536 /* called in GDBusWorker thread with connection's lock held */
4538 handle_get_all_properties (GDBusConnection *connection,
4540 GDBusMessage *message)
4542 ExportedInterface *ei;
4544 const char *interface_name;
4548 g_variant_get (g_dbus_message_get_body (message),
4552 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4553 * no such interface registered
4555 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4558 GDBusMessage *reply;
4559 reply = g_dbus_message_new_method_error (message,
4560 "org.freedesktop.DBus.Error.InvalidArgs",
4561 _("No such interface"),
4563 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4564 g_object_unref (reply);
4569 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4581 /* ---------------------------------------------------------------------------------------------------- */
4583 static const gchar introspect_header[] =
4584 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4585 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4586 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4589 static const gchar introspect_tail[] =
4592 static const gchar introspect_properties_interface[] =
4593 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4594 " <method name=\"Get\">\n"
4595 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4596 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4597 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4599 " <method name=\"GetAll\">\n"
4600 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4601 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4603 " <method name=\"Set\">\n"
4604 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4605 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4606 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4608 " <signal name=\"PropertiesChanged\">\n"
4609 " <arg type=\"s\" name=\"interface_name\"/>\n"
4610 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4611 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4615 static const gchar introspect_introspectable_interface[] =
4616 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4617 " <method name=\"Introspect\">\n"
4618 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4621 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4622 " <method name=\"Ping\"/>\n"
4623 " <method name=\"GetMachineId\">\n"
4624 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4629 introspect_append_header (GString *s)
4631 g_string_append (s, introspect_header);
4635 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4637 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4643 begin = object_path + path_len;
4644 end = strchr (begin, '/');
4646 s = g_strndup (begin, end - begin);
4648 s = g_strdup (begin);
4650 if (g_hash_table_lookup (set, s) == NULL)
4651 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
4657 /* TODO: we want a nicer public interface for this */
4658 /* called in any thread with connection's lock held */
4660 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4665 GHashTableIter hash_iter;
4666 const gchar *object_path;
4672 CONNECTION_ENSURE_LOCK (connection);
4674 path_len = strlen (path);
4678 set = g_hash_table_new (g_str_hash, g_str_equal);
4680 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4681 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4682 maybe_add_path (path, path_len, object_path, set);
4684 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4685 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4686 maybe_add_path (path, path_len, object_path, set);
4688 p = g_ptr_array_new ();
4689 keys = g_hash_table_get_keys (set);
4690 for (l = keys; l != NULL; l = l->next)
4691 g_ptr_array_add (p, l->data);
4692 g_hash_table_unref (set);
4695 g_ptr_array_add (p, NULL);
4696 ret = (gchar **) g_ptr_array_free (p, FALSE);
4700 /* called in any thread with connection's lock not held */
4702 g_dbus_connection_list_registered (GDBusConnection *connection,
4706 CONNECTION_LOCK (connection);
4707 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4708 CONNECTION_UNLOCK (connection);
4712 /* called in GDBusWorker thread with connection's lock held */
4714 handle_introspect (GDBusConnection *connection,
4716 GDBusMessage *message)
4720 GDBusMessage *reply;
4721 GHashTableIter hash_iter;
4722 ExportedInterface *ei;
4725 /* first the header with the standard interfaces */
4726 s = g_string_sized_new (sizeof (introspect_header) +
4727 sizeof (introspect_properties_interface) +
4728 sizeof (introspect_introspectable_interface) +
4729 sizeof (introspect_tail));
4730 introspect_append_header (s);
4731 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4732 "org.freedesktop.DBus.Properties"))
4733 g_string_append (s, introspect_properties_interface);
4735 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4736 "org.freedesktop.DBus.Introspectable"))
4737 g_string_append (s, introspect_introspectable_interface);
4739 /* then include the registered interfaces */
4740 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4741 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4742 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4744 /* finally include nodes registered below us */
4745 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4746 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4747 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4748 g_strfreev (registered);
4749 g_string_append (s, introspect_tail);
4751 reply = g_dbus_message_new_method_reply (message);
4752 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4753 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4754 g_object_unref (reply);
4755 g_string_free (s, TRUE);
4760 /* called in thread where object was registered - no locks held */
4762 call_in_idle_cb (gpointer user_data)
4764 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4765 GDBusInterfaceVTable *vtable;
4766 guint registration_id;
4767 guint subtree_registration_id;
4769 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4770 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4772 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4774 subtree_registration_id))
4776 GDBusMessage *reply;
4777 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4778 "org.freedesktop.DBus.Error.UnknownMethod",
4779 _("No such interface '%s' on object at path %s"),
4780 g_dbus_method_invocation_get_interface_name (invocation),
4781 g_dbus_method_invocation_get_object_path (invocation));
4782 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4783 g_object_unref (reply);
4787 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4788 g_assert (vtable != NULL && vtable->method_call != NULL);
4790 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4791 g_dbus_method_invocation_get_sender (invocation),
4792 g_dbus_method_invocation_get_object_path (invocation),
4793 g_dbus_method_invocation_get_interface_name (invocation),
4794 g_dbus_method_invocation_get_method_name (invocation),
4795 g_dbus_method_invocation_get_parameters (invocation),
4796 g_object_ref (invocation),
4797 g_dbus_method_invocation_get_user_data (invocation));
4803 /* called in GDBusWorker thread with connection's lock held */
4805 schedule_method_call (GDBusConnection *connection,
4806 GDBusMessage *message,
4807 guint registration_id,
4808 guint subtree_registration_id,
4809 const GDBusInterfaceInfo *interface_info,
4810 const GDBusMethodInfo *method_info,
4811 const GDBusPropertyInfo *property_info,
4812 GVariant *parameters,
4813 const GDBusInterfaceVTable *vtable,
4814 GMainContext *main_context,
4817 GDBusMethodInvocation *invocation;
4818 GSource *idle_source;
4820 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4821 g_dbus_message_get_path (message),
4822 g_dbus_message_get_interface (message),
4823 g_dbus_message_get_member (message),
4831 /* TODO: would be nicer with a real MethodData like we already
4832 * have PropertyData and PropertyGetAllData... */
4833 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4834 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4835 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4837 idle_source = g_idle_source_new ();
4838 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4839 g_source_set_callback (idle_source,
4843 g_source_set_name (idle_source, "[gio] call_in_idle_cb");
4844 g_source_attach (idle_source, main_context);
4845 g_source_unref (idle_source);
4848 /* called in GDBusWorker thread with connection's lock held */
4850 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4851 GDBusMessage *message,
4852 guint registration_id,
4853 guint subtree_registration_id,
4854 GDBusInterfaceInfo *interface_info,
4855 const GDBusInterfaceVTable *vtable,
4856 GMainContext *main_context,
4859 GDBusMethodInfo *method_info;
4860 GDBusMessage *reply;
4861 GVariant *parameters;
4863 GVariantType *in_type;
4867 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4868 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4870 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4871 * error to the caller
4873 if (method_info == NULL)
4875 reply = g_dbus_message_new_method_error (message,
4876 "org.freedesktop.DBus.Error.UnknownMethod",
4877 _("No such method '%s'"),
4878 g_dbus_message_get_member (message));
4879 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4880 g_object_unref (reply);
4885 parameters = g_dbus_message_get_body (message);
4886 if (parameters == NULL)
4888 parameters = g_variant_new ("()");
4889 g_variant_ref_sink (parameters);
4893 g_variant_ref (parameters);
4896 /* Check that the incoming args are of the right type - if they are not, return
4897 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4899 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4900 if (!g_variant_is_of_type (parameters, in_type))
4904 type_string = g_variant_type_dup_string (in_type);
4906 reply = g_dbus_message_new_method_error (message,
4907 "org.freedesktop.DBus.Error.InvalidArgs",
4908 _("Type of message, '%s', does not match expected type '%s'"),
4909 g_variant_get_type_string (parameters),
4911 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4912 g_variant_type_free (in_type);
4913 g_variant_unref (parameters);
4914 g_object_unref (reply);
4915 g_free (type_string);
4919 g_variant_type_free (in_type);
4921 /* schedule the call in idle */
4922 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4923 interface_info, method_info, NULL, parameters,
4924 vtable, main_context, user_data);
4925 g_variant_unref (parameters);
4932 /* ---------------------------------------------------------------------------------------------------- */
4934 /* called in GDBusWorker thread with connection's lock held */
4936 obj_message_func (GDBusConnection *connection,
4938 GDBusMessage *message)
4940 const gchar *interface_name;
4941 const gchar *member;
4942 const gchar *signature;
4947 interface_name = g_dbus_message_get_interface (message);
4948 member = g_dbus_message_get_member (message);
4949 signature = g_dbus_message_get_signature (message);
4951 /* see if we have an interface for handling this call */
4952 if (interface_name != NULL)
4954 ExportedInterface *ei;
4955 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4958 /* we do - invoke the handler in idle in the right thread */
4960 /* handle no vtable or handler being present */
4961 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
4964 handled = validate_and_maybe_schedule_method_call (connection,
4976 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4977 g_strcmp0 (member, "Introspect") == 0 &&
4978 g_strcmp0 (signature, "") == 0)
4980 handled = handle_introspect (connection, eo, message);
4983 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4984 g_strcmp0 (member, "Get") == 0 &&
4985 g_strcmp0 (signature, "ss") == 0)
4987 handled = handle_getset_property (connection, eo, message, TRUE);
4990 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4991 g_strcmp0 (member, "Set") == 0 &&
4992 g_strcmp0 (signature, "ssv") == 0)
4994 handled = handle_getset_property (connection, eo, message, FALSE);
4997 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4998 g_strcmp0 (member, "GetAll") == 0 &&
4999 g_strcmp0 (signature, "s") == 0)
5001 handled = handle_get_all_properties (connection, eo, message);
5010 * g_dbus_connection_register_object:
5011 * @connection: a #GDBusConnection
5012 * @object_path: the object path to register at
5013 * @interface_info: introspection data for the interface
5014 * @vtable: (allow-none): a #GDBusInterfaceVTable to call into or %NULL
5015 * @user_data: (allow-none): data to pass to functions in @vtable
5016 * @user_data_free_func: function to call when the object path is unregistered
5017 * @error: return location for error or %NULL
5019 * Registers callbacks for exported objects at @object_path with the
5020 * D-Bus interface that is described in @interface_info.
5022 * Calls to functions in @vtable (and @user_data_free_func) will happen
5024 * [thread-default main context][g-main-context-push-thread-default]
5025 * of the thread you are calling this method from.
5027 * Note that all #GVariant values passed to functions in @vtable will match
5028 * the signature given in @interface_info - if a remote caller passes
5029 * incorrect values, the `org.freedesktop.DBus.Error.InvalidArgs`
5030 * is returned to the remote caller.
5032 * Additionally, if the remote caller attempts to invoke methods or
5033 * access properties not mentioned in @interface_info the
5034 * `org.freedesktop.DBus.Error.UnknownMethod` resp.
5035 * `org.freedesktop.DBus.Error.InvalidArgs` errors
5036 * are returned to the caller.
5038 * It is considered a programming error if the
5039 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
5040 * #GVariant of incorrect type.
5042 * If an existing callback is already registered at @object_path and
5043 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
5045 * GDBus automatically implements the standard D-Bus interfaces
5046 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
5047 * and org.freedesktop.Peer, so you don't have to implement those for the
5048 * objects you export. You can implement org.freedesktop.DBus.Properties
5049 * yourself, e.g. to handle getting and setting of properties asynchronously.
5051 * Note that the reference count on @interface_info will be
5052 * incremented by 1 (unless allocated statically, e.g. if the
5053 * reference count is -1, see g_dbus_interface_info_ref()) for as long
5054 * as the object is exported. Also note that @vtable will be copied.
5056 * See this [server][gdbus-server] for an example of how to use this method.
5058 * Returns: 0 if @error is set, otherwise a registration id (never 0)
5059 * that can be used with g_dbus_connection_unregister_object()
5064 g_dbus_connection_register_object (GDBusConnection *connection,
5065 const gchar *object_path,
5066 GDBusInterfaceInfo *interface_info,
5067 const GDBusInterfaceVTable *vtable,
5069 GDestroyNotify user_data_free_func,
5073 ExportedInterface *ei;
5076 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5077 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5078 g_return_val_if_fail (interface_info != NULL, 0);
5079 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
5080 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5081 g_return_val_if_fail (check_initialized (connection), 0);
5085 CONNECTION_LOCK (connection);
5087 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5090 eo = g_new0 (ExportedObject, 1);
5091 eo->object_path = g_strdup (object_path);
5092 eo->connection = connection;
5093 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
5096 (GDestroyNotify) exported_interface_free);
5097 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
5100 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
5106 _("An object is already exported for the interface %s at %s"),
5107 interface_info->name,
5112 ei = g_new0 (ExportedInterface, 1);
5113 ei->id = _global_registration_id++; /* TODO: overflow etc. */
5115 ei->user_data = user_data;
5116 ei->user_data_free_func = user_data_free_func;
5117 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
5118 ei->interface_info = g_dbus_interface_info_ref (interface_info);
5119 g_dbus_interface_info_cache_build (ei->interface_info);
5120 ei->interface_name = g_strdup (interface_info->name);
5121 ei->context = g_main_context_ref_thread_default ();
5123 g_hash_table_insert (eo->map_if_name_to_ei,
5124 (gpointer) ei->interface_name,
5126 g_hash_table_insert (connection->map_id_to_ei,
5127 GUINT_TO_POINTER (ei->id),
5133 CONNECTION_UNLOCK (connection);
5139 * g_dbus_connection_unregister_object:
5140 * @connection: a #GDBusConnection
5141 * @registration_id: a registration id obtained from
5142 * g_dbus_connection_register_object()
5144 * Unregisters an object.
5146 * Returns: %TRUE if the object was unregistered, %FALSE otherwise
5151 g_dbus_connection_unregister_object (GDBusConnection *connection,
5152 guint registration_id)
5154 ExportedInterface *ei;
5158 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5159 g_return_val_if_fail (check_initialized (connection), FALSE);
5163 CONNECTION_LOCK (connection);
5165 ei = g_hash_table_lookup (connection->map_id_to_ei,
5166 GUINT_TO_POINTER (registration_id));
5172 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5173 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5174 /* unregister object path if we have no more exported interfaces */
5175 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5176 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5182 CONNECTION_UNLOCK (connection);
5187 /* ---------------------------------------------------------------------------------------------------- */
5190 * g_dbus_connection_emit_signal:
5191 * @connection: a #GDBusConnection
5192 * @destination_bus_name: (allow-none): the unique bus name for the destination
5193 * for the signal or %NULL to emit to all listeners
5194 * @object_path: path of remote object
5195 * @interface_name: D-Bus interface to emit a signal on
5196 * @signal_name: the name of the signal to emit
5197 * @parameters: (allow-none): a #GVariant tuple with parameters for the signal
5198 * or %NULL if not passing parameters
5199 * @error: Return location for error or %NULL
5203 * If the parameters GVariant is floating, it is consumed.
5205 * This can only fail if @parameters is not compatible with the D-Bus protocol.
5207 * Returns: %TRUE unless @error is set
5212 g_dbus_connection_emit_signal (GDBusConnection *connection,
5213 const gchar *destination_bus_name,
5214 const gchar *object_path,
5215 const gchar *interface_name,
5216 const gchar *signal_name,
5217 GVariant *parameters,
5220 GDBusMessage *message;
5226 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5227 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5228 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5229 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5230 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5231 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5232 g_return_val_if_fail (check_initialized (connection), FALSE);
5234 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5236 _g_dbus_debug_print_lock ();
5237 g_print ("========================================================================\n"
5238 "GDBus-debug:Emission:\n"
5239 " >>>> SIGNAL EMISSION %s.%s()\n"
5241 " destination %s\n",
5242 interface_name, signal_name,
5244 destination_bus_name != NULL ? destination_bus_name : "(none)");
5245 _g_dbus_debug_print_unlock ();
5248 message = g_dbus_message_new_signal (object_path,
5252 if (destination_bus_name != NULL)
5253 g_dbus_message_set_header (message,
5254 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5255 g_variant_new_string (destination_bus_name));
5257 if (parameters != NULL)
5258 g_dbus_message_set_body (message, parameters);
5260 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5261 g_object_unref (message);
5267 add_call_flags (GDBusMessage *message,
5268 GDBusCallFlags flags)
5270 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5271 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
5275 decode_method_reply (GDBusMessage *reply,
5276 const gchar *method_name,
5277 const GVariantType *reply_type,
5278 GUnixFDList **out_fd_list,
5284 switch (g_dbus_message_get_message_type (reply))
5286 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5287 result = g_dbus_message_get_body (reply);
5290 result = g_variant_new ("()");
5291 g_variant_ref_sink (result);
5295 g_variant_ref (result);
5298 if (!g_variant_is_of_type (result, reply_type))
5300 gchar *type_string = g_variant_type_dup_string (reply_type);
5304 G_IO_ERROR_INVALID_ARGUMENT,
5305 _("Method '%s' returned type '%s', but expected '%s'"),
5306 method_name, g_variant_get_type_string (result), type_string);
5308 g_variant_unref (result);
5309 g_free (type_string);
5316 if (out_fd_list != NULL)
5318 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5319 if (*out_fd_list != NULL)
5320 g_object_ref (*out_fd_list);
5326 case G_DBUS_MESSAGE_TYPE_ERROR:
5327 g_dbus_message_to_gerror (reply, error);
5331 g_assert_not_reached ();
5341 GVariantType *reply_type;
5342 gchar *method_name; /* for error message */
5345 GUnixFDList *fd_list;
5349 call_state_free (CallState *state)
5351 g_variant_type_free (state->reply_type);
5352 g_free (state->method_name);
5354 if (state->fd_list != NULL)
5355 g_object_unref (state->fd_list);
5356 g_slice_free (CallState, state);
5359 /* called in any thread, with the connection's lock not held */
5361 g_dbus_connection_call_done (GObject *source,
5362 GAsyncResult *result,
5365 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5366 GTask *task = user_data;
5367 CallState *state = g_task_get_task_data (task);
5368 GError *error = NULL;
5369 GDBusMessage *reply;
5370 GVariant *value = NULL;
5372 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5376 if (G_UNLIKELY (_g_dbus_debug_call ()))
5378 _g_dbus_debug_print_lock ();
5379 g_print ("========================================================================\n"
5380 "GDBus-debug:Call:\n"
5381 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5387 g_print ("SUCCESS\n");
5391 g_print ("FAILED: %s\n",
5394 _g_dbus_debug_print_unlock ();
5398 value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5401 g_task_return_error (task, error);
5403 g_task_return_pointer (task, value, (GDestroyNotify) g_variant_unref);
5405 g_clear_object (&reply);
5406 g_object_unref (task);
5409 /* called in any thread, with the connection's lock not held */
5411 g_dbus_connection_call_internal (GDBusConnection *connection,
5412 const gchar *bus_name,
5413 const gchar *object_path,
5414 const gchar *interface_name,
5415 const gchar *method_name,
5416 GVariant *parameters,
5417 const GVariantType *reply_type,
5418 GDBusCallFlags flags,
5420 GUnixFDList *fd_list,
5421 GCancellable *cancellable,
5422 GAsyncReadyCallback callback,
5425 GDBusMessage *message;
5428 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5429 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5430 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5431 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5432 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5433 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5434 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5435 g_return_if_fail (check_initialized (connection));
5437 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5439 g_return_if_fail (fd_list == NULL);
5442 message = g_dbus_message_new_method_call (bus_name,
5446 add_call_flags (message, flags);
5447 if (parameters != NULL)
5448 g_dbus_message_set_body (message, parameters);
5451 if (fd_list != NULL)
5452 g_dbus_message_set_unix_fd_list (message, fd_list);
5455 /* If the user has no callback then we can just send the message with
5456 * the G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set and skip all
5457 * the logic for processing the reply. If the service sends the reply
5458 * anyway then it will just be ignored.
5460 if (callback != NULL)
5465 state = g_slice_new0 (CallState);
5466 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5468 if (reply_type == NULL)
5469 reply_type = G_VARIANT_TYPE_ANY;
5471 state->reply_type = g_variant_type_copy (reply_type);
5473 task = g_task_new (connection, cancellable, callback, user_data);
5474 g_task_set_task_data (task, state, (GDestroyNotify) call_state_free);
5476 g_dbus_connection_send_message_with_reply (connection,
5478 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5482 g_dbus_connection_call_done,
5484 serial = state->serial;
5488 GDBusMessageFlags flags;
5490 flags = g_dbus_message_get_flags (message);
5491 flags |= G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
5492 g_dbus_message_set_flags (message, flags);
5494 g_dbus_connection_send_message (connection,
5496 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5500 if (G_UNLIKELY (_g_dbus_debug_call ()))
5502 _g_dbus_debug_print_lock ();
5503 g_print ("========================================================================\n"
5504 "GDBus-debug:Call:\n"
5505 " >>>> ASYNC %s.%s()\n"
5507 " owned by name %s (serial %d)\n",
5511 bus_name != NULL ? bus_name : "(none)",
5513 _g_dbus_debug_print_unlock ();
5516 if (message != NULL)
5517 g_object_unref (message);
5520 /* called in any thread, with the connection's lock not held */
5522 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
5523 GUnixFDList **out_fd_list,
5531 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5532 g_return_val_if_fail (g_task_is_valid (res, connection), NULL);
5533 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5535 task = G_TASK (res);
5536 state = g_task_get_task_data (task);
5538 ret = g_task_propagate_pointer (task, error);
5542 if (out_fd_list != NULL)
5543 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
5547 /* called in any user thread, with the connection's lock not held */
5549 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
5550 const gchar *bus_name,
5551 const gchar *object_path,
5552 const gchar *interface_name,
5553 const gchar *method_name,
5554 GVariant *parameters,
5555 const GVariantType *reply_type,
5556 GDBusCallFlags flags,
5558 GUnixFDList *fd_list,
5559 GUnixFDList **out_fd_list,
5560 GCancellable *cancellable,
5563 GDBusMessage *message;
5564 GDBusMessage *reply;
5566 GError *local_error;
5567 GDBusSendMessageFlags send_flags;
5573 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5574 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5575 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5576 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5577 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5578 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5579 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5581 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
5583 g_return_val_if_fail (fd_list == NULL, NULL);
5585 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5587 if (!(flags & CALL_FLAGS_INITIALIZING))
5588 g_return_val_if_fail (check_initialized (connection), FALSE);
5590 if (reply_type == NULL)
5591 reply_type = G_VARIANT_TYPE_ANY;
5593 message = g_dbus_message_new_method_call (bus_name,
5597 add_call_flags (message, flags);
5598 if (parameters != NULL)
5599 g_dbus_message_set_body (message, parameters);
5602 if (fd_list != NULL)
5603 g_dbus_message_set_unix_fd_list (message, fd_list);
5606 if (G_UNLIKELY (_g_dbus_debug_call ()))
5608 _g_dbus_debug_print_lock ();
5609 g_print ("========================================================================\n"
5610 "GDBus-debug:Call:\n"
5611 " >>>> SYNC %s.%s()\n"
5613 " owned by name %s\n",
5617 bus_name != NULL ? bus_name : "(none)");
5618 _g_dbus_debug_print_unlock ();
5623 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
5625 /* translate from one flavour of flags to another... */
5626 if (flags & CALL_FLAGS_INITIALIZING)
5627 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
5629 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5633 NULL, /* volatile guint32 *out_serial */
5637 if (G_UNLIKELY (_g_dbus_debug_call ()))
5639 _g_dbus_debug_print_lock ();
5640 g_print ("========================================================================\n"
5641 "GDBus-debug:Call:\n"
5642 " <<<< SYNC COMPLETE %s.%s()\n"
5648 g_print ("SUCCESS\n");
5652 g_print ("FAILED: %s\n",
5653 local_error->message);
5655 _g_dbus_debug_print_unlock ();
5661 *error = local_error;
5663 g_error_free (local_error);
5667 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
5670 if (message != NULL)
5671 g_object_unref (message);
5673 g_object_unref (reply);
5678 /* ---------------------------------------------------------------------------------------------------- */
5681 * g_dbus_connection_call:
5682 * @connection: a #GDBusConnection
5683 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
5684 * @connection is not a message bus connection
5685 * @object_path: path of remote object
5686 * @interface_name: D-Bus interface to invoke method on
5687 * @method_name: the name of the method to invoke
5688 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
5689 * or %NULL if not passing parameters
5690 * @reply_type: (allow-none): the expected type of the reply, or %NULL
5691 * @flags: flags from the #GDBusCallFlags enumeration
5692 * @timeout_msec: the timeout in milliseconds, -1 to use the default
5693 * timeout or %G_MAXINT for no timeout
5694 * @cancellable: (allow-none): a #GCancellable or %NULL
5695 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request
5696 * is satisfied or %NULL if you don't care about the result of the
5698 * @user_data: the data to pass to @callback
5700 * Asynchronously invokes the @method_name method on the
5701 * @interface_name D-Bus interface on the remote object at
5702 * @object_path owned by @bus_name.
5704 * If @connection is closed then the operation will fail with
5705 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
5706 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
5707 * not compatible with the D-Bus protocol, the operation fails with
5708 * %G_IO_ERROR_INVALID_ARGUMENT.
5710 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
5711 * error will be raised if it does not match. Said another way, if you give a @reply_type
5712 * then any non-%NULL return value will be of this type.
5714 * If the @parameters #GVariant is floating, it is consumed. This allows
5715 * convenient 'inline' use of g_variant_new(), e.g.:
5716 * |[<!-- language="C" -->
5717 * g_dbus_connection_call (connection,
5718 * "org.freedesktop.StringThings",
5719 * "/org/freedesktop/StringThings",
5720 * "org.freedesktop.StringThings",
5722 * g_variant_new ("(ss)",
5726 * G_DBUS_CALL_FLAGS_NONE,
5729 * (GAsyncReadyCallback) two_strings_done,
5733 * This is an asynchronous method. When the operation is finished,
5734 * @callback will be invoked in the
5735 * [thread-default main context][g-main-context-push-thread-default]
5736 * of the thread you are calling this method from. You can then call
5737 * g_dbus_connection_call_finish() to get the result of the operation.
5738 * See g_dbus_connection_call_sync() for the synchronous version of this
5741 * If @callback is %NULL then the D-Bus method call message will be sent with
5742 * the %G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set.
5747 g_dbus_connection_call (GDBusConnection *connection,
5748 const gchar *bus_name,
5749 const gchar *object_path,
5750 const gchar *interface_name,
5751 const gchar *method_name,
5752 GVariant *parameters,
5753 const GVariantType *reply_type,
5754 GDBusCallFlags flags,
5756 GCancellable *cancellable,
5757 GAsyncReadyCallback callback,
5760 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);
5764 * g_dbus_connection_call_finish:
5765 * @connection: a #GDBusConnection
5766 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call()
5767 * @error: return location for error or %NULL
5769 * Finishes an operation started with g_dbus_connection_call().
5771 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5772 * return values. Free with g_variant_unref().
5777 g_dbus_connection_call_finish (GDBusConnection *connection,
5781 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
5785 * g_dbus_connection_call_sync:
5786 * @connection: a #GDBusConnection
5787 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
5788 * @connection is not a message bus connection
5789 * @object_path: path of remote object
5790 * @interface_name: D-Bus interface to invoke method on
5791 * @method_name: the name of the method to invoke
5792 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
5793 * or %NULL if not passing parameters
5794 * @reply_type: (allow-none): the expected type of the reply, or %NULL
5795 * @flags: flags from the #GDBusCallFlags enumeration
5796 * @timeout_msec: the timeout in milliseconds, -1 to use the default
5797 * timeout or %G_MAXINT for no timeout
5798 * @cancellable: (allow-none): a #GCancellable or %NULL
5799 * @error: return location for error or %NULL
5801 * Synchronously invokes the @method_name method on the
5802 * @interface_name D-Bus interface on the remote object at
5803 * @object_path owned by @bus_name.
5805 * If @connection is closed then the operation will fail with
5806 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
5807 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
5808 * contains a value not compatible with the D-Bus protocol, the operation
5809 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
5811 * If @reply_type is non-%NULL then the reply will be checked for having
5812 * this type and an error will be raised if it does not match. Said
5813 * another way, if you give a @reply_type then any non-%NULL return
5814 * value will be of this type.
5816 * If the @parameters #GVariant is floating, it is consumed.
5817 * This allows convenient 'inline' use of g_variant_new(), e.g.:
5818 * |[<!-- language="C" -->
5819 * g_dbus_connection_call_sync (connection,
5820 * "org.freedesktop.StringThings",
5821 * "/org/freedesktop/StringThings",
5822 * "org.freedesktop.StringThings",
5824 * g_variant_new ("(ss)",
5828 * G_DBUS_CALL_FLAGS_NONE,
5834 * The calling thread is blocked until a reply is received. See
5835 * g_dbus_connection_call() for the asynchronous version of
5838 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5839 * return values. Free with g_variant_unref().
5844 g_dbus_connection_call_sync (GDBusConnection *connection,
5845 const gchar *bus_name,
5846 const gchar *object_path,
5847 const gchar *interface_name,
5848 const gchar *method_name,
5849 GVariant *parameters,
5850 const GVariantType *reply_type,
5851 GDBusCallFlags flags,
5853 GCancellable *cancellable,
5856 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);
5859 /* ---------------------------------------------------------------------------------------------------- */
5864 * g_dbus_connection_call_with_unix_fd_list:
5865 * @connection: a #GDBusConnection
5866 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
5867 * @connection is not a message bus connection
5868 * @object_path: path of remote object
5869 * @interface_name: D-Bus interface to invoke method on
5870 * @method_name: the name of the method to invoke
5871 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
5872 * or %NULL if not passing parameters
5873 * @reply_type: (allow-none): the expected type of the reply, or %NULL
5874 * @flags: flags from the #GDBusCallFlags enumeration
5875 * @timeout_msec: the timeout in milliseconds, -1 to use the default
5876 * timeout or %G_MAXINT for no timeout
5877 * @fd_list: (allow-none): a #GUnixFDList or %NULL
5878 * @cancellable: (allow-none): a #GCancellable or %NULL
5879 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request is
5880 * satisfied or %NULL if you don't * care about the result of the
5882 * @user_data: The data to pass to @callback.
5884 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
5886 * This method is only available on UNIX.
5891 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
5892 const gchar *bus_name,
5893 const gchar *object_path,
5894 const gchar *interface_name,
5895 const gchar *method_name,
5896 GVariant *parameters,
5897 const GVariantType *reply_type,
5898 GDBusCallFlags flags,
5900 GUnixFDList *fd_list,
5901 GCancellable *cancellable,
5902 GAsyncReadyCallback callback,
5905 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);
5909 * g_dbus_connection_call_with_unix_fd_list_finish:
5910 * @connection: a #GDBusConnection
5911 * @out_fd_list: (out) (allow-none): return location for a #GUnixFDList or %NULL
5912 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
5913 * g_dbus_connection_call_with_unix_fd_list()
5914 * @error: return location for error or %NULL
5916 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
5918 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5919 * return values. Free with g_variant_unref().
5924 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
5925 GUnixFDList **out_fd_list,
5929 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
5933 * g_dbus_connection_call_with_unix_fd_list_sync:
5934 * @connection: a #GDBusConnection
5935 * @bus_name: (allow-none): a unique or well-known bus name or %NULL
5936 * if @connection is not a message bus connection
5937 * @object_path: path of remote object
5938 * @interface_name: D-Bus interface to invoke method on
5939 * @method_name: the name of the method to invoke
5940 * @parameters: (allow-none): a #GVariant tuple with parameters for
5941 * the method or %NULL if not passing parameters
5942 * @reply_type: (allow-none): the expected type of the reply, or %NULL
5943 * @flags: flags from the #GDBusCallFlags enumeration
5944 * @timeout_msec: the timeout in milliseconds, -1 to use the default
5945 * timeout or %G_MAXINT for no timeout
5946 * @fd_list: (allow-none): a #GUnixFDList or %NULL
5947 * @out_fd_list: (out) (allow-none): return location for a #GUnixFDList or %NULL
5948 * @cancellable: (allow-none): a #GCancellable or %NULL
5949 * @error: return location for error or %NULL
5951 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
5953 * This method is only available on UNIX.
5955 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5956 * return values. Free with g_variant_unref().
5961 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
5962 const gchar *bus_name,
5963 const gchar *object_path,
5964 const gchar *interface_name,
5965 const gchar *method_name,
5966 GVariant *parameters,
5967 const GVariantType *reply_type,
5968 GDBusCallFlags flags,
5970 GUnixFDList *fd_list,
5971 GUnixFDList **out_fd_list,
5972 GCancellable *cancellable,
5975 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);
5978 #endif /* G_OS_UNIX */
5980 /* ---------------------------------------------------------------------------------------------------- */
5982 struct ExportedSubtree
5986 GDBusConnection *connection;
5987 GDBusSubtreeVTable *vtable;
5988 GDBusSubtreeFlags flags;
5990 GMainContext *context;
5992 GDestroyNotify user_data_free_func;
5996 exported_subtree_free (ExportedSubtree *es)
5998 call_destroy_notify (es->context,
5999 es->user_data_free_func,
6002 g_main_context_unref (es->context);
6004 _g_dbus_subtree_vtable_free (es->vtable);
6005 g_free (es->object_path);
6009 /* called without lock held in the thread where the caller registered
6013 handle_subtree_introspect (GDBusConnection *connection,
6014 ExportedSubtree *es,
6015 GDBusMessage *message)
6019 GDBusMessage *reply;
6022 const gchar *sender;
6023 const gchar *requested_object_path;
6024 const gchar *requested_node;
6025 GDBusInterfaceInfo **interfaces;
6027 gchar **subnode_paths;
6028 gboolean has_properties_interface;
6029 gboolean has_introspectable_interface;
6033 requested_object_path = g_dbus_message_get_path (message);
6034 sender = g_dbus_message_get_sender (message);
6035 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6037 s = g_string_new (NULL);
6038 introspect_append_header (s);
6040 /* Strictly we don't need the children in dynamic mode, but we avoid the
6041 * conditionals to preserve code clarity
6043 children = es->vtable->enumerate (es->connection,
6050 requested_node = strrchr (requested_object_path, '/') + 1;
6052 /* Assert existence of object if we are not dynamic */
6053 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
6054 !_g_strv_has_string ((const gchar * const *) children, requested_node))
6059 requested_node = NULL;
6062 interfaces = es->vtable->introspect (es->connection,
6067 if (interfaces != NULL)
6069 has_properties_interface = FALSE;
6070 has_introspectable_interface = FALSE;
6072 for (n = 0; interfaces[n] != NULL; n++)
6074 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
6075 has_properties_interface = TRUE;
6076 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
6077 has_introspectable_interface = TRUE;
6079 if (!has_properties_interface)
6080 g_string_append (s, introspect_properties_interface);
6081 if (!has_introspectable_interface)
6082 g_string_append (s, introspect_introspectable_interface);
6084 for (n = 0; interfaces[n] != NULL; n++)
6086 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
6087 g_dbus_interface_info_unref (interfaces[n]);
6089 g_free (interfaces);
6092 /* then include <node> entries from the Subtree for the root */
6095 for (n = 0; children != NULL && children[n] != NULL; n++)
6096 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
6099 /* finally include nodes registered below us */
6100 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
6101 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
6102 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
6103 g_strfreev (subnode_paths);
6105 g_string_append (s, "</node>\n");
6107 reply = g_dbus_message_new_method_reply (message);
6108 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6109 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6110 g_object_unref (reply);
6115 g_string_free (s, TRUE);
6116 g_strfreev (children);
6120 /* called without lock held in the thread where the caller registered
6124 handle_subtree_method_invocation (GDBusConnection *connection,
6125 ExportedSubtree *es,
6126 GDBusMessage *message)
6129 const gchar *sender;
6130 const gchar *interface_name;
6131 const gchar *member;
6132 const gchar *signature;
6133 const gchar *requested_object_path;
6134 const gchar *requested_node;
6136 GDBusInterfaceInfo *interface_info;
6137 const GDBusInterfaceVTable *interface_vtable;
6138 gpointer interface_user_data;
6140 GDBusInterfaceInfo **interfaces;
6141 gboolean is_property_get;
6142 gboolean is_property_set;
6143 gboolean is_property_get_all;
6148 requested_object_path = g_dbus_message_get_path (message);
6149 sender = g_dbus_message_get_sender (message);
6150 interface_name = g_dbus_message_get_interface (message);
6151 member = g_dbus_message_get_member (message);
6152 signature = g_dbus_message_get_signature (message);
6153 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6155 is_property_get = FALSE;
6156 is_property_set = FALSE;
6157 is_property_get_all = FALSE;
6158 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6160 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6161 is_property_get = TRUE;
6162 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6163 is_property_set = TRUE;
6164 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6165 is_property_get_all = TRUE;
6170 requested_node = strrchr (requested_object_path, '/') + 1;
6172 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6174 /* We don't want to dispatch to unenumerated
6175 * nodes, so ensure that the child exists.
6180 children = es->vtable->enumerate (es->connection,
6185 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6186 g_strfreev (children);
6194 requested_node = NULL;
6197 /* get introspection data for the node */
6198 interfaces = es->vtable->introspect (es->connection,
6200 requested_object_path,
6204 if (interfaces == NULL)
6207 interface_info = NULL;
6208 for (n = 0; interfaces[n] != NULL; n++)
6210 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6211 interface_info = interfaces[n];
6214 /* dispatch the call if the user wants to handle it */
6215 if (interface_info != NULL)
6217 /* figure out where to dispatch the method call */
6218 interface_user_data = NULL;
6219 interface_vtable = es->vtable->dispatch (es->connection,
6224 &interface_user_data,
6226 if (interface_vtable == NULL)
6229 CONNECTION_LOCK (connection);
6230 handled = validate_and_maybe_schedule_method_call (es->connection,
6237 interface_user_data);
6238 CONNECTION_UNLOCK (connection);
6240 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6241 else if (is_property_get || is_property_set || is_property_get_all)
6243 if (is_property_get)
6244 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6245 else if (is_property_set)
6246 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6247 else if (is_property_get_all)
6248 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6250 g_assert_not_reached ();
6252 /* see if the object supports this interface at all */
6253 for (n = 0; interfaces[n] != NULL; n++)
6255 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6256 interface_info = interfaces[n];
6259 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6260 * claims it won't support the interface
6262 if (interface_info == NULL)
6264 GDBusMessage *reply;
6265 reply = g_dbus_message_new_method_error (message,
6266 "org.freedesktop.DBus.Error.InvalidArgs",
6267 _("No such interface '%s'"),
6269 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6270 g_object_unref (reply);
6275 /* figure out where to dispatch the property get/set/getall calls */
6276 interface_user_data = NULL;
6277 interface_vtable = es->vtable->dispatch (es->connection,
6282 &interface_user_data,
6284 if (interface_vtable == NULL)
6286 g_warning ("The subtree introspection function indicates that '%s' "
6287 "is a valid interface name, but calling the dispatch "
6288 "function on that interface gave us NULL", interface_name);
6292 if (is_property_get || is_property_set)
6294 CONNECTION_LOCK (connection);
6295 handled = validate_and_maybe_schedule_property_getset (es->connection,
6303 interface_user_data);
6304 CONNECTION_UNLOCK (connection);
6306 else if (is_property_get_all)
6308 CONNECTION_LOCK (connection);
6309 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6316 interface_user_data);
6317 CONNECTION_UNLOCK (connection);
6322 if (interfaces != NULL)
6324 for (n = 0; interfaces[n] != NULL; n++)
6325 g_dbus_interface_info_unref (interfaces[n]);
6326 g_free (interfaces);
6334 GDBusMessage *message;
6335 ExportedSubtree *es;
6336 } SubtreeDeferredData;
6339 subtree_deferred_data_free (SubtreeDeferredData *data)
6341 g_object_unref (data->message);
6345 /* called without lock held in the thread where the caller registered the subtree */
6347 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6349 SubtreeDeferredData *data = _data;
6354 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6355 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6356 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6357 handled = handle_subtree_introspect (data->es->connection,
6361 handled = handle_subtree_method_invocation (data->es->connection,
6367 CONNECTION_LOCK (data->es->connection);
6368 handled = handle_generic_unlocked (data->es->connection, data->message);
6369 CONNECTION_UNLOCK (data->es->connection);
6372 /* if we couldn't handle the request, just bail with the UnknownMethod error */
6375 GDBusMessage *reply;
6376 reply = g_dbus_message_new_method_error (data->message,
6377 "org.freedesktop.DBus.Error.UnknownMethod",
6378 _("Method '%s' on interface '%s' with signature '%s' does not exist"),
6379 g_dbus_message_get_member (data->message),
6380 g_dbus_message_get_interface (data->message),
6381 g_dbus_message_get_signature (data->message));
6382 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6383 g_object_unref (reply);
6389 /* called in GDBusWorker thread with connection's lock held */
6391 subtree_message_func (GDBusConnection *connection,
6392 ExportedSubtree *es,
6393 GDBusMessage *message)
6395 GSource *idle_source;
6396 SubtreeDeferredData *data;
6398 data = g_new0 (SubtreeDeferredData, 1);
6399 data->message = g_object_ref (message);
6402 /* defer this call to an idle handler in the right thread */
6403 idle_source = g_idle_source_new ();
6404 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
6405 g_source_set_callback (idle_source,
6406 process_subtree_vtable_message_in_idle_cb,
6408 (GDestroyNotify) subtree_deferred_data_free);
6409 g_source_set_name (idle_source, "[gio] process_subtree_vtable_message_in_idle_cb");
6410 g_source_attach (idle_source, es->context);
6411 g_source_unref (idle_source);
6413 /* since we own the entire subtree, handlers for objects not in the subtree have been
6414 * tried already by libdbus-1 - so we just need to ensure that we're always going
6415 * to reply to the message
6421 * g_dbus_connection_register_subtree:
6422 * @connection: a #GDBusConnection
6423 * @object_path: the object path to register the subtree at
6424 * @vtable: a #GDBusSubtreeVTable to enumerate, introspect and
6425 * dispatch nodes in the subtree
6426 * @flags: flags used to fine tune the behavior of the subtree
6427 * @user_data: data to pass to functions in @vtable
6428 * @user_data_free_func: function to call when the subtree is unregistered
6429 * @error: return location for error or %NULL
6431 * Registers a whole subtree of dynamic objects.
6433 * The @enumerate and @introspection functions in @vtable are used to
6434 * convey, to remote callers, what nodes exist in the subtree rooted
6437 * When handling remote calls into any node in the subtree, first the
6438 * @enumerate function is used to check if the node exists. If the node exists
6439 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6440 * the @introspection function is used to check if the node supports the
6441 * requested method. If so, the @dispatch function is used to determine
6442 * where to dispatch the call. The collected #GDBusInterfaceVTable and
6443 * #gpointer will be used to call into the interface vtable for processing
6446 * All calls into user-provided code will be invoked in the
6447 * [thread-default main context][g-main-context-push-thread-default]
6448 * of the thread you are calling this method from.
6450 * If an existing subtree is already registered at @object_path or
6451 * then @error is set to #G_IO_ERROR_EXISTS.
6453 * Note that it is valid to register regular objects (using
6454 * g_dbus_connection_register_object()) in a subtree registered with
6455 * g_dbus_connection_register_subtree() - if so, the subtree handler
6456 * is tried as the last resort. One way to think about a subtree
6457 * handler is to consider it a fallback handler for object paths not
6458 * registered via g_dbus_connection_register_object() or other bindings.
6460 * Note that @vtable will be copied so you cannot change it after
6463 * See this [server][gdbus-subtree-server] for an example of how to use
6466 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
6467 * that can be used with g_dbus_connection_unregister_subtree() .
6472 g_dbus_connection_register_subtree (GDBusConnection *connection,
6473 const gchar *object_path,
6474 const GDBusSubtreeVTable *vtable,
6475 GDBusSubtreeFlags flags,
6477 GDestroyNotify user_data_free_func,
6481 ExportedSubtree *es;
6483 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
6484 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
6485 g_return_val_if_fail (vtable != NULL, 0);
6486 g_return_val_if_fail (error == NULL || *error == NULL, 0);
6487 g_return_val_if_fail (check_initialized (connection), 0);
6491 CONNECTION_LOCK (connection);
6493 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6499 _("A subtree is already exported for %s"),
6504 es = g_new0 (ExportedSubtree, 1);
6505 es->object_path = g_strdup (object_path);
6506 es->connection = connection;
6508 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
6510 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
6511 es->user_data = user_data;
6512 es->user_data_free_func = user_data_free_func;
6513 es->context = g_main_context_ref_thread_default ();
6515 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
6516 g_hash_table_insert (connection->map_id_to_es,
6517 GUINT_TO_POINTER (es->id),
6523 CONNECTION_UNLOCK (connection);
6528 /* ---------------------------------------------------------------------------------------------------- */
6531 * g_dbus_connection_unregister_subtree:
6532 * @connection: a #GDBusConnection
6533 * @registration_id: a subtree registration id obtained from
6534 * g_dbus_connection_register_subtree()
6536 * Unregisters a subtree.
6538 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise
6543 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
6544 guint registration_id)
6546 ExportedSubtree *es;
6549 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
6550 g_return_val_if_fail (check_initialized (connection), FALSE);
6554 CONNECTION_LOCK (connection);
6556 es = g_hash_table_lookup (connection->map_id_to_es,
6557 GUINT_TO_POINTER (registration_id));
6561 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
6562 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
6567 CONNECTION_UNLOCK (connection);
6572 /* ---------------------------------------------------------------------------------------------------- */
6574 /* may be called in any thread, with connection's lock held */
6576 handle_generic_ping_unlocked (GDBusConnection *connection,
6577 const gchar *object_path,
6578 GDBusMessage *message)
6580 GDBusMessage *reply;
6581 reply = g_dbus_message_new_method_reply (message);
6582 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6583 g_object_unref (reply);
6586 /* may be called in any thread, with connection's lock held */
6588 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
6589 const gchar *object_path,
6590 GDBusMessage *message)
6592 GDBusMessage *reply;
6595 if (connection->machine_id == NULL)
6600 connection->machine_id = _g_dbus_get_machine_id (&error);
6601 if (connection->machine_id == NULL)
6603 reply = g_dbus_message_new_method_error_literal (message,
6604 "org.freedesktop.DBus.Error.Failed",
6606 g_error_free (error);
6612 reply = g_dbus_message_new_method_reply (message);
6613 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
6615 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6616 g_object_unref (reply);
6619 /* may be called in any thread, with connection's lock held */
6621 handle_generic_introspect_unlocked (GDBusConnection *connection,
6622 const gchar *object_path,
6623 GDBusMessage *message)
6628 GDBusMessage *reply;
6630 /* first the header */
6631 s = g_string_new (NULL);
6632 introspect_append_header (s);
6634 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
6635 for (n = 0; registered != NULL && registered[n] != NULL; n++)
6636 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
6637 g_strfreev (registered);
6638 g_string_append (s, "</node>\n");
6640 reply = g_dbus_message_new_method_reply (message);
6641 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6642 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6643 g_object_unref (reply);
6644 g_string_free (s, TRUE);
6647 /* may be called in any thread, with connection's lock held */
6649 handle_generic_unlocked (GDBusConnection *connection,
6650 GDBusMessage *message)
6653 const gchar *interface_name;
6654 const gchar *member;
6655 const gchar *signature;
6658 CONNECTION_ENSURE_LOCK (connection);
6662 interface_name = g_dbus_message_get_interface (message);
6663 member = g_dbus_message_get_member (message);
6664 signature = g_dbus_message_get_signature (message);
6665 path = g_dbus_message_get_path (message);
6667 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
6668 g_strcmp0 (member, "Introspect") == 0 &&
6669 g_strcmp0 (signature, "") == 0)
6671 handle_generic_introspect_unlocked (connection, path, message);
6674 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6675 g_strcmp0 (member, "Ping") == 0 &&
6676 g_strcmp0 (signature, "") == 0)
6678 handle_generic_ping_unlocked (connection, path, message);
6681 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6682 g_strcmp0 (member, "GetMachineId") == 0 &&
6683 g_strcmp0 (signature, "") == 0)
6685 handle_generic_get_machine_id_unlocked (connection, path, message);
6692 /* ---------------------------------------------------------------------------------------------------- */
6694 /* called in GDBusWorker thread with connection's lock held */
6696 distribute_method_call (GDBusConnection *connection,
6697 GDBusMessage *message)
6699 GDBusMessage *reply;
6701 ExportedSubtree *es;
6702 const gchar *object_path;
6703 const gchar *interface_name;
6704 const gchar *member;
6706 gchar *subtree_path;
6709 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
6711 interface_name = g_dbus_message_get_interface (message);
6712 member = g_dbus_message_get_member (message);
6713 path = g_dbus_message_get_path (message);
6714 subtree_path = g_strdup (path);
6715 needle = strrchr (subtree_path, '/');
6716 if (needle != NULL && needle != subtree_path)
6722 g_free (subtree_path);
6723 subtree_path = NULL;
6727 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
6729 _g_dbus_debug_print_lock ();
6730 g_print ("========================================================================\n"
6731 "GDBus-debug:Incoming:\n"
6732 " <<<< METHOD INVOCATION %s.%s()\n"
6734 " invoked by name %s\n"
6736 interface_name, member,
6738 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
6739 g_dbus_message_get_serial (message));
6740 _g_dbus_debug_print_unlock ();
6743 object_path = g_dbus_message_get_path (message);
6744 g_assert (object_path != NULL);
6746 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
6749 if (obj_message_func (connection, eo, message))
6753 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6756 if (subtree_message_func (connection, es, message))
6760 if (subtree_path != NULL)
6762 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
6765 if (subtree_message_func (connection, es, message))
6770 if (handle_generic_unlocked (connection, message))
6773 /* if we end up here, the message has not been not handled - so return an error saying this */
6774 reply = g_dbus_message_new_method_error (message,
6775 "org.freedesktop.DBus.Error.UnknownMethod",
6776 _("No such interface '%s' on object at path %s"),
6779 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6780 g_object_unref (reply);
6783 g_free (subtree_path);
6786 /* ---------------------------------------------------------------------------------------------------- */
6788 /* Called in any user thread, with the message_bus_lock held. */
6790 message_bus_get_singleton (GBusType bus_type,
6794 const gchar *starter_bus;
6800 case G_BUS_TYPE_SESSION:
6801 ret = &the_session_bus;
6804 case G_BUS_TYPE_SYSTEM:
6805 ret = &the_system_bus;
6808 case G_BUS_TYPE_STARTER:
6809 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
6810 if (g_strcmp0 (starter_bus, "session") == 0)
6812 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
6815 else if (g_strcmp0 (starter_bus, "system") == 0)
6817 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
6822 if (starter_bus != NULL)
6826 G_IO_ERROR_INVALID_ARGUMENT,
6827 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
6828 " - unknown value '%s'"),
6833 g_set_error_literal (error,
6835 G_IO_ERROR_INVALID_ARGUMENT,
6836 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
6837 "variable is not set"));
6843 g_assert_not_reached ();
6851 /* Called in any user thread, without holding locks. */
6852 static GDBusConnection *
6853 get_uninitialized_connection (GBusType bus_type,
6854 GCancellable *cancellable,
6857 GWeakRef *singleton;
6858 GDBusConnection *ret;
6862 G_LOCK (message_bus_lock);
6863 singleton = message_bus_get_singleton (bus_type, error);
6864 if (singleton == NULL)
6867 ret = g_weak_ref_get (singleton);
6872 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
6873 if (address == NULL)
6875 ret = g_object_new (G_TYPE_DBUS_CONNECTION,
6877 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
6878 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
6879 "exit-on-close", TRUE,
6882 g_weak_ref_set (singleton, ret);
6886 g_assert (ret != NULL);
6889 G_UNLOCK (message_bus_lock);
6893 /* May be called from any thread. Must not hold message_bus_lock. */
6895 _g_bus_get_singleton_if_exists (GBusType bus_type)
6897 GWeakRef *singleton;
6898 GDBusConnection *ret = NULL;
6900 G_LOCK (message_bus_lock);
6901 singleton = message_bus_get_singleton (bus_type, NULL);
6902 if (singleton == NULL)
6905 ret = g_weak_ref_get (singleton);
6908 G_UNLOCK (message_bus_lock);
6914 * @bus_type: a #GBusType
6915 * @cancellable: (allow-none): a #GCancellable or %NULL
6916 * @error: return location for error or %NULL
6918 * Synchronously connects to the message bus specified by @bus_type.
6919 * Note that the returned object may shared with other callers,
6920 * e.g. if two separate parts of a process calls this function with
6921 * the same @bus_type, they will share the same object.
6923 * This is a synchronous failable function. See g_bus_get() and
6924 * g_bus_get_finish() for the asynchronous version.
6926 * The returned object is a singleton, that is, shared with other
6927 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6928 * event that you need a private message bus connection, use
6929 * g_dbus_address_get_for_bus_sync() and
6930 * g_dbus_connection_new_for_address().
6932 * Note that the returned #GDBusConnection object will (usually) have
6933 * the #GDBusConnection:exit-on-close property set to %TRUE.
6935 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
6936 * Free with g_object_unref().
6941 g_bus_get_sync (GBusType bus_type,
6942 GCancellable *cancellable,
6945 GDBusConnection *connection;
6947 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6949 connection = get_uninitialized_connection (bus_type, cancellable, error);
6950 if (connection == NULL)
6953 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
6955 g_object_unref (connection);
6964 bus_get_async_initable_cb (GObject *source_object,
6968 GTask *task = user_data;
6969 GError *error = NULL;
6971 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
6975 g_assert (error != NULL);
6976 g_task_return_error (task, error);
6977 g_object_unref (source_object);
6981 g_task_return_pointer (task, source_object, g_object_unref);
6983 g_object_unref (task);
6988 * @bus_type: a #GBusType
6989 * @cancellable: (allow-none): a #GCancellable or %NULL
6990 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
6991 * @user_data: the data to pass to @callback
6993 * Asynchronously connects to the message bus specified by @bus_type.
6995 * When the operation is finished, @callback will be invoked. You can
6996 * then call g_bus_get_finish() to get the result of the operation.
6998 * This is a asynchronous failable function. See g_bus_get_sync() for
6999 * the synchronous version.
7004 g_bus_get (GBusType bus_type,
7005 GCancellable *cancellable,
7006 GAsyncReadyCallback callback,
7009 GDBusConnection *connection;
7011 GError *error = NULL;
7013 task = g_task_new (NULL, cancellable, callback, user_data);
7015 connection = get_uninitialized_connection (bus_type, cancellable, &error);
7016 if (connection == NULL)
7018 g_assert (error != NULL);
7019 g_task_return_error (task, error);
7020 g_object_unref (task);
7024 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
7027 bus_get_async_initable_cb,
7034 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
7036 * @error: return location for error or %NULL
7038 * Finishes an operation started with g_bus_get().
7040 * The returned object is a singleton, that is, shared with other
7041 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7042 * event that you need a private message bus connection, use
7043 * g_dbus_address_get_for_bus_sync() and
7044 * g_dbus_connection_new_for_address().
7046 * Note that the returned #GDBusConnection object will (usually) have
7047 * the #GDBusConnection:exit-on-close property set to %TRUE.
7049 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7050 * Free with g_object_unref().
7055 g_bus_get_finish (GAsyncResult *res,
7058 g_return_val_if_fail (g_task_is_valid (res, NULL), NULL);
7059 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7061 return g_task_propagate_pointer (G_TASK (res), error);
7064 /* ---------------------------------------------------------------------------------------------------- */