1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
18 * Author: David Zeuthen <davidz@redhat.com>
24 * - would be nice to expose GDBusAuthMechanism and an extension point
26 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
27 * the mechanism VFuncs need to be able to set an error.
29 * - Need to document other mechanisms/sources for determining the D-Bus
30 * address of a well-known bus.
32 * - e.g. on Win32 we need code like from here
34 * http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
36 * that was never copied over here because it originally was copy-paste
37 * from the GPLv2 / AFL 2.1 libdbus sources.
39 * - on OS X we need to look in launchd for the address
41 * https://bugs.freedesktop.org/show_bug.cgi?id=14259
43 * - on X11 we need to look in a X11 property on the X server
44 * - (we can also just use dbus-launch(1) from the D-Bus
47 * - (ideally) this requires D-Bus spec work because none of
48 * this has never really been specced out properly (except
51 * - Related to the above, we also need to be able to launch a message bus
52 * instance.... Since we don't want to write our own bus daemon we should
53 * launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
55 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
56 * to specify where the nonce is stored. This will allow people to use
57 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
58 * to easily achieve secure RPC via nonce-tcp.
60 * - need to expose an extension point for resolving D-Bus address and
61 * turning them into GIOStream objects. This will allow us to implement
62 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
64 * - see g_dbus_address_connect() in gdbusaddress.c
66 * - would be cute to use kernel-specific APIs to resolve fds for
67 * debug output when using G_DBUS_DEBUG=message, e.g. in addition to
69 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
71 * maybe we can show more information about what fd 21 really is.
72 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
73 * Initial experiments on Linux 2.6 suggests that the symlink looks
78 * e.g. not of much use.
80 * - GDBus High-Level docs
81 * - Proxy: properties, signals...
82 * - Connection: IOStream based, ::close, connection setup steps
83 * mainloop integration, threading
84 * - Differences from libdbus (extend "Migrating from")
85 * - the message handling thread
86 * - Using GVariant instead of GValue
87 * - Explain why the high-level API is a good thing and what
88 * kind of pitfalls it avoids
89 * - Export objects before claiming names
90 * - Talk about auto-starting services (cf. GBusNameWatcherFlags)
92 * - use abstract sockets in test code
93 * - right now it doesn't work, dbus-daemon(1) fails with
95 * /gdbus/connection/filter: Failed to start message bus: Failed to bind
96 * socket "/tmp/g-dbus-tests-pid-28531": Address already in use
97 * ** WARNING **: Error reading address from dbus daemon, 0 bytes read
107 #include "gdbusauth.h"
108 #include "gdbusutils.h"
109 #include "gdbusaddress.h"
110 #include "gdbusmessage.h"
111 #include "gdbusconnection.h"
112 #include "gdbuserror.h"
113 #include "gioenumtypes.h"
114 #include "gdbusintrospection.h"
115 #include "gdbusmethodinvocation.h"
116 #include "gdbusprivate.h"
117 #include "gdbusauthobserver.h"
118 #include "ginitable.h"
119 #include "gasyncinitable.h"
120 #include "giostream.h"
121 #include "gasyncresult.h"
122 #include "gsimpleasyncresult.h"
126 #include "gunixconnection.h"
127 #include "gunixfdmessage.h"
130 #include "glibintl.h"
133 * SECTION:gdbusconnection
134 * @short_description: D-Bus Connections
135 * @include: gio/gio.h
137 * The #GDBusConnection type is used for D-Bus connections to remote
138 * peers such as a message buses. It is a low-level API that offers a
139 * lot of flexibility. For instance, it lets you establish a connection
140 * over any transport that can by represented as an #GIOStream.
142 * This class is rarely used directly in D-Bus clients. If you are writing
143 * a D-Bus client, it is often easier to use the g_bus_own_name(),
144 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
146 * As an exception to the usual GLib rule that a particular object must not
147 * be used by two threads at the same time, #GDBusConnection's methods may be
148 * called from any thread. This is so that g_bus_get() and g_bus_get_sync()
149 * can safely return the same #GDBusConnection when called from any thread.
151 * Most of the ways to obtain a #GDBusConnection automatically initialize it
152 * (i.e. connect to D-Bus): for instance, g_dbus_connection_new() and
153 * g_bus_get(), and the synchronous versions of those methods, give you an
154 * initialized connection. Language bindings for GIO should use
155 * g_initable_new() or g_async_initable_new_async(), which also initialize the
158 * If you construct an uninitialized #GDBusConnection, such as via
159 * g_object_new(), you must initialize it via g_initable_init() or
160 * g_async_initable_init_async() before using its methods or properties.
161 * Calling methods or accessing properties on a #GDBusConnection that has not
162 * completed initialization successfully is considered to be invalid, and leads
163 * to undefined behaviour. In particular, if initialization fails with a
164 * #GError, the only valid thing you can do with that #GDBusConnection is to
165 * free it with g_object_unref().
167 * ## An example D-Bus server # {#gdbus-server}
169 * Here is an example for a D-Bus server:
170 * [gdbus-example-server.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-server.c)
172 * ## An example for exporting a subtree # {#gdbus-subtree-server}
174 * Here is an example for exporting a subtree:
175 * [gdbus-example-subtree.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-subtree.c)
177 * ## An example for file descriptor passing # {#gdbus-unix-fd-client}
179 * Here is an example for passing UNIX file descriptors:
180 * [gdbus-unix-fd-client.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-unix-fd-client.c)
182 * ## An example for exporting a GObject # {#gdbus-export}
184 * Here is an example for exporting a #GObject:
185 * [gdbus-example-export.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-export.c)
188 /* ---------------------------------------------------------------------------------------------------- */
190 typedef struct _GDBusConnectionClass GDBusConnectionClass;
193 * GDBusConnectionClass:
194 * @closed: Signal class handler for the #GDBusConnection::closed signal.
196 * Class structure for #GDBusConnection.
200 struct _GDBusConnectionClass
203 GObjectClass parent_class;
207 void (*closed) (GDBusConnection *connection,
208 gboolean remote_peer_vanished,
212 G_LOCK_DEFINE_STATIC (message_bus_lock);
214 static GWeakRef the_session_bus;
215 static GWeakRef the_system_bus;
216 static GWeakRef the_user_bus;
217 static GWeakRef the_machine_bus;
219 /* Extra pseudo-member of GDBusSendMessageFlags.
220 * Set by initable_init() to indicate that despite not being initialized yet,
221 * enough of the only-valid-after-init members are set that we can send a
222 * message, and we're being called from its thread, so no memory barrier is
223 * required before accessing them.
225 #define SEND_MESSAGE_FLAGS_INITIALIZING (1<<31)
227 /* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
228 #define CALL_FLAGS_INITIALIZING (1<<31)
230 /* ---------------------------------------------------------------------------------------------------- */
234 GDestroyNotify callback;
236 GMainContext *context;
237 } CallDestroyNotifyData;
240 call_destroy_notify_data_in_idle (gpointer user_data)
242 CallDestroyNotifyData *data = user_data;
243 data->callback (data->user_data);
248 call_destroy_notify_data_free (CallDestroyNotifyData *data)
250 if (data->context != NULL)
251 g_main_context_unref (data->context);
256 * call_destroy_notify: <internal>
257 * @context: (allow-none): A #GMainContext or %NULL.
258 * @callback: (allow-none): A #GDestroyNotify or %NULL.
259 * @user_data: Data to pass to @callback.
261 * Schedules @callback to run in @context.
264 call_destroy_notify (GMainContext *context,
265 GDestroyNotify callback,
268 GSource *idle_source;
269 CallDestroyNotifyData *data;
271 if (callback == NULL)
274 data = g_new0 (CallDestroyNotifyData, 1);
275 data->callback = callback;
276 data->user_data = user_data;
277 data->context = context;
278 if (data->context != NULL)
279 g_main_context_ref (data->context);
281 idle_source = g_idle_source_new ();
282 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
283 g_source_set_callback (idle_source,
284 call_destroy_notify_data_in_idle,
286 (GDestroyNotify) call_destroy_notify_data_free);
287 g_source_set_name (idle_source, "[gio] call_destroy_notify_data_in_idle");
288 g_source_attach (idle_source, data->context);
289 g_source_unref (idle_source);
295 /* ---------------------------------------------------------------------------------------------------- */
298 _g_strv_has_string (const gchar* const *haystack,
303 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
305 if (g_strcmp0 (haystack[n], needle) == 0)
311 /* ---------------------------------------------------------------------------------------------------- */
314 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
316 // TODO: for some reason this doesn't work on Windows
317 #define CONNECTION_ENSURE_LOCK(obj) do { \
318 if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock))) \
320 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
321 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
326 #define CONNECTION_LOCK(obj) do { \
327 g_mutex_lock (&(obj)->lock); \
330 #define CONNECTION_UNLOCK(obj) do { \
331 g_mutex_unlock (&(obj)->lock); \
334 /* Flags in connection->atomic_flags */
336 FLAG_INITIALIZED = 1 << 0,
337 FLAG_EXIT_ON_CLOSE = 1 << 1,
344 * The #GDBusConnection structure contains only private data and
345 * should only be accessed using the provided API.
349 struct _GDBusConnection
352 GObject parent_instance;
354 /* ------------------------------------------------------------------------ */
355 /* -- General object state ------------------------------------------------ */
356 /* ------------------------------------------------------------------------ */
358 /* General-purpose lock for most fields */
361 /* A lock used in the init() method of the GInitable interface - see comments
362 * in initable_init() for why a separate lock is needed.
364 * If you need both @lock and @init_lock, you must take @init_lock first.
368 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
369 * someone calls org.freedesktop.DBus.Peer.GetMachineId(). Protected by @lock.
373 /* The underlying stream used for communication
374 * Read-only after initable_init(), so it may be read if you either
375 * hold @init_lock or check for initialization first.
379 /* The object used for authentication (if any).
380 * Read-only after initable_init(), so it may be read if you either
381 * hold @init_lock or check for initialization first.
385 /* Last serial used. Protected by @lock. */
388 /* The object used to send/receive messages.
389 * Read-only after initable_init(), so it may be read if you either
390 * hold @init_lock or check for initialization first.
393 GKDBusWorker *kdbus_worker;
395 /* If connected to a message bus, this contains the unique name assigned to
396 * us by the bus (e.g. ":1.42").
397 * Read-only after initable_init(), so it may be read if you either
398 * hold @init_lock or check for initialization first.
400 gchar *bus_unique_name;
402 /* The GUID returned by the other side if we authenticed as a client or
403 * the GUID to use if authenticating as a server.
404 * Read-only after initable_init(), so it may be read if you either
405 * hold @init_lock or check for initialization first.
409 /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
410 * Inspect @initialization_error to see whether it succeeded or failed.
412 * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
414 * FLAG_CLOSED is the closed property. It may be read at any time, but
415 * may only be written while holding @lock.
417 volatile gint atomic_flags;
419 /* If the connection could not be established during initable_init(),
420 * this GError will be set.
421 * Read-only after initable_init(), so it may be read if you either
422 * hold @init_lock or check for initialization first.
424 GError *initialization_error;
426 /* The result of g_main_context_ref_thread_default() when the object
427 * was created (the GObject _init() function) - this is used for delivery
428 * of the :closed GObject signal.
430 * Only set in the GObject init function, so no locks are needed.
432 GMainContext *main_context_at_construction;
434 /* Read-only construct properties, no locks needed */
436 GDBusConnectionFlags flags;
438 /* Map used for managing method replies, protected by @lock */
439 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
441 /* Maps used for managing signal subscription, protected by @lock */
442 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
443 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
444 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
446 /* Maps used for managing exported objects and subtrees,
449 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
450 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
451 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
452 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
454 /* Map used for storing last used serials for each thread, protected by @lock */
455 GHashTable *map_thread_to_last_serial;
457 /* Structure used for message filters, protected by @lock */
460 /* Capabilities negotiated during authentication
461 * Read-only after initable_init(), so it may be read without holding a
462 * lock, if you check for initialization first.
464 GDBusCapabilityFlags capabilities;
466 /* Protected by @init_lock */
467 GDBusAuthObserver *authentication_observer;
469 /* Read-only after initable_init(), so it may be read if you either
470 * hold @init_lock or check for initialization first.
472 GCredentials *credentials;
474 /* set to TRUE when finalizing */
478 typedef struct ExportedObject ExportedObject;
479 static void exported_object_free (ExportedObject *eo);
481 typedef struct ExportedSubtree ExportedSubtree;
482 static void exported_subtree_free (ExportedSubtree *es);
500 PROP_CAPABILITY_FLAGS,
501 PROP_AUTHENTICATION_OBSERVER,
504 static void distribute_signals (GDBusConnection *connection,
505 GDBusMessage *message);
507 static void distribute_method_call (GDBusConnection *connection,
508 GDBusMessage *message);
510 static gboolean handle_generic_unlocked (GDBusConnection *connection,
511 GDBusMessage *message);
514 static void purge_all_signal_subscriptions (GDBusConnection *connection);
515 static void purge_all_filters (GDBusConnection *connection);
517 static void schedule_method_call (GDBusConnection *connection,
518 GDBusMessage *message,
519 guint registration_id,
520 guint subtree_registration_id,
521 const GDBusInterfaceInfo *interface_info,
522 const GDBusMethodInfo *method_info,
523 const GDBusPropertyInfo *property_info,
524 GVariant *parameters,
525 const GDBusInterfaceVTable *vtable,
526 GMainContext *main_context,
529 #define _G_ENSURE_LOCK(name) do { \
530 if (G_UNLIKELY (G_TRYLOCK(name))) \
532 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
533 "_G_ENSURE_LOCK: Lock '" #name "' is not locked"); \
537 static guint signals[LAST_SIGNAL] = { 0 };
539 static void initable_iface_init (GInitableIface *initable_iface);
540 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
542 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
543 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
544 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
548 * Check that all members of @connection that can only be accessed after
549 * the connection is initialized can safely be accessed. If not,
550 * log a critical warning. This function is a memory barrier.
552 * Returns: %TRUE if initialized
555 check_initialized (GDBusConnection *connection)
557 /* The access to @atomic_flags isn't conditional, so that this function
558 * provides a memory barrier for thread-safety even if checks are disabled.
559 * (If you don't want this stricter guarantee, you can call
560 * g_return_if_fail (check_initialized (c)).)
562 * This isn't strictly necessary now that we've decided use of an
563 * uninitialized GDBusConnection is undefined behaviour, but it seems
564 * better to be as deterministic as is feasible.
566 * (Anything that could suffer a crash from seeing undefined values
567 * must have a race condition - thread A initializes the connection while
568 * thread B calls a method without initialization, hoping that thread A will
569 * win the race - so its behaviour is undefined anyway.)
571 gint flags = g_atomic_int_get (&connection->atomic_flags);
573 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
575 /* We can safely access this, due to the memory barrier above */
576 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
582 MAY_BE_UNINITIALIZED = (1<<1)
583 } CheckUnclosedFlags;
586 * Check the same thing as check_initialized(), and also that the
587 * connection is not closed. If the connection is uninitialized,
588 * raise a critical warning (it's programmer error); if it's closed,
589 * raise a recoverable GError (it's a runtime error).
591 * This function is a memory barrier.
593 * Returns: %TRUE if initialized and not closed
596 check_unclosed (GDBusConnection *connection,
597 CheckUnclosedFlags check,
600 /* check_initialized() is effectively inlined, so we don't waste time
601 * doing two memory barriers
603 gint flags = g_atomic_int_get (&connection->atomic_flags);
605 if (!(check & MAY_BE_UNINITIALIZED))
607 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
608 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
611 if (flags & FLAG_CLOSED)
613 g_set_error_literal (error,
616 _("The connection is closed"));
623 static GHashTable *alive_connections = NULL;
626 g_dbus_connection_dispose (GObject *object)
628 GDBusConnection *connection = G_DBUS_CONNECTION (object);
630 G_LOCK (message_bus_lock);
631 CONNECTION_LOCK (connection);
632 if (connection->worker != NULL)
634 _g_dbus_worker_stop (connection->worker);
635 connection->worker = NULL;
636 if (alive_connections != NULL)
637 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
641 if (alive_connections != NULL)
642 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
644 CONNECTION_UNLOCK (connection);
645 G_UNLOCK (message_bus_lock);
647 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
648 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
652 g_dbus_connection_finalize (GObject *object)
654 GDBusConnection *connection = G_DBUS_CONNECTION (object);
656 connection->finalizing = TRUE;
658 purge_all_signal_subscriptions (connection);
660 purge_all_filters (connection);
661 g_ptr_array_unref (connection->filters);
663 if (connection->authentication_observer != NULL)
664 g_object_unref (connection->authentication_observer);
666 if (connection->auth != NULL)
667 g_object_unref (connection->auth);
669 if (connection->credentials)
670 g_object_unref (connection->credentials);
672 if (connection->stream != NULL)
674 g_object_unref (connection->stream);
675 connection->stream = NULL;
678 g_free (connection->address);
680 g_free (connection->guid);
681 g_free (connection->bus_unique_name);
683 if (connection->initialization_error != NULL)
684 g_error_free (connection->initialization_error);
686 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
688 g_hash_table_unref (connection->map_rule_to_signal_data);
689 g_hash_table_unref (connection->map_id_to_signal_data);
690 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
692 g_hash_table_unref (connection->map_id_to_ei);
693 g_hash_table_unref (connection->map_object_path_to_eo);
694 g_hash_table_unref (connection->map_id_to_es);
695 g_hash_table_unref (connection->map_object_path_to_es);
697 g_hash_table_unref (connection->map_thread_to_last_serial);
699 g_main_context_unref (connection->main_context_at_construction);
701 g_free (connection->machine_id);
703 g_mutex_clear (&connection->init_lock);
704 g_mutex_clear (&connection->lock);
706 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
709 /* called in any user thread, with the connection's lock not held */
711 g_dbus_connection_get_property (GObject *object,
716 GDBusConnection *connection = G_DBUS_CONNECTION (object);
721 g_value_set_object (value, g_dbus_connection_get_stream (connection));
725 g_value_set_string (value, g_dbus_connection_get_guid (connection));
728 case PROP_UNIQUE_NAME:
729 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
733 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
736 case PROP_EXIT_ON_CLOSE:
737 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
740 case PROP_CAPABILITY_FLAGS:
741 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
745 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
750 /* called in any user thread, with the connection's lock not held */
752 g_dbus_connection_set_property (GObject *object,
757 GDBusConnection *connection = G_DBUS_CONNECTION (object);
762 connection->stream = g_value_dup_object (value);
766 connection->guid = g_value_dup_string (value);
770 connection->address = g_value_dup_string (value);
774 connection->flags = g_value_get_flags (value);
777 case PROP_EXIT_ON_CLOSE:
778 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
781 case PROP_AUTHENTICATION_OBSERVER:
782 connection->authentication_observer = g_value_dup_object (value);
786 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
791 /* Base-class implementation of GDBusConnection::closed.
793 * Called in a user thread, by the main context that was thread-default when
794 * the object was constructed.
797 g_dbus_connection_real_closed (GDBusConnection *connection,
798 gboolean remote_peer_vanished,
801 gint flags = g_atomic_int_get (&connection->atomic_flags);
803 /* Because atomic int access is a memory barrier, we can safely read
804 * initialization_error without a lock, as long as we do it afterwards.
806 if (remote_peer_vanished &&
807 (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
808 (flags & FLAG_INITIALIZED) != 0 &&
809 connection->initialization_error == NULL)
813 g_printerr ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
816 g_quark_to_string (error->domain), error->code);
820 g_printerr ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
827 g_dbus_connection_class_init (GDBusConnectionClass *klass)
829 GObjectClass *gobject_class;
831 gobject_class = G_OBJECT_CLASS (klass);
833 gobject_class->finalize = g_dbus_connection_finalize;
834 gobject_class->dispose = g_dbus_connection_dispose;
835 gobject_class->set_property = g_dbus_connection_set_property;
836 gobject_class->get_property = g_dbus_connection_get_property;
838 klass->closed = g_dbus_connection_real_closed;
841 * GDBusConnection:stream:
843 * The underlying #GIOStream used for I/O.
845 * If this is passed on construction and is a #GSocketConnection,
846 * then the corresponding #GSocket will be put into non-blocking mode.
848 * While the #GDBusConnection is active, it will interact with this
849 * stream from a worker thread, so it is not safe to interact with
850 * the stream directly.
854 g_object_class_install_property (gobject_class,
856 g_param_spec_object ("stream",
858 P_("The underlying streams used for I/O"),
862 G_PARAM_CONSTRUCT_ONLY |
863 G_PARAM_STATIC_NAME |
864 G_PARAM_STATIC_BLURB |
865 G_PARAM_STATIC_NICK));
868 * GDBusConnection:address:
870 * A D-Bus address specifying potential endpoints that can be used
871 * when establishing the connection.
875 g_object_class_install_property (gobject_class,
877 g_param_spec_string ("address",
879 P_("D-Bus address specifying potential socket endpoints"),
882 G_PARAM_CONSTRUCT_ONLY |
883 G_PARAM_STATIC_NAME |
884 G_PARAM_STATIC_BLURB |
885 G_PARAM_STATIC_NICK));
888 * GDBusConnection:flags:
890 * Flags from the #GDBusConnectionFlags enumeration.
894 g_object_class_install_property (gobject_class,
896 g_param_spec_flags ("flags",
899 G_TYPE_DBUS_CONNECTION_FLAGS,
900 G_DBUS_CONNECTION_FLAGS_NONE,
902 G_PARAM_CONSTRUCT_ONLY |
903 G_PARAM_STATIC_NAME |
904 G_PARAM_STATIC_BLURB |
905 G_PARAM_STATIC_NICK));
908 * GDBusConnection:guid:
910 * The GUID of the peer performing the role of server when
913 * If you are constructing a #GDBusConnection and pass
914 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
915 * #GDBusConnection:flags property then you MUST also set this
916 * property to a valid guid.
918 * If you are constructing a #GDBusConnection and pass
919 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
920 * #GDBusConnection:flags property you will be able to read the GUID
921 * of the other peer here after the connection has been successfully
926 g_object_class_install_property (gobject_class,
928 g_param_spec_string ("guid",
930 P_("GUID of the server peer"),
934 G_PARAM_CONSTRUCT_ONLY |
935 G_PARAM_STATIC_NAME |
936 G_PARAM_STATIC_BLURB |
937 G_PARAM_STATIC_NICK));
940 * GDBusConnection:unique-name:
942 * The unique name as assigned by the message bus or %NULL if the
943 * connection is not open or not a message bus connection.
947 g_object_class_install_property (gobject_class,
949 g_param_spec_string ("unique-name",
951 P_("Unique name of bus connection"),
954 G_PARAM_STATIC_NAME |
955 G_PARAM_STATIC_BLURB |
956 G_PARAM_STATIC_NICK));
959 * GDBusConnection:closed:
961 * A boolean specifying whether the connection has been closed.
965 g_object_class_install_property (gobject_class,
967 g_param_spec_boolean ("closed",
969 P_("Whether the connection is closed"),
972 G_PARAM_STATIC_NAME |
973 G_PARAM_STATIC_BLURB |
974 G_PARAM_STATIC_NICK));
977 * GDBusConnection:exit-on-close:
979 * A boolean specifying whether the process will be terminated (by
980 * calling `raise(SIGTERM)`) if the connection is closed by the
983 * Note that #GDBusConnection objects returned by g_bus_get_finish()
984 * and g_bus_get_sync() will (usually) have this property set to %TRUE.
988 g_object_class_install_property (gobject_class,
990 g_param_spec_boolean ("exit-on-close",
992 P_("Whether the process is terminated when the connection is closed"),
996 G_PARAM_STATIC_NAME |
997 G_PARAM_STATIC_BLURB |
998 G_PARAM_STATIC_NICK));
1001 * GDBusConnection:capabilities:
1003 * Flags from the #GDBusCapabilityFlags enumeration
1004 * representing connection features negotiated with the other peer.
1008 g_object_class_install_property (gobject_class,
1009 PROP_CAPABILITY_FLAGS,
1010 g_param_spec_flags ("capabilities",
1013 G_TYPE_DBUS_CAPABILITY_FLAGS,
1014 G_DBUS_CAPABILITY_FLAGS_NONE,
1016 G_PARAM_STATIC_NAME |
1017 G_PARAM_STATIC_BLURB |
1018 G_PARAM_STATIC_NICK));
1021 * GDBusConnection:authentication-observer:
1023 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
1027 g_object_class_install_property (gobject_class,
1028 PROP_AUTHENTICATION_OBSERVER,
1029 g_param_spec_object ("authentication-observer",
1030 P_("Authentication Observer"),
1031 P_("Object used to assist in the authentication process"),
1032 G_TYPE_DBUS_AUTH_OBSERVER,
1034 G_PARAM_CONSTRUCT_ONLY |
1035 G_PARAM_STATIC_NAME |
1036 G_PARAM_STATIC_BLURB |
1037 G_PARAM_STATIC_NICK));
1040 * GDBusConnection::closed:
1041 * @connection: the #GDBusConnection emitting the signal
1042 * @remote_peer_vanished: %TRUE if @connection is closed because the
1043 * remote peer closed its end of the connection
1044 * @error: (allow-none): a #GError with more details about the event or %NULL
1046 * Emitted when the connection is closed.
1048 * The cause of this event can be
1050 * - If g_dbus_connection_close() is called. In this case
1051 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
1053 * - If the remote peer closes the connection. In this case
1054 * @remote_peer_vanished is set to %TRUE and @error is set.
1056 * - If the remote peer sends invalid or malformed data. In this
1057 * case @remote_peer_vanished is set to %FALSE and @error is set.
1059 * Upon receiving this signal, you should give up your reference to
1060 * @connection. You are guaranteed that this signal is emitted only
1065 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
1066 G_TYPE_DBUS_CONNECTION,
1068 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1079 g_dbus_connection_init (GDBusConnection *connection)
1081 g_mutex_init (&connection->lock);
1082 g_mutex_init (&connection->init_lock);
1084 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
1086 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1088 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1090 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1093 (GDestroyNotify) g_ptr_array_unref);
1095 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1098 (GDestroyNotify) exported_object_free);
1100 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1103 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1106 (GDestroyNotify) exported_subtree_free);
1108 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1111 connection->map_thread_to_last_serial = g_hash_table_new (g_direct_hash,
1114 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1116 connection->filters = g_ptr_array_new ();
1120 * g_dbus_connection_get_stream:
1121 * @connection: a #GDBusConnection
1123 * Gets the underlying stream used for IO.
1125 * While the #GDBusConnection is active, it will interact with this
1126 * stream from a worker thread, so it is not safe to interact with
1127 * the stream directly.
1129 * Returns: (transfer none): the stream used for IO
1134 g_dbus_connection_get_stream (GDBusConnection *connection)
1136 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1138 /* do not use g_return_val_if_fail(), we want the memory barrier */
1139 if (!check_initialized (connection))
1142 return connection->stream;
1146 * g_dbus_connection_start_message_processing:
1147 * @connection: a #GDBusConnection
1149 * If @connection was created with
1150 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1151 * starts processing messages. Does nothing on if @connection wasn't
1152 * created with this flag or if the method has already been called.
1157 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1159 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1161 /* do not use g_return_val_if_fail(), we want the memory barrier */
1162 if (!check_initialized (connection))
1165 g_assert (connection->worker || connection->kdbus_worker);
1167 if (connection->kdbus_worker)
1168 g_kdbus_worker_unfreeze (connection->kdbus_worker);
1170 _g_dbus_worker_unfreeze (connection->worker);
1174 * g_dbus_connection_is_closed:
1175 * @connection: a #GDBusConnection
1177 * Gets whether @connection is closed.
1179 * Returns: %TRUE if the connection is closed, %FALSE otherwise
1184 g_dbus_connection_is_closed (GDBusConnection *connection)
1188 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1190 flags = g_atomic_int_get (&connection->atomic_flags);
1192 return (flags & FLAG_CLOSED) ? TRUE : FALSE;
1196 * g_dbus_connection_get_capabilities:
1197 * @connection: a #GDBusConnection
1199 * Gets the capabilities negotiated with the remote peer
1201 * Returns: zero or more flags from the #GDBusCapabilityFlags enumeration
1205 GDBusCapabilityFlags
1206 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1208 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1210 /* do not use g_return_val_if_fail(), we want the memory barrier */
1211 if (!check_initialized (connection))
1212 return G_DBUS_CAPABILITY_FLAGS_NONE;
1214 return connection->capabilities;
1217 /* ---------------------------------------------------------------------------------------------------- */
1219 /* Called in a temporary thread without holding locks. */
1221 flush_in_thread_func (GSimpleAsyncResult *res,
1223 GCancellable *cancellable)
1228 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1231 g_simple_async_result_take_error (res, error);
1235 * g_dbus_connection_flush:
1236 * @connection: a #GDBusConnection
1237 * @cancellable: (allow-none): a #GCancellable or %NULL
1238 * @callback: (allow-none): a #GAsyncReadyCallback to call when the
1239 * request is satisfied or %NULL if you don't care about the result
1240 * @user_data: The data to pass to @callback
1242 * Asynchronously flushes @connection, that is, writes all queued
1243 * outgoing message to the transport and then flushes the transport
1244 * (using g_output_stream_flush_async()). This is useful in programs
1245 * that wants to emit a D-Bus signal and then exit immediately. Without
1246 * flushing the connection, there is no guaranteed that the message has
1247 * been sent to the networking buffers in the OS kernel.
1249 * This is an asynchronous method. When the operation is finished,
1250 * @callback will be invoked in the
1251 * [thread-default main context][g-main-context-push-thread-default]
1252 * of the thread you are calling this method from. You can
1253 * then call g_dbus_connection_flush_finish() to get the result of the
1254 * operation. See g_dbus_connection_flush_sync() for the synchronous
1260 g_dbus_connection_flush (GDBusConnection *connection,
1261 GCancellable *cancellable,
1262 GAsyncReadyCallback callback,
1265 GSimpleAsyncResult *simple;
1267 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1269 simple = g_simple_async_result_new (G_OBJECT (connection),
1272 g_dbus_connection_flush);
1273 g_simple_async_result_set_check_cancellable (simple, cancellable);
1274 g_simple_async_result_run_in_thread (simple,
1275 flush_in_thread_func,
1278 g_object_unref (simple);
1282 * g_dbus_connection_flush_finish:
1283 * @connection: a #GDBusConnection
1284 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1285 * to g_dbus_connection_flush()
1286 * @error: return location for error or %NULL
1288 * Finishes an operation started with g_dbus_connection_flush().
1290 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1295 g_dbus_connection_flush_finish (GDBusConnection *connection,
1299 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1304 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1305 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1306 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1308 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1310 if (g_simple_async_result_propagate_error (simple, error))
1320 * g_dbus_connection_flush_sync:
1321 * @connection: a #GDBusConnection
1322 * @cancellable: (allow-none): a #GCancellable or %NULL
1323 * @error: return location for error or %NULL
1325 * Synchronously flushes @connection. The calling thread is blocked
1326 * until this is done. See g_dbus_connection_flush() for the
1327 * asynchronous version of this method and more details about what it
1330 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1335 g_dbus_connection_flush_sync (GDBusConnection *connection,
1336 GCancellable *cancellable,
1341 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1342 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1346 /* This is only a best-effort attempt to see whether the connection is
1347 * closed, so it doesn't need the lock. If the connection closes just
1348 * after this check, but before scheduling the flush operation, the
1349 * result will be more or less the same as if the connection closed while
1350 * the flush operation was pending - it'll fail with either CLOSED or
1353 if (!check_unclosed (connection, 0, error))
1356 g_assert (connection->worker != NULL);
1358 ret = _g_dbus_worker_flush_sync (connection->worker,
1366 /* ---------------------------------------------------------------------------------------------------- */
1370 GDBusConnection *connection;
1372 gboolean remote_peer_vanished;
1376 emit_closed_data_free (EmitClosedData *data)
1378 g_object_unref (data->connection);
1379 if (data->error != NULL)
1380 g_error_free (data->error);
1384 /* Called in a user thread that has acquired the main context that was
1385 * thread-default when the object was constructed
1388 emit_closed_in_idle (gpointer user_data)
1390 EmitClosedData *data = user_data;
1393 g_object_notify (G_OBJECT (data->connection), "closed");
1394 g_signal_emit (data->connection,
1395 signals[CLOSED_SIGNAL],
1397 data->remote_peer_vanished,
1403 /* Can be called from any thread, must hold lock.
1404 * FLAG_CLOSED must already have been set.
1407 schedule_closed_unlocked (GDBusConnection *connection,
1408 gboolean remote_peer_vanished,
1411 GSource *idle_source;
1412 EmitClosedData *data;
1414 CONNECTION_ENSURE_LOCK (connection);
1416 data = g_new0 (EmitClosedData, 1);
1417 data->connection = g_object_ref (connection);
1418 data->remote_peer_vanished = remote_peer_vanished;
1419 data->error = error != NULL ? g_error_copy (error) : NULL;
1421 idle_source = g_idle_source_new ();
1422 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1423 g_source_set_callback (idle_source,
1424 emit_closed_in_idle,
1426 (GDestroyNotify) emit_closed_data_free);
1427 g_source_set_name (idle_source, "[gio] emit_closed_in_idle");
1428 g_source_attach (idle_source, connection->main_context_at_construction);
1429 g_source_unref (idle_source);
1432 /* ---------------------------------------------------------------------------------------------------- */
1435 * g_dbus_connection_close:
1436 * @connection: a #GDBusConnection
1437 * @cancellable: (allow-none): a #GCancellable or %NULL
1438 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request is
1439 * satisfied or %NULL if you don't care about the result
1440 * @user_data: The data to pass to @callback
1442 * Closes @connection. Note that this never causes the process to
1443 * exit (this might only happen if the other end of a shared message
1444 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1446 * Once the connection is closed, operations such as sending a message
1447 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1448 * will not automatically flush the connection so queued messages may
1449 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1451 * If @connection is already closed, this method fails with
1452 * %G_IO_ERROR_CLOSED.
1454 * When @connection has been closed, the #GDBusConnection::closed
1455 * signal is emitted in the
1456 * [thread-default main context][g-main-context-push-thread-default]
1457 * of the thread that @connection was constructed in.
1459 * This is an asynchronous method. When the operation is finished,
1460 * @callback will be invoked in the
1461 * [thread-default main context][g-main-context-push-thread-default]
1462 * of the thread you are calling this method from. You can
1463 * then call g_dbus_connection_close_finish() to get the result of the
1464 * operation. See g_dbus_connection_close_sync() for the synchronous
1470 g_dbus_connection_close (GDBusConnection *connection,
1471 GCancellable *cancellable,
1472 GAsyncReadyCallback callback,
1475 GSimpleAsyncResult *simple;
1477 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1479 /* do not use g_return_val_if_fail(), we want the memory barrier */
1480 if (!check_initialized (connection))
1483 g_assert (connection->worker != NULL);
1485 simple = g_simple_async_result_new (G_OBJECT (connection),
1488 g_dbus_connection_close);
1489 g_simple_async_result_set_check_cancellable (simple, cancellable);
1490 _g_dbus_worker_close (connection->worker, cancellable, simple);
1491 g_object_unref (simple);
1495 * g_dbus_connection_close_finish:
1496 * @connection: a #GDBusConnection
1497 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1498 * to g_dbus_connection_close()
1499 * @error: return location for error or %NULL
1501 * Finishes an operation started with g_dbus_connection_close().
1503 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1508 g_dbus_connection_close_finish (GDBusConnection *connection,
1512 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1517 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1518 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1519 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1521 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1523 if (g_simple_async_result_propagate_error (simple, error))
1534 GAsyncResult *result;
1537 /* Can be called by any thread, without the connection lock */
1539 sync_close_cb (GObject *source_object,
1543 SyncCloseData *data = user_data;
1545 data->result = g_object_ref (res);
1546 g_main_loop_quit (data->loop);
1550 * g_dbus_connection_close_sync:
1551 * @connection: a #GDBusConnection
1552 * @cancellable: (allow-none): a #GCancellable or %NULL
1553 * @error: return location for error or %NULL
1555 * Synchronously closees @connection. The calling thread is blocked
1556 * until this is done. See g_dbus_connection_close() for the
1557 * asynchronous version of this method and more details about what it
1560 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1565 g_dbus_connection_close_sync (GDBusConnection *connection,
1566 GCancellable *cancellable,
1571 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1572 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1576 if (check_unclosed (connection, 0, error))
1578 GMainContext *context;
1581 context = g_main_context_new ();
1582 g_main_context_push_thread_default (context);
1583 data.loop = g_main_loop_new (context, TRUE);
1586 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1587 g_main_loop_run (data.loop);
1588 ret = g_dbus_connection_close_finish (connection, data.result, error);
1590 g_object_unref (data.result);
1591 g_main_loop_unref (data.loop);
1592 g_main_context_pop_thread_default (context);
1593 g_main_context_unref (context);
1599 /* ---------------------------------------------------------------------------------------------------- */
1602 * g_dbus_request_name:
1603 * @connection: a #GDBusConnection
1604 * @name: well-known bus name (name to request)
1605 * @flags: a set of flags from the GBusNameOwnerFlags enumeration
1606 * @error: return location for error or %NULL
1608 * Synchronously acquires name on the bus and returns status code.
1610 * The calling thread is blocked until a reply is received.
1612 * Returns: status code or %G_BUS_REQUEST_NAME_FLAGS_ERROR
1617 GBusRequestNameReplyFlags
1618 g_dbus_request_name (GDBusConnection *connection,
1620 GBusNameOwnerFlags flags,
1624 guint32 request_name_reply;
1626 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_BUS_RELEASE_NAME_FLAGS_ERROR);
1627 g_return_val_if_fail (g_dbus_is_name (name) && !g_dbus_is_unique_name (name), G_BUS_RELEASE_NAME_FLAGS_ERROR);
1628 g_return_val_if_fail (error == NULL || *error == NULL, G_BUS_RELEASE_NAME_FLAGS_ERROR);
1630 if (connection->kdbus_worker)
1631 result = _g_kdbus_RequestName (connection->kdbus_worker, name, flags, error);
1633 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/org/freedesktop/DBus",
1634 "org.freedesktop.DBus", "RequestName",
1635 g_variant_new ("(su)", name, flags), G_VARIANT_TYPE ("(u)"),
1636 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1640 g_variant_get (result, "(u)", &request_name_reply);
1641 g_variant_unref (result);
1644 request_name_reply = G_BUS_REQUEST_NAME_FLAGS_ERROR;
1646 return (GBusRequestNameReplyFlags) request_name_reply;
1650 * g_dbus_release_name:
1651 * @connection: a #GDBusConnection
1652 * @name: well-known bus name (name to release)
1653 * @error: return location for error or %NULL
1655 * Synchronously releases name on the bus and returns status code.
1657 * The calling thread is blocked until a reply is received.
1659 * Returns: status code or %G_BUS_RELEASE_NAME_FLAGS_ERROR
1664 GBusReleaseNameReplyFlags
1665 g_dbus_release_name (GDBusConnection *connection,
1670 guint32 release_name_reply;
1672 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_BUS_RELEASE_NAME_FLAGS_ERROR);
1673 g_return_val_if_fail (g_dbus_is_name (name) && !g_dbus_is_unique_name (name), G_BUS_RELEASE_NAME_FLAGS_ERROR);
1674 g_return_val_if_fail (error == NULL || *error == NULL, G_BUS_RELEASE_NAME_FLAGS_ERROR);
1676 if (connection->kdbus_worker)
1677 result = _g_kdbus_ReleaseName (connection->kdbus_worker, name, error);
1679 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/org/freedesktop/DBus",
1680 "org.freedesktop.DBus", "ReleaseName",
1681 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(u)"),
1682 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1686 g_variant_get (result, "(u)", &release_name_reply);
1687 g_variant_unref (result);
1690 release_name_reply = G_BUS_RELEASE_NAME_FLAGS_ERROR;
1692 return (GBusReleaseNameReplyFlags) release_name_reply;
1696 * g_dbus_get_bus_id:
1697 * @connection: a #GDBusConnection
1698 * @error: return location for error or %NULL
1700 * Synchronously returns the unique ID of the bus.
1702 * The calling thread is blocked until a reply is received.
1704 * Returns: the unique ID of the bus or %NULL if @error is set.
1705 * Free with g_free().
1710 g_dbus_get_bus_id (GDBusConnection *connection,
1716 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1717 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1722 if (connection->kdbus_worker)
1724 result = _g_kdbus_GetBusId (connection->kdbus_worker, error);
1728 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1729 "org.freedesktop.DBus", "GetId",
1730 NULL, G_VARIANT_TYPE ("(s)"),
1731 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1736 g_variant_get (result, "(s)", &bus_id);
1737 g_variant_unref (result);
1746 LIST_ACTIVATABLE_NAMES,
1748 } GDBusListNameType;
1751 _g_dbus_get_list_internal (GDBusConnection *connection,
1753 GDBusListNameType list_name_type,
1765 if (list_name_type == LIST_QUEUED_OWNERS)
1767 if (connection->kdbus_worker)
1768 result = _g_kdbus_GetListQueuedOwners (connection->kdbus_worker, name, error);
1770 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1771 "org.freedesktop.DBus", "ListQueuedOwners",
1772 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(as)"),
1773 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1779 if (list_name_type == LIST_NAMES)
1780 method_name = "ListNames";
1782 method_name = "ListActivatableNames";
1784 if (connection->kdbus_worker)
1785 result = _g_kdbus_GetListNames (connection->kdbus_worker, list_name_type, error);
1787 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1788 "org.freedesktop.DBus", method_name,
1789 NULL, G_VARIANT_TYPE ("(as)"),
1790 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1795 g_variant_get (result, "(as)", &iter);
1796 n = g_variant_iter_n_children (iter);
1797 strv = g_new (gchar *, n + 1);
1800 while (g_variant_iter_loop (iter, "s", &str))
1802 strv[i] = g_strdup (str);
1807 g_variant_iter_free (iter);
1808 g_variant_unref (result);
1815 * g_dbus_get_list_names:
1816 * @connection: a #GDBusConnection
1817 * @error: return location for error or %NULL
1819 * Synchronously returns a list of all currently-owned names on the bus.
1821 * The calling thread is blocked until a reply is received.
1823 * Returns: a list of all currently-owned names on the bus or %NULL if
1824 * @error is set. Free with g_strfreev().
1829 g_dbus_get_list_names (GDBusConnection *connection,
1834 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1835 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1837 strv = _g_dbus_get_list_internal (connection, NULL, LIST_NAMES, error);
1843 * g_dbus_get_list_activatable_names:
1844 * @connection: a #GDBusConnection
1845 * @error: return location for error or %NULL
1847 * Synchronously returns a list of all names that can be activated on the bus.
1849 * The calling thread is blocked until a reply is received.
1851 * Returns: a list of all names that can be activated on the bus or %NULL if
1852 * @error is set. Free with g_strfreev().
1857 g_dbus_get_list_activatable_names (GDBusConnection *connection,
1862 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1863 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1865 strv = _g_dbus_get_list_internal (connection, NULL, LIST_ACTIVATABLE_NAMES, error);
1871 * g_dbus_get_list_queued_names:
1872 * @connection: a #GDBusConnection
1873 * @name: a unique or well-known bus name
1874 * @error: return location for error or %NULL
1876 * Synchronously returns the unique bus names of connections currently queued
1879 * If @name contains a value not compatible with the D-Bus syntax and naming
1880 * conventions for bus names, the operation returns %NULL and @error is set.
1882 * The calling thread is blocked until a reply is received.
1884 * Returns: the unique bus names of connections currently queued for the @name
1885 * or %NULL if @error is set. Free with g_strfreev().
1890 g_dbus_get_list_queued_owners (GDBusConnection *connection,
1896 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1897 g_return_val_if_fail (name == NULL || g_dbus_is_name (name), NULL);
1898 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1900 strv = _g_dbus_get_list_internal (connection, name, LIST_QUEUED_OWNERS, error);
1906 * g_dbus_get_name_owner:
1907 * @connection: a #GDBusConnection
1908 * @name: well-known bus name to get the owner of
1909 * @error: return location for error or %NULL
1911 * Synchronously returns the unique connection name of the primary owner of
1912 * the name given. If the requested name doesn't have an owner, an @error is
1915 * If @name contains a value not compatible with the D-Bus syntax and naming
1916 * conventions for bus names, the operation returns %NULL and @error is set.
1918 * The calling thread is blocked until a reply is received.
1920 * Returns: the unique connection name of the primary owner of the
1921 * name given. If the requested name doesn't have an owner, function
1922 * returns %NULL and @error is set. Free with g_free().
1927 g_dbus_get_name_owner (GDBusConnection *connection,
1934 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1935 g_return_val_if_fail (name == NULL || g_dbus_is_name (name), NULL);
1936 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1941 if (connection->kdbus_worker)
1942 result = _g_kdbus_GetNameOwner (connection->kdbus_worker, name, error);
1944 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1945 "org.freedesktop.DBus", "GetNameOwner",
1946 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(s)"),
1947 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1950 g_variant_get (result, "(s)", &name_owner);
1951 g_variant_unref (result);
1960 * g_dbus_get_connection_pid:
1961 * @connection: a #GDBusConnection
1962 * @name: a unique or well-known bus name of the connection to query
1963 * @error: return location for error or %NULL
1965 * Synchronously returns the Unix process ID of the process connected to the
1966 * bus. If unable to determine it, an @error is returned.
1968 * If @name contains a value not compatible with the D-Bus syntax and naming
1969 * conventions for bus names, the operation returns (guint32) -1 and @error
1972 * The calling thread is blocked until a reply is received.
1974 * Returns: the Unix process ID of the process connected to the bus or
1975 * (guint32) -1 if @error is set.
1980 g_dbus_get_connection_pid (GDBusConnection *connection,
1987 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), -1);
1988 g_return_val_if_fail (name == NULL || g_dbus_is_name (name), -1);
1989 g_return_val_if_fail (error == NULL || *error == NULL, -1);
1994 if (connection->kdbus_worker)
1995 result = _g_kdbus_GetConnectionUnixProcessID (connection->kdbus_worker, name, error);
1997 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1998 "org.freedesktop.DBus", "GetConnectionUnixProcessID",
1999 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(u)"),
2000 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
2003 g_variant_get (result, "(u)", &pid);
2004 g_variant_unref (result);
2011 * g_dbus_get_connection_uid:
2012 * @connection: a #GDBusConnection
2013 * @name: a unique or well-known bus name of the connection to query
2014 * @error: return location for error or %NULL
2016 * Synchronously returns the Unix user ID of the process connected to the
2017 * bus. If unable to determine it, an @error is returned.
2019 * If @name contains a value not compatible with the D-Bus syntax and naming
2020 * conventions for bus names, the operation returns (guint32) -1 and @error
2023 * The calling thread is blocked until a reply is received.
2025 * Returns: the Unix user ID of the process connected to the bus or
2026 * (guint32) -1 if @error is set.
2031 g_dbus_get_connection_uid (GDBusConnection *connection,
2038 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), -1);
2039 g_return_val_if_fail (name == NULL || g_dbus_is_name (name), -1);
2040 g_return_val_if_fail (error == NULL || *error == NULL, -1);
2045 if (connection->kdbus_worker)
2046 result = _g_kdbus_GetConnectionUnixUser (connection->kdbus_worker, name, error);
2048 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
2049 "org.freedesktop.DBus", "GetConnectionUnixUser",
2050 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(u)"),
2051 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
2054 g_variant_get (result, "(u)", &uid);
2055 g_variant_unref (result);
2061 /* ---------------------------------------------------------------------------------------------------- */
2064 * g_dbus_connection_get_last_serial:
2065 * @connection: a #GDBusConnection
2067 * Retrieves the last serial number assigned to a #GDBusMessage on
2068 * the current thread. This includes messages sent via both low-level
2069 * API such as g_dbus_connection_send_message() as well as
2070 * high-level API such as g_dbus_connection_emit_signal(),
2071 * g_dbus_connection_call() or g_dbus_proxy_call().
2073 * Returns: the last used serial or zero when no message has been sent
2074 * within the current thread
2079 g_dbus_connection_get_last_serial (GDBusConnection *connection)
2083 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2085 CONNECTION_LOCK (connection);
2086 ret = GPOINTER_TO_UINT (g_hash_table_lookup (connection->map_thread_to_last_serial,
2088 CONNECTION_UNLOCK (connection);
2093 /* ---------------------------------------------------------------------------------------------------- */
2095 /* Can be called by any thread, with the connection lock held */
2097 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
2098 GDBusMessage *message,
2099 GDBusSendMessageFlags flags,
2100 volatile guint32 *out_serial,
2105 guint32 serial_to_use;
2108 CONNECTION_ENSURE_LOCK (connection);
2110 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2111 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
2113 /* TODO: check all necessary headers are present */
2118 if (out_serial != NULL)
2121 /* If we're in initable_init(), don't check for being initialized, to avoid
2122 * chicken-and-egg problems. initable_init() is responsible for setting up
2123 * our prerequisites (mainly connection->worker), and only calling us
2124 * from its own thread (so no memory barrier is needed).
2126 if (!check_unclosed (connection,
2127 (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
2131 blob = g_dbus_message_to_blob (message,
2133 connection->capabilities,
2139 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
2140 g_dbus_message_set_serial (message, ++connection->last_serial);
2142 serial_to_use = g_dbus_message_get_serial (message);
2144 g_dbus_message_lock (message);
2149 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
2152 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
2155 g_assert_not_reached ();
2160 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
2161 blob_size, serial_to_use, connection);
2162 g_printerr ("----\n");
2163 hexdump (blob, blob_size);
2164 g_printerr ("----\n");
2167 /* TODO: use connection->auth to encode the blob */
2169 if (out_serial != NULL)
2170 *out_serial = serial_to_use;
2172 /* store used serial for the current thread */
2173 /* TODO: watch the thread disposal and remove associated record
2175 * - see https://bugzilla.gnome.org/show_bug.cgi?id=676825#c7
2177 g_hash_table_replace (connection->map_thread_to_last_serial,
2179 GUINT_TO_POINTER (serial_to_use));
2181 if (connection->worker)
2182 _g_dbus_worker_send_message (connection->worker,
2187 g_kdbus_worker_send_message (connection->kdbus_worker, message, error);
2189 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
2200 * g_dbus_connection_send_message:
2201 * @connection: a #GDBusConnection
2202 * @message: a #GDBusMessage
2203 * @flags: flags affecting how the message is sent
2204 * @out_serial: (out) (allow-none): return location for serial number assigned
2205 * to @message when sending it or %NULL
2206 * @error: Return location for error or %NULL
2208 * Asynchronously sends @message to the peer represented by @connection.
2210 * Unless @flags contain the
2211 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2212 * will be assigned by @connection and set on @message via
2213 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2214 * serial number used will be written to this location prior to
2215 * submitting the message to the underlying transport.
2217 * If @connection is closed then the operation will fail with
2218 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
2219 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2221 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2222 * for an example of how to use this low-level API to send and receive
2223 * UNIX file descriptors.
2225 * Note that @message must be unlocked, unless @flags contain the
2226 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2228 * Returns: %TRUE if the message was well-formed and queued for
2229 * transmission, %FALSE if @error is set
2234 g_dbus_connection_send_message (GDBusConnection *connection,
2235 GDBusMessage *message,
2236 GDBusSendMessageFlags flags,
2237 volatile guint32 *out_serial,
2242 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2243 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
2244 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
2245 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2247 CONNECTION_LOCK (connection);
2248 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
2249 CONNECTION_UNLOCK (connection);
2253 /* ---------------------------------------------------------------------------------------------------- */
2257 volatile gint ref_count;
2258 GDBusConnection *connection;
2260 GSimpleAsyncResult *simple;
2262 GMainContext *main_context;
2264 GCancellable *cancellable;
2266 gulong cancellable_handler_id;
2268 GSource *timeout_source;
2273 /* Can be called from any thread with or without lock held */
2274 static SendMessageData *
2275 send_message_data_ref (SendMessageData *data)
2277 g_atomic_int_inc (&data->ref_count);
2281 /* Can be called from any thread with or without lock held */
2283 send_message_data_unref (SendMessageData *data)
2285 if (g_atomic_int_dec_and_test (&data->ref_count))
2287 g_assert (data->timeout_source == NULL);
2288 g_assert (data->simple == NULL);
2289 g_assert (data->cancellable_handler_id == 0);
2290 g_object_unref (data->connection);
2291 if (data->cancellable != NULL)
2292 g_object_unref (data->cancellable);
2293 g_main_context_unref (data->main_context);
2298 /* ---------------------------------------------------------------------------------------------------- */
2300 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
2302 send_message_with_reply_deliver (SendMessageData *data, gboolean remove)
2304 CONNECTION_ENSURE_LOCK (data->connection);
2306 g_assert (!data->delivered);
2308 data->delivered = TRUE;
2310 g_simple_async_result_complete_in_idle (data->simple);
2311 g_object_unref (data->simple);
2312 data->simple = NULL;
2314 if (data->timeout_source != NULL)
2316 g_source_destroy (data->timeout_source);
2317 data->timeout_source = NULL;
2319 if (data->cancellable_handler_id > 0)
2321 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
2322 data->cancellable_handler_id = 0;
2327 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
2328 GUINT_TO_POINTER (data->serial)));
2331 send_message_data_unref (data);
2334 /* ---------------------------------------------------------------------------------------------------- */
2336 /* Can be called from any thread with lock held */
2338 send_message_data_deliver_reply_unlocked (SendMessageData *data,
2339 GDBusMessage *reply)
2341 if (data->delivered)
2344 g_simple_async_result_set_op_res_gpointer (data->simple,
2345 g_object_ref (reply),
2348 send_message_with_reply_deliver (data, TRUE);
2354 /* ---------------------------------------------------------------------------------------------------- */
2356 /* Called from a user thread, lock is not held */
2358 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
2360 SendMessageData *data = user_data;
2362 CONNECTION_LOCK (data->connection);
2363 if (data->delivered)
2366 g_simple_async_result_set_error (data->simple,
2368 G_IO_ERROR_CANCELLED,
2369 _("Operation was cancelled"));
2371 send_message_with_reply_deliver (data, TRUE);
2374 CONNECTION_UNLOCK (data->connection);
2378 /* Can be called from any thread with or without lock held */
2380 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
2383 SendMessageData *data = user_data;
2384 GSource *idle_source;
2386 /* postpone cancellation to idle handler since we may be called directly
2387 * via g_cancellable_connect() (e.g. holding lock)
2389 idle_source = g_idle_source_new ();
2390 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
2391 g_source_set_callback (idle_source,
2392 send_message_with_reply_cancelled_idle_cb,
2393 send_message_data_ref (data),
2394 (GDestroyNotify) send_message_data_unref);
2395 g_source_set_name (idle_source, "[gio] send_message_with_reply_cancelled_idle_cb");
2396 g_source_attach (idle_source, data->main_context);
2397 g_source_unref (idle_source);
2400 /* ---------------------------------------------------------------------------------------------------- */
2402 /* Called from a user thread, lock is not held */
2404 send_message_with_reply_timeout_cb (gpointer user_data)
2406 SendMessageData *data = user_data;
2408 CONNECTION_LOCK (data->connection);
2409 if (data->delivered)
2412 g_simple_async_result_set_error (data->simple,
2414 G_IO_ERROR_TIMED_OUT,
2415 _("Timeout was reached"));
2417 send_message_with_reply_deliver (data, TRUE);
2420 CONNECTION_UNLOCK (data->connection);
2425 /* ---------------------------------------------------------------------------------------------------- */
2427 /* Called from a user thread, connection's lock is held */
2429 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
2430 GDBusMessage *message,
2431 GDBusSendMessageFlags flags,
2433 volatile guint32 *out_serial,
2434 GCancellable *cancellable,
2435 GAsyncReadyCallback callback,
2438 GSimpleAsyncResult *simple;
2439 SendMessageData *data;
2441 volatile guint32 serial;
2445 if (out_serial == NULL)
2446 out_serial = &serial;
2448 if (timeout_msec == -1)
2449 timeout_msec = 25 * 1000;
2451 simple = g_simple_async_result_new (G_OBJECT (connection),
2454 g_dbus_connection_send_message_with_reply);
2455 g_simple_async_result_set_check_cancellable (simple, cancellable);
2457 if (g_cancellable_is_cancelled (cancellable))
2459 g_simple_async_result_set_error (simple,
2461 G_IO_ERROR_CANCELLED,
2462 _("Operation was cancelled"));
2463 g_simple_async_result_complete_in_idle (simple);
2464 g_object_unref (simple);
2469 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
2471 g_simple_async_result_take_error (simple, error);
2472 g_simple_async_result_complete_in_idle (simple);
2473 g_object_unref (simple);
2477 data = g_new0 (SendMessageData, 1);
2478 data->ref_count = 1;
2479 data->connection = g_object_ref (connection);
2480 data->simple = simple;
2481 data->serial = *out_serial;
2482 data->main_context = g_main_context_ref_thread_default ();
2484 if (cancellable != NULL)
2486 data->cancellable = g_object_ref (cancellable);
2487 data->cancellable_handler_id = g_cancellable_connect (cancellable,
2488 G_CALLBACK (send_message_with_reply_cancelled_cb),
2489 send_message_data_ref (data),
2490 (GDestroyNotify) send_message_data_unref);
2493 if (timeout_msec != G_MAXINT)
2495 data->timeout_source = g_timeout_source_new (timeout_msec);
2496 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
2497 g_source_set_callback (data->timeout_source,
2498 send_message_with_reply_timeout_cb,
2499 send_message_data_ref (data),
2500 (GDestroyNotify) send_message_data_unref);
2501 g_source_attach (data->timeout_source, data->main_context);
2502 g_source_unref (data->timeout_source);
2505 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
2506 GUINT_TO_POINTER (*out_serial),
2514 * g_dbus_connection_send_message_with_reply:
2515 * @connection: a #GDBusConnection
2516 * @message: a #GDBusMessage
2517 * @flags: flags affecting how the message is sent
2518 * @timeout_msec: the timeout in milliseconds, -1 to use the default
2519 * timeout or %G_MAXINT for no timeout
2520 * @out_serial: (out) (allow-none): return location for serial number assigned
2521 * to @message when sending it or %NULL
2522 * @cancellable: (allow-none): a #GCancellable or %NULL
2523 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request
2524 * is satisfied or %NULL if you don't care about the result
2525 * @user_data: The data to pass to @callback
2527 * Asynchronously sends @message to the peer represented by @connection.
2529 * Unless @flags contain the
2530 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2531 * will be assigned by @connection and set on @message via
2532 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2533 * serial number used will be written to this location prior to
2534 * submitting the message to the underlying transport.
2536 * If @connection is closed then the operation will fail with
2537 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2538 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2539 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2541 * This is an asynchronous method. When the operation is finished, @callback
2542 * will be invoked in the
2543 * [thread-default main context][g-main-context-push-thread-default]
2544 * of the thread you are calling this method from. You can then call
2545 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
2546 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
2548 * Note that @message must be unlocked, unless @flags contain the
2549 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2551 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2552 * for an example of how to use this low-level API to send and receive
2553 * UNIX file descriptors.
2558 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
2559 GDBusMessage *message,
2560 GDBusSendMessageFlags flags,
2562 volatile guint32 *out_serial,
2563 GCancellable *cancellable,
2564 GAsyncReadyCallback callback,
2567 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2568 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2569 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2570 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2572 CONNECTION_LOCK (connection);
2573 g_dbus_connection_send_message_with_reply_unlocked (connection,
2581 CONNECTION_UNLOCK (connection);
2585 * g_dbus_connection_send_message_with_reply_finish:
2586 * @connection: a #GDBusConnection
2587 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
2588 * g_dbus_connection_send_message_with_reply()
2589 * @error: teturn location for error or %NULL
2591 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2593 * Note that @error is only set if a local in-process error
2594 * occurred. That is to say that the returned #GDBusMessage object may
2595 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2596 * g_dbus_message_to_gerror() to transcode this to a #GError.
2598 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2599 * for an example of how to use this low-level API to send and receive
2600 * UNIX file descriptors.
2602 * Returns: (transfer full): a locked #GDBusMessage or %NULL if @error is set
2607 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2611 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2612 GDBusMessage *reply;
2614 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2615 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2619 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
2621 if (g_simple_async_result_propagate_error (simple, error))
2624 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
2630 /* ---------------------------------------------------------------------------------------------------- */
2635 GMainContext *context;
2637 } SendMessageSyncData;
2639 /* Called from a user thread, lock is not held */
2641 send_message_with_reply_sync_cb (GDBusConnection *connection,
2645 SendMessageSyncData *data = user_data;
2646 data->res = g_object_ref (res);
2647 g_main_loop_quit (data->loop);
2651 * g_dbus_connection_send_message_with_reply_sync:
2652 * @connection: a #GDBusConnection
2653 * @message: a #GDBusMessage
2654 * @flags: flags affecting how the message is sent.
2655 * @timeout_msec: the timeout in milliseconds, -1 to use the default
2656 * timeout or %G_MAXINT for no timeout
2657 * @out_serial: (out) (allow-none): return location for serial number
2658 * assigned to @message when sending it or %NULL
2659 * @cancellable: (allow-none): a #GCancellable or %NULL
2660 * @error: return location for error or %NULL
2662 * Synchronously sends @message to the peer represented by @connection
2663 * and blocks the calling thread until a reply is received or the
2664 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2665 * for the asynchronous version of this method.
2667 * Unless @flags contain the
2668 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2669 * will be assigned by @connection and set on @message via
2670 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2671 * serial number used will be written to this location prior to
2672 * submitting the message to the underlying transport.
2674 * If @connection is closed then the operation will fail with
2675 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2676 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2677 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2679 * Note that @error is only set if a local in-process error
2680 * occurred. That is to say that the returned #GDBusMessage object may
2681 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2682 * g_dbus_message_to_gerror() to transcode this to a #GError.
2684 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2685 * for an example of how to use this low-level API to send and receive
2686 * UNIX file descriptors.
2688 * Note that @message must be unlocked, unless @flags contain the
2689 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2691 * Returns: (transfer full): a locked #GDBusMessage that is the reply
2692 * to @message or %NULL if @error is set
2697 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2698 GDBusMessage *message,
2699 GDBusSendMessageFlags flags,
2701 volatile guint32 *out_serial,
2702 GCancellable *cancellable,
2705 SendMessageSyncData *data;
2706 GDBusMessage *reply;
2708 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2709 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2710 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2711 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2712 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2714 data = g_new0 (SendMessageSyncData, 1);
2715 data->context = g_main_context_new ();
2716 data->loop = g_main_loop_new (data->context, FALSE);
2718 g_main_context_push_thread_default (data->context);
2720 g_dbus_connection_send_message_with_reply (connection,
2726 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2728 g_main_loop_run (data->loop);
2729 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2733 g_main_context_pop_thread_default (data->context);
2735 g_main_context_unref (data->context);
2736 g_main_loop_unref (data->loop);
2737 g_object_unref (data->res);
2743 /* ---------------------------------------------------------------------------------------------------- */
2747 GDBusMessageFilterFunction func;
2754 GDBusMessageFilterFunction filter_function;
2756 GDestroyNotify user_data_free_func;
2759 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2761 on_worker_message_received (GDBusMessage *message,
2764 GDBusConnection *connection;
2765 FilterCallback *filters;
2770 G_LOCK (message_bus_lock);
2771 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2774 G_UNLOCK (message_bus_lock);
2777 connection = G_DBUS_CONNECTION (user_data);
2778 g_object_ref (connection);
2779 G_UNLOCK (message_bus_lock);
2781 //g_debug ("in on_worker_message_received");
2783 g_object_ref (message);
2784 g_dbus_message_lock (message);
2786 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2788 /* First collect the set of callback functions */
2789 CONNECTION_LOCK (connection);
2790 num_filters = connection->filters->len;
2791 filters = g_new0 (FilterCallback, num_filters);
2792 for (n = 0; n < num_filters; n++)
2794 FilterData *data = connection->filters->pdata[n];
2795 filters[n].func = data->filter_function;
2796 filters[n].user_data = data->user_data;
2798 CONNECTION_UNLOCK (connection);
2800 /* then call the filters in order (without holding the lock) */
2801 for (n = 0; n < num_filters; n++)
2803 message = filters[n].func (connection,
2806 filters[n].user_data);
2807 if (message == NULL)
2809 g_dbus_message_lock (message);
2812 /* Standard dispatch unless the filter ate the message - no need to
2813 * do anything if the message was altered
2815 if (message != NULL)
2817 GDBusMessageType message_type;
2819 message_type = g_dbus_message_get_message_type (message);
2820 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2822 guint32 reply_serial;
2823 SendMessageData *send_message_data;
2825 reply_serial = g_dbus_message_get_reply_serial (message);
2826 CONNECTION_LOCK (connection);
2827 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2828 GUINT_TO_POINTER (reply_serial));
2829 if (send_message_data != NULL)
2831 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2832 send_message_data_deliver_reply_unlocked (send_message_data, message);
2836 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2838 CONNECTION_UNLOCK (connection);
2840 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2842 CONNECTION_LOCK (connection);
2843 distribute_signals (connection, message);
2844 CONNECTION_UNLOCK (connection);
2846 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2848 CONNECTION_LOCK (connection);
2849 distribute_method_call (connection, message);
2850 CONNECTION_UNLOCK (connection);
2854 if (message != NULL)
2855 g_object_unref (message);
2856 g_object_unref (connection);
2860 /* Called in GDBusWorker's thread, lock is not held */
2861 static GDBusMessage *
2862 on_worker_message_about_to_be_sent (GDBusMessage *message,
2865 GDBusConnection *connection;
2866 FilterCallback *filters;
2871 G_LOCK (message_bus_lock);
2872 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2875 G_UNLOCK (message_bus_lock);
2878 connection = G_DBUS_CONNECTION (user_data);
2879 g_object_ref (connection);
2880 G_UNLOCK (message_bus_lock);
2882 //g_debug ("in on_worker_message_about_to_be_sent");
2884 /* First collect the set of callback functions */
2885 CONNECTION_LOCK (connection);
2886 num_filters = connection->filters->len;
2887 filters = g_new0 (FilterCallback, num_filters);
2888 for (n = 0; n < num_filters; n++)
2890 FilterData *data = connection->filters->pdata[n];
2891 filters[n].func = data->filter_function;
2892 filters[n].user_data = data->user_data;
2894 CONNECTION_UNLOCK (connection);
2896 /* then call the filters in order (without holding the lock) */
2897 for (n = 0; n < num_filters; n++)
2899 g_dbus_message_lock (message);
2900 message = filters[n].func (connection,
2903 filters[n].user_data);
2904 if (message == NULL)
2908 g_object_unref (connection);
2914 /* called with connection lock held, in GDBusWorker thread */
2916 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2918 SendMessageData *data = value;
2920 if (data->delivered)
2923 g_simple_async_result_set_error (data->simple,
2926 _("The connection is closed"));
2928 /* Ask send_message_with_reply_deliver not to remove the element from the
2929 * hash table - we're in the middle of a foreach; that would be unsafe.
2930 * Instead, return TRUE from this function so that it gets removed safely.
2932 send_message_with_reply_deliver (data, FALSE);
2936 /* Called in GDBusWorker's thread - we must not block - without lock held */
2938 on_worker_closed (gboolean remote_peer_vanished,
2942 GDBusConnection *connection;
2944 guint old_atomic_flags;
2946 G_LOCK (message_bus_lock);
2947 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2950 G_UNLOCK (message_bus_lock);
2953 connection = G_DBUS_CONNECTION (user_data);
2954 g_object_ref (connection);
2955 G_UNLOCK (message_bus_lock);
2957 //g_debug ("in on_worker_closed: %s", error->message);
2959 CONNECTION_LOCK (connection);
2960 /* Even though this is atomic, we do it inside the lock to avoid breaking
2961 * assumptions in remove_match_rule(). We'd need the lock in a moment
2962 * anyway, so, no loss.
2964 old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
2966 if (!(old_atomic_flags & FLAG_CLOSED))
2968 g_hash_table_foreach_remove (connection->map_method_serial_to_send_message_data, cancel_method_on_close, NULL);
2969 schedule_closed_unlocked (connection, remote_peer_vanished, error);
2971 CONNECTION_UNLOCK (connection);
2973 g_object_unref (connection);
2976 /* ---------------------------------------------------------------------------------------------------- */
2978 /* Determines the biggest set of capabilities we can support on this
2981 * Called with the init_lock held.
2983 static GDBusCapabilityFlags
2984 get_offered_capabilities_max (GDBusConnection *connection)
2986 GDBusCapabilityFlags ret;
2987 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2989 if (G_IS_UNIX_CONNECTION (connection->stream))
2990 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2995 /* Called in a user thread, lock is not held */
2997 initable_init (GInitable *initable,
2998 GCancellable *cancellable,
3001 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
3002 gboolean initially_frozen;
3005 /* This method needs to be idempotent to work with the singleton
3006 * pattern. See the docs for g_initable_init(). We implement this by
3009 * Unfortunately we can't use the main lock since the on_worker_*()
3010 * callbacks above needs the lock during initialization (for message
3011 * bus connections we do a synchronous Hello() call on the bus).
3013 g_mutex_lock (&connection->init_lock);
3017 /* Make this a no-op if we're already initialized (successfully or
3020 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
3022 ret = (connection->initialization_error == NULL);
3026 /* Because of init_lock, we can't get here twice in different threads */
3027 g_assert (connection->initialization_error == NULL);
3029 /* The user can pass multiple (but mutally exclusive) construct
3032 * - stream (of type GIOStream)
3033 * - address (of type gchar*)
3035 * At the end of the day we end up with a non-NULL GIOStream
3036 * object in connection->stream.
3038 if (connection->address != NULL)
3042 g_assert (connection->stream == NULL);
3044 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
3045 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
3047 g_set_error_literal (&connection->initialization_error,
3049 G_IO_ERROR_INVALID_ARGUMENT,
3050 _("Unsupported flags encountered when constructing a client-side connection"));
3054 ret = g_dbus_address_get_stream_internal (connection->address, TRUE,
3055 NULL, /* TODO: out_guid */
3056 cancellable, &connection->initialization_error);
3060 if (G_IS_IO_STREAM (ret))
3061 connection->stream = G_IO_STREAM (ret);
3062 else if (G_IS_KDBUS_WORKER (ret))
3063 connection->kdbus_worker = G_KDBUS_WORKER (ret);
3065 g_assert_not_reached ();
3067 else if (connection->stream != NULL)
3073 g_assert_not_reached ();
3076 /* [KDBUS] Skip authentication process for kdbus transport */
3077 if (connection->kdbus_worker)
3082 /* Authenticate the connection */
3083 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
3085 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
3086 g_assert (connection->guid != NULL);
3087 connection->auth = _g_dbus_auth_new (connection->stream);
3088 if (!_g_dbus_auth_run_server (connection->auth,
3089 connection->authentication_observer,
3091 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
3092 get_offered_capabilities_max (connection),
3093 &connection->capabilities,
3094 &connection->credentials,
3096 &connection->initialization_error))
3099 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
3101 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
3102 g_assert (connection->guid == NULL);
3103 connection->auth = _g_dbus_auth_new (connection->stream);
3104 connection->guid = _g_dbus_auth_run_client (connection->auth,
3105 connection->authentication_observer,
3106 get_offered_capabilities_max (connection),
3107 &connection->capabilities,
3109 &connection->initialization_error);
3110 if (connection->guid == NULL)
3114 if (connection->authentication_observer != NULL)
3116 g_object_unref (connection->authentication_observer);
3117 connection->authentication_observer = NULL;
3122 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
3124 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
3127 /* We want all IO operations to be non-blocking since they happen in
3128 * the worker thread which is shared by _all_ connections.
3130 if (G_IS_SOCKET_CONNECTION (connection->stream))
3132 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
3136 G_LOCK (message_bus_lock);
3137 if (alive_connections == NULL)
3138 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
3139 g_hash_table_insert (alive_connections, connection, connection);
3140 G_UNLOCK (message_bus_lock);
3142 initially_frozen = (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) != 0;
3144 if (connection->kdbus_worker)
3145 g_kdbus_worker_associate (connection->kdbus_worker,
3146 connection->capabilities,
3147 on_worker_message_received,
3148 on_worker_message_about_to_be_sent,
3152 connection->worker = _g_dbus_worker_new (connection->stream,
3153 connection->capabilities,
3155 on_worker_message_received,
3156 on_worker_message_about_to_be_sent,
3160 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
3161 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3163 GVariant *hello_result;
3165 /* we could lift this restriction by adding code in gdbusprivate.c */
3166 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
3168 g_set_error_literal (&connection->initialization_error,
3171 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
3175 if (connection->kdbus_worker)
3177 hello_result = _g_kdbus_Hello (connection->kdbus_worker, &connection->initialization_error);
3181 hello_result = g_dbus_connection_call_sync (connection,
3182 "org.freedesktop.DBus", /* name */
3183 "/org/freedesktop/DBus", /* path */
3184 "org.freedesktop.DBus", /* interface */
3186 NULL, /* parameters */
3187 G_VARIANT_TYPE ("(s)"),
3188 CALL_FLAGS_INITIALIZING,
3190 NULL, /* TODO: cancellable */
3191 &connection->initialization_error);
3194 if (hello_result == NULL)
3197 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
3198 g_variant_unref (hello_result);
3199 //g_debug ("unique name is '%s'", connection->bus_unique_name);
3202 if (connection->kdbus_worker && !initially_frozen)
3203 g_kdbus_worker_unfreeze (connection->kdbus_worker);
3209 g_assert (connection->initialization_error != NULL);
3210 g_propagate_error (error, g_error_copy (connection->initialization_error));
3213 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
3214 g_mutex_unlock (&connection->init_lock);
3220 initable_iface_init (GInitableIface *initable_iface)
3222 initable_iface->init = initable_init;
3225 /* ---------------------------------------------------------------------------------------------------- */
3228 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
3233 /* ---------------------------------------------------------------------------------------------------- */
3236 * g_dbus_connection_new:
3237 * @stream: a #GIOStream
3238 * @guid: (allow-none): the GUID to use if a authenticating as a server or %NULL
3239 * @flags: flags describing how to make the connection
3240 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3241 * @cancellable: (allow-none): a #GCancellable or %NULL
3242 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
3243 * @user_data: the data to pass to @callback
3245 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
3246 * with the end represented by @stream.
3248 * If @stream is a #GSocketConnection, then the corresponding #GSocket
3249 * will be put into non-blocking mode.
3251 * The D-Bus connection will interact with @stream from a worker thread.
3252 * As a result, the caller should not interact with @stream after this
3253 * method has been called, except by calling g_object_unref() on it.
3255 * If @observer is not %NULL it may be used to control the
3256 * authentication process.
3258 * When the operation is finished, @callback will be invoked. You can
3259 * then call g_dbus_connection_new_finish() to get the result of the
3262 * This is a asynchronous failable constructor. See
3263 * g_dbus_connection_new_sync() for the synchronous
3269 g_dbus_connection_new (GIOStream *stream,
3271 GDBusConnectionFlags flags,
3272 GDBusAuthObserver *observer,
3273 GCancellable *cancellable,
3274 GAsyncReadyCallback callback,
3277 g_return_if_fail (G_IS_IO_STREAM (stream));
3278 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
3286 "authentication-observer", observer,
3291 * g_dbus_connection_new_finish:
3292 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback
3293 * passed to g_dbus_connection_new().
3294 * @error: return location for error or %NULL
3296 * Finishes an operation started with g_dbus_connection_new().
3298 * Returns: a #GDBusConnection or %NULL if @error is set. Free
3299 * with g_object_unref().
3304 g_dbus_connection_new_finish (GAsyncResult *res,
3308 GObject *source_object;
3310 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
3311 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3313 source_object = g_async_result_get_source_object (res);
3314 g_assert (source_object != NULL);
3315 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
3318 g_object_unref (source_object);
3320 return G_DBUS_CONNECTION (object);
3326 * g_dbus_connection_new_sync:
3327 * @stream: a #GIOStream
3328 * @guid: (allow-none): the GUID to use if a authenticating as a server or %NULL
3329 * @flags: flags describing how to make the connection
3330 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3331 * @cancellable: (allow-none): a #GCancellable or %NULL
3332 * @error: return location for error or %NULL
3334 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
3335 * with the end represented by @stream.
3337 * If @stream is a #GSocketConnection, then the corresponding #GSocket
3338 * will be put into non-blocking mode.
3340 * The D-Bus connection will interact with @stream from a worker thread.
3341 * As a result, the caller should not interact with @stream after this
3342 * method has been called, except by calling g_object_unref() on it.
3344 * If @observer is not %NULL it may be used to control the
3345 * authentication process.
3347 * This is a synchronous failable constructor. See
3348 * g_dbus_connection_new() for the asynchronous version.
3350 * Returns: a #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
3355 g_dbus_connection_new_sync (GIOStream *stream,
3357 GDBusConnectionFlags flags,
3358 GDBusAuthObserver *observer,
3359 GCancellable *cancellable,
3362 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
3363 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3364 return g_initable_new (G_TYPE_DBUS_CONNECTION,
3370 "authentication-observer", observer,
3374 /* ---------------------------------------------------------------------------------------------------- */
3377 * g_dbus_connection_new_for_address:
3378 * @address: a D-Bus address
3379 * @flags: flags describing how to make the connection
3380 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3381 * @cancellable: (allow-none): a #GCancellable or %NULL
3382 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
3383 * @user_data: the data to pass to @callback
3385 * Asynchronously connects and sets up a D-Bus client connection for
3386 * exchanging D-Bus messages with an endpoint specified by @address
3387 * which must be in the D-Bus address format.
3389 * This constructor can only be used to initiate client-side
3390 * connections - use g_dbus_connection_new() if you need to act as the
3391 * server. In particular, @flags cannot contain the
3392 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
3393 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
3395 * When the operation is finished, @callback will be invoked. You can
3396 * then call g_dbus_connection_new_finish() to get the result of the
3399 * If @observer is not %NULL it may be used to control the
3400 * authentication process.
3402 * This is a asynchronous failable constructor. See
3403 * g_dbus_connection_new_for_address_sync() for the synchronous
3409 g_dbus_connection_new_for_address (const gchar *address,
3410 GDBusConnectionFlags flags,
3411 GDBusAuthObserver *observer,
3412 GCancellable *cancellable,
3413 GAsyncReadyCallback callback,
3416 g_return_if_fail (address != NULL);
3417 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
3424 "authentication-observer", observer,
3429 * g_dbus_connection_new_for_address_finish:
3430 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
3431 * to g_dbus_connection_new()
3432 * @error: return location for error or %NULL
3434 * Finishes an operation started with g_dbus_connection_new_for_address().
3436 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
3442 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
3446 GObject *source_object;
3448 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
3449 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3451 source_object = g_async_result_get_source_object (res);
3452 g_assert (source_object != NULL);
3453 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
3456 g_object_unref (source_object);
3458 return G_DBUS_CONNECTION (object);
3464 * g_dbus_connection_new_for_address_sync:
3465 * @address: a D-Bus address
3466 * @flags: flags describing how to make the connection
3467 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3468 * @cancellable: (allow-none): a #GCancellable or %NULL
3469 * @error: return location for error or %NULL
3471 * Synchronously connects and sets up a D-Bus client connection for
3472 * exchanging D-Bus messages with an endpoint specified by @address
3473 * which must be in the D-Bus address format.
3475 * This constructor can only be used to initiate client-side
3476 * connections - use g_dbus_connection_new_sync() if you need to act
3477 * as the server. In particular, @flags cannot contain the
3478 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
3479 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
3481 * This is a synchronous failable constructor. See
3482 * g_dbus_connection_new_for_address() for the asynchronous version.
3484 * If @observer is not %NULL it may be used to control the
3485 * authentication process.
3487 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
3493 g_dbus_connection_new_for_address_sync (const gchar *address,
3494 GDBusConnectionFlags flags,
3495 GDBusAuthObserver *observer,
3496 GCancellable *cancellable,
3499 g_return_val_if_fail (address != NULL, NULL);
3500 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3501 return g_initable_new (G_TYPE_DBUS_CONNECTION,
3506 "authentication-observer", observer,
3510 /* ---------------------------------------------------------------------------------------------------- */
3513 * g_dbus_connection_set_exit_on_close:
3514 * @connection: a #GDBusConnection
3515 * @exit_on_close: whether the process should be terminated
3516 * when @connection is closed by the remote peer
3518 * Sets whether the process should be terminated when @connection is
3519 * closed by the remote peer. See #GDBusConnection:exit-on-close for
3522 * Note that this function should be used with care. Most modern UNIX
3523 * desktops tie the notion of a user session the session bus, and expect
3524 * all of a users applications to quit when their bus connection goes away.
3525 * If you are setting @exit_on_close to %FALSE for the shared session
3526 * bus connection, you should make sure that your application exits
3527 * when the user session ends.
3532 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
3533 gboolean exit_on_close)
3535 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3538 g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
3540 g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
3545 * g_dbus_connection_get_exit_on_close:
3546 * @connection: a #GDBusConnection
3548 * Gets whether the process is terminated when @connection is
3549 * closed by the remote peer. See
3550 * #GDBusConnection:exit-on-close for more details.
3552 * Returns: whether the process is terminated when @connection is
3553 * closed by the remote peer
3558 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
3560 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3562 if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
3569 * g_dbus_connection_get_guid:
3570 * @connection: a #GDBusConnection
3572 * The GUID of the peer performing the role of server when
3573 * authenticating. See #GDBusConnection:guid for more details.
3575 * Returns: The GUID. Do not free this string, it is owned by
3581 g_dbus_connection_get_guid (GDBusConnection *connection)
3583 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3584 return connection->guid;
3588 * g_dbus_connection_get_unique_name:
3589 * @connection: a #GDBusConnection
3591 * Gets the unique name of @connection as assigned by the message
3592 * bus. This can also be used to figure out if @connection is a
3593 * message bus connection.
3595 * Returns: the unique name or %NULL if @connection is not a message
3596 * bus connection. Do not free this string, it is owned by
3602 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3604 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3606 /* do not use g_return_val_if_fail(), we want the memory barrier */
3607 if (!check_initialized (connection))
3610 return connection->bus_unique_name;
3614 * g_dbus_connection_get_peer_credentials:
3615 * @connection: a #GDBusConnection
3617 * Gets the credentials of the authenticated peer. This will always
3618 * return %NULL unless @connection acted as a server
3619 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3620 * when set up and the client passed credentials as part of the
3621 * authentication process.
3623 * In a message bus setup, the message bus is always the server and
3624 * each application is a client. So this method will always return
3625 * %NULL for message bus clients.
3627 * Returns: (transfer none): a #GCredentials or %NULL if not available.
3628 * Do not free this object, it is owned by @connection.
3633 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3635 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3637 /* do not use g_return_val_if_fail(), we want the memory barrier */
3638 if (!check_initialized (connection))
3641 return connection->credentials;
3644 /* ---------------------------------------------------------------------------------------------------- */
3646 static guint _global_filter_id = 1;
3649 * g_dbus_connection_add_filter:
3650 * @connection: a #GDBusConnection
3651 * @filter_function: a filter function
3652 * @user_data: user data to pass to @filter_function
3653 * @user_data_free_func: function to free @user_data with when filter
3654 * is removed or %NULL
3656 * Adds a message filter. Filters are handlers that are run on all
3657 * incoming and outgoing messages, prior to standard dispatch. Filters
3658 * are run in the order that they were added. The same handler can be
3659 * added as a filter more than once, in which case it will be run more
3660 * than once. Filters added during a filter callback won't be run on
3661 * the message being processed. Filter functions are allowed to modify
3662 * and even drop messages.
3664 * Note that filters are run in a dedicated message handling thread so
3665 * they can't block and, generally, can't do anything but signal a
3666 * worker thread. Also note that filters are rarely needed - use API
3667 * such as g_dbus_connection_send_message_with_reply(),
3668 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3670 * If a filter consumes an incoming message the message is not
3671 * dispatched anywhere else - not even the standard dispatch machinery
3672 * (that API such as g_dbus_connection_signal_subscribe() and
3673 * g_dbus_connection_send_message_with_reply() relies on) will see the
3674 * message. Similary, if a filter consumes an outgoing message, the
3675 * message will not be sent to the other peer.
3677 * Returns: a filter identifier that can be used with
3678 * g_dbus_connection_remove_filter()
3683 g_dbus_connection_add_filter (GDBusConnection *connection,
3684 GDBusMessageFilterFunction filter_function,
3686 GDestroyNotify user_data_free_func)
3690 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3691 g_return_val_if_fail (filter_function != NULL, 0);
3692 g_return_val_if_fail (check_initialized (connection), 0);
3694 CONNECTION_LOCK (connection);
3695 data = g_new0 (FilterData, 1);
3696 data->id = _global_filter_id++; /* TODO: overflow etc. */
3697 data->filter_function = filter_function;
3698 data->user_data = user_data;
3699 data->user_data_free_func = user_data_free_func;
3700 g_ptr_array_add (connection->filters, data);
3701 CONNECTION_UNLOCK (connection);
3706 /* only called from finalize(), removes all filters */
3708 purge_all_filters (GDBusConnection *connection)
3711 for (n = 0; n < connection->filters->len; n++)
3713 FilterData *data = connection->filters->pdata[n];
3714 if (data->user_data_free_func != NULL)
3715 data->user_data_free_func (data->user_data);
3721 * g_dbus_connection_remove_filter:
3722 * @connection: a #GDBusConnection
3723 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3730 g_dbus_connection_remove_filter (GDBusConnection *connection,
3734 FilterData *to_destroy;
3736 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3737 g_return_if_fail (check_initialized (connection));
3739 CONNECTION_LOCK (connection);
3741 for (n = 0; n < connection->filters->len; n++)
3743 FilterData *data = connection->filters->pdata[n];
3744 if (data->id == filter_id)
3746 g_ptr_array_remove_index (connection->filters, n);
3751 CONNECTION_UNLOCK (connection);
3753 /* do free without holding lock */
3754 if (to_destroy != NULL)
3756 if (to_destroy->user_data_free_func != NULL)
3757 to_destroy->user_data_free_func (to_destroy->user_data);
3758 g_free (to_destroy);
3762 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3766 /* ---------------------------------------------------------------------------------------------------- */
3772 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3773 gchar *interface_name;
3777 GDBusSignalFlags flags;
3778 GArray *subscribers;
3783 GDBusSignalCallback callback;
3785 GDestroyNotify user_data_free_func;
3787 GMainContext *context;
3791 signal_data_free (SignalData *signal_data)
3793 g_free (signal_data->rule);
3794 g_free (signal_data->sender);
3795 g_free (signal_data->sender_unique_name);
3796 g_free (signal_data->interface_name);
3797 g_free (signal_data->member);
3798 g_free (signal_data->object_path);
3799 g_free (signal_data->arg0);
3800 g_array_free (signal_data->subscribers, TRUE);
3801 g_free (signal_data);
3805 args_to_rule (const gchar *sender,
3806 const gchar *interface_name,
3807 const gchar *member,
3808 const gchar *object_path,
3810 GDBusSignalFlags flags)
3814 rule = g_string_new ("type='signal'");
3815 if (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE)
3816 g_string_prepend_c (rule, '-');
3818 g_string_append_printf (rule, ",sender='%s'", sender);
3819 if (interface_name != NULL)
3820 g_string_append_printf (rule, ",interface='%s'", interface_name);
3822 g_string_append_printf (rule, ",member='%s'", member);
3823 if (object_path != NULL)
3824 g_string_append_printf (rule, ",path='%s'", object_path);
3828 if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3829 g_string_append_printf (rule, ",arg0path='%s'", arg0);
3830 else if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3831 g_string_append_printf (rule, ",arg0namespace='%s'", arg0);
3833 g_string_append_printf (rule, ",arg0='%s'", arg0);
3836 return g_string_free (rule, FALSE);
3839 static guint _global_subscriber_id = 1;
3840 static guint _global_registration_id = 1;
3841 static guint _global_subtree_registration_id = 1;
3843 /* ---------------------------------------------------------------------------------------------------- */
3845 /* Called in a user thread, lock is held */
3847 add_match_rule (GDBusConnection *connection,
3848 const gchar *match_rule)
3851 GDBusMessage *message;
3853 if (match_rule[0] == '-')
3856 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3857 "/org/freedesktop/DBus", /* path */
3858 "org.freedesktop.DBus", /* interface */
3860 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3862 if (!g_dbus_connection_send_message_unlocked (connection,
3864 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3868 g_critical ("Error while sending AddMatch() message: %s", error->message);
3869 g_error_free (error);
3871 g_object_unref (message);
3874 /* ---------------------------------------------------------------------------------------------------- */
3876 /* Called in a user thread, lock is held */
3878 remove_match_rule (GDBusConnection *connection,
3879 const gchar *match_rule)
3882 GDBusMessage *message;
3884 if (match_rule[0] == '-')
3887 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3888 "/org/freedesktop/DBus", /* path */
3889 "org.freedesktop.DBus", /* interface */
3891 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3894 if (!g_dbus_connection_send_message_unlocked (connection,
3896 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3900 /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
3901 * critical; but we're holding the lock, and our caller checked whether
3902 * we were already closed, so we can't get that error.
3904 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3905 g_error_free (error);
3907 g_object_unref (message);
3910 /* ---------------------------------------------------------------------------------------------------- */
3913 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3915 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3916 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3917 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3918 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3919 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3922 /* ---------------------------------------------------------------------------------------------------- */
3925 * g_dbus_connection_signal_subscribe:
3926 * @connection: a #GDBusConnection
3927 * @sender: (allow-none): sender name to match on (unique or well-known name)
3928 * or %NULL to listen from all senders
3929 * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3930 * match on all interfaces
3931 * @member: (allow-none): D-Bus signal name to match on or %NULL to match on
3933 * @object_path: (allow-none): object path to match on or %NULL to match on
3935 * @arg0: (allow-none): contents of first string argument to match on or %NULL
3936 * to match on all kinds of arguments
3937 * @flags: flags describing how to subscribe to the signal (currently unused)
3938 * @callback: callback to invoke when there is a signal matching the requested data
3939 * @user_data: user data to pass to @callback
3940 * @user_data_free_func: (allow-none): function to free @user_data with when
3941 * subscription is removed or %NULL
3943 * Subscribes to signals on @connection and invokes @callback with a whenever
3944 * the signal is received. Note that @callback will be invoked in the
3945 * [thread-default main context][g-main-context-push-thread-default]
3946 * of the thread you are calling this method from.
3948 * If @connection is not a message bus connection, @sender must be
3951 * If @sender is a well-known name note that @callback is invoked with
3952 * the unique name for the owner of @sender, not the well-known name
3953 * as one would expect. This is because the message bus rewrites the
3954 * name. As such, to avoid certain race conditions, users should be
3955 * tracking the name owner of the well-known name and use that when
3956 * processing the received signal.
3958 * If one of %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE or
3959 * %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH are given, @arg0 is
3960 * interpreted as part of a namespace or path. The first argument
3961 * of a signal is matched against that part as specified by D-Bus.
3963 * Returns: a subscription identifier that can be used with g_dbus_connection_signal_unsubscribe()
3968 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3969 const gchar *sender,
3970 const gchar *interface_name,
3971 const gchar *member,
3972 const gchar *object_path,
3974 GDBusSignalFlags flags,
3975 GDBusSignalCallback callback,
3977 GDestroyNotify user_data_free_func)
3980 SignalData *signal_data;
3981 SignalSubscriber subscriber;
3982 GPtrArray *signal_data_array;
3983 const gchar *sender_unique_name;
3985 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3986 * an OOM condition. We might want to change that but that would involve making
3987 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3988 * handle that. And there's really no sensible way of handling this short of retrying
3989 * to add the match rule... and then there's the little thing that, hey, maybe there's
3990 * a reason the bus in an OOM condition.
3992 * Doable, but not really sure it's worth it...
3995 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3996 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3997 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3998 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3999 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
4000 g_return_val_if_fail (callback != NULL, 0);
4001 g_return_val_if_fail (check_initialized (connection), 0);
4002 g_return_val_if_fail (!((flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH) && (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)), 0);
4003 g_return_val_if_fail (!(arg0 == NULL && (flags & (G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH | G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE))), 0);
4005 CONNECTION_LOCK (connection);
4007 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
4008 * with a '-' character to prefix the rule (which will otherwise be
4011 * This allows us to hash the rule and do our lifecycle tracking in
4012 * the usual way, but the '-' prevents the match rule from ever
4013 * actually being send to the bus (either for add or remove).
4015 rule = args_to_rule (sender, interface_name, member, object_path, arg0, flags);
4017 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
4018 sender_unique_name = sender;
4020 sender_unique_name = "";
4022 subscriber.callback = callback;
4023 subscriber.user_data = user_data;
4024 subscriber.user_data_free_func = user_data_free_func;
4025 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
4026 subscriber.context = g_main_context_ref_thread_default ();
4028 /* see if we've already have this rule */
4029 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
4030 if (signal_data != NULL)
4032 g_array_append_val (signal_data->subscribers, subscriber);
4037 signal_data = g_new0 (SignalData, 1);
4038 signal_data->rule = rule;
4039 signal_data->sender = g_strdup (sender);
4040 signal_data->sender_unique_name = g_strdup (sender_unique_name);
4041 signal_data->interface_name = g_strdup (interface_name);
4042 signal_data->member = g_strdup (member);
4043 signal_data->object_path = g_strdup (object_path);
4044 signal_data->arg0 = g_strdup (arg0);
4045 signal_data->flags = flags;
4046 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
4047 g_array_append_val (signal_data->subscribers, subscriber);
4049 g_hash_table_insert (connection->map_rule_to_signal_data,
4053 /* Add the match rule to the bus...
4055 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
4056 * always send such messages to us.
4058 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
4060 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
4061 add_match_rule (connection, signal_data->rule);
4064 if (connection->kdbus_worker)
4066 if (g_strcmp0 (signal_data->member, "NameAcquired") == 0)
4067 _g_kdbus_subscribe_name_acquired (connection->kdbus_worker, arg0);
4068 else if (g_strcmp0 (signal_data->member, "NameLost") == 0)
4069 _g_kdbus_subscribe_name_lost (connection->kdbus_worker, arg0);
4074 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
4075 signal_data->sender_unique_name);
4076 if (signal_data_array == NULL)
4078 signal_data_array = g_ptr_array_new ();
4079 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
4080 g_strdup (signal_data->sender_unique_name),
4083 g_ptr_array_add (signal_data_array, signal_data);
4086 g_hash_table_insert (connection->map_id_to_signal_data,
4087 GUINT_TO_POINTER (subscriber.id),
4090 CONNECTION_UNLOCK (connection);
4092 return subscriber.id;
4095 /* ---------------------------------------------------------------------------------------------------- */
4097 /* called in any thread */
4098 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
4100 unsubscribe_id_internal (GDBusConnection *connection,
4101 guint subscription_id,
4102 GArray *out_removed_subscribers)
4104 SignalData *signal_data;
4105 GPtrArray *signal_data_array;
4108 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
4109 GUINT_TO_POINTER (subscription_id));
4110 if (signal_data == NULL)
4112 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
4116 for (n = 0; n < signal_data->subscribers->len; n++)
4118 SignalSubscriber *subscriber;
4120 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
4121 if (subscriber->id != subscription_id)
4124 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
4125 GUINT_TO_POINTER (subscription_id)));
4126 g_array_append_val (out_removed_subscribers, *subscriber);
4127 g_array_remove_index (signal_data->subscribers, n);
4129 if (signal_data->subscribers->len == 0)
4131 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
4133 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
4134 signal_data->sender_unique_name);
4135 g_warn_if_fail (signal_data_array != NULL);
4136 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
4138 if (signal_data_array->len == 0)
4140 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
4141 signal_data->sender_unique_name));
4144 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
4145 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
4146 !is_signal_data_for_name_lost_or_acquired (signal_data) &&
4147 !g_dbus_connection_is_closed (connection) &&
4148 !connection->finalizing)
4150 /* The check for g_dbus_connection_is_closed() means that
4151 * sending the RemoveMatch message can't fail with
4152 * G_IO_ERROR_CLOSED, because we're holding the lock,
4153 * so on_worker_closed() can't happen between the check we just
4154 * did, and releasing the lock later.
4156 remove_match_rule (connection, signal_data->rule);
4160 if (connection->kdbus_worker)
4162 if (g_strcmp0 (signal_data->member, "NameAcquired") == 0)
4163 _g_kdbus_unsubscribe_name_acquired (connection->kdbus_worker);
4164 else if (g_strcmp0 (signal_data->member, "NameLost") == 0)
4165 _g_kdbus_unsubscribe_name_lost (connection->kdbus_worker);
4169 signal_data_free (signal_data);
4175 g_assert_not_reached ();
4182 * g_dbus_connection_signal_unsubscribe:
4183 * @connection: a #GDBusConnection
4184 * @subscription_id: a subscription id obtained from
4185 * g_dbus_connection_signal_subscribe()
4187 * Unsubscribes from signals.
4192 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
4193 guint subscription_id)
4195 GArray *subscribers;
4198 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4199 g_return_if_fail (check_initialized (connection));
4201 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
4203 CONNECTION_LOCK (connection);
4204 unsubscribe_id_internal (connection,
4207 CONNECTION_UNLOCK (connection);
4210 g_assert (subscribers->len == 0 || subscribers->len == 1);
4212 /* call GDestroyNotify without lock held */
4213 for (n = 0; n < subscribers->len; n++)
4215 SignalSubscriber *subscriber;
4216 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
4217 call_destroy_notify (subscriber->context,
4218 subscriber->user_data_free_func,
4219 subscriber->user_data);
4220 g_main_context_unref (subscriber->context);
4223 g_array_free (subscribers, TRUE);
4226 /* ---------------------------------------------------------------------------------------------------- */
4230 guint subscription_id;
4231 GDBusSignalCallback callback;
4233 GDBusMessage *message;
4234 GDBusConnection *connection;
4235 const gchar *sender;
4237 const gchar *interface;
4238 const gchar *member;
4241 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
4245 emit_signal_instance_in_idle_cb (gpointer data)
4247 SignalInstance *signal_instance = data;
4248 GVariant *parameters;
4249 gboolean has_subscription;
4251 parameters = g_dbus_message_get_body (signal_instance->message);
4252 if (parameters == NULL)
4254 parameters = g_variant_new ("()");
4255 g_variant_ref_sink (parameters);
4259 g_variant_ref (parameters);
4263 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
4264 signal_instance->subscription_id,
4265 signal_instance->sender,
4266 signal_instance->path,
4267 signal_instance->interface,
4268 signal_instance->member,
4269 g_variant_print (parameters, TRUE));
4272 /* Careful here, don't do the callback if we no longer has the subscription */
4273 CONNECTION_LOCK (signal_instance->connection);
4274 has_subscription = FALSE;
4275 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
4276 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
4277 has_subscription = TRUE;
4278 CONNECTION_UNLOCK (signal_instance->connection);
4280 if (has_subscription)
4281 signal_instance->callback (signal_instance->connection,
4282 signal_instance->sender,
4283 signal_instance->path,
4284 signal_instance->interface,
4285 signal_instance->member,
4287 signal_instance->user_data);
4289 g_variant_unref (parameters);
4295 signal_instance_free (SignalInstance *signal_instance)
4297 g_object_unref (signal_instance->message);
4298 g_object_unref (signal_instance->connection);
4299 g_free (signal_instance);
4303 namespace_rule_matches (const gchar *namespace,
4309 len_namespace = strlen (namespace);
4310 len_name = strlen (name);
4312 if (len_name < len_namespace)
4315 if (memcmp (namespace, name, len_namespace) != 0)
4318 return len_namespace == len_name || name[len_namespace] == '.';
4322 path_rule_matches (const gchar *path_a,
4323 const gchar *path_b)
4327 len_a = strlen (path_a);
4328 len_b = strlen (path_b);
4330 if (len_a < len_b && path_a[len_a - 1] != '/')
4333 if (len_b < len_a && path_b[len_b - 1] != '/')
4336 return memcmp (path_a, path_b, MIN (len_a, len_b)) == 0;
4339 /* called in GDBusWorker thread WITH lock held */
4341 schedule_callbacks (GDBusConnection *connection,
4342 GPtrArray *signal_data_array,
4343 GDBusMessage *message,
4344 const gchar *sender)
4347 const gchar *interface;
4348 const gchar *member;
4357 interface = g_dbus_message_get_interface (message);
4358 member = g_dbus_message_get_member (message);
4359 path = g_dbus_message_get_path (message);
4360 arg0 = g_dbus_message_get_arg0 (message);
4363 g_print ("In schedule_callbacks:\n"
4365 " interface = '%s'\n"
4376 /* TODO: if this is slow, then we can change signal_data_array into
4377 * map_object_path_to_signal_data_array or something.
4379 for (n = 0; n < signal_data_array->len; n++)
4381 SignalData *signal_data = signal_data_array->pdata[n];
4383 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
4386 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
4389 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
4392 if (signal_data->arg0 != NULL)
4397 if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
4399 if (!namespace_rule_matches (signal_data->arg0, arg0))
4402 else if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
4404 if (!path_rule_matches (signal_data->arg0, arg0))
4407 else if (!g_str_equal (signal_data->arg0, arg0))
4411 for (m = 0; m < signal_data->subscribers->len; m++)
4413 SignalSubscriber *subscriber;
4414 GSource *idle_source;
4415 SignalInstance *signal_instance;
4417 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
4419 signal_instance = g_new0 (SignalInstance, 1);
4420 signal_instance->subscription_id = subscriber->id;
4421 signal_instance->callback = subscriber->callback;
4422 signal_instance->user_data = subscriber->user_data;
4423 signal_instance->message = g_object_ref (message);
4424 signal_instance->connection = g_object_ref (connection);
4425 signal_instance->sender = sender;
4426 signal_instance->path = path;
4427 signal_instance->interface = interface;
4428 signal_instance->member = member;
4430 idle_source = g_idle_source_new ();
4431 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4432 g_source_set_callback (idle_source,
4433 emit_signal_instance_in_idle_cb,
4435 (GDestroyNotify) signal_instance_free);
4436 g_source_set_name (idle_source, "[gio] emit_signal_instance_in_idle_cb");
4437 g_source_attach (idle_source, subscriber->context);
4438 g_source_unref (idle_source);
4443 /* called in GDBusWorker thread with lock held */
4445 distribute_signals (GDBusConnection *connection,
4446 GDBusMessage *message)
4448 GPtrArray *signal_data_array;
4449 const gchar *sender;
4451 sender = g_dbus_message_get_sender (message);
4453 if (G_UNLIKELY (_g_dbus_debug_signal ()))
4455 _g_dbus_debug_print_lock ();
4456 g_print ("========================================================================\n"
4457 "GDBus-debug:Signal:\n"
4458 " <<<< RECEIVED SIGNAL %s.%s\n"
4460 " sent by name %s\n",
4461 g_dbus_message_get_interface (message),
4462 g_dbus_message_get_member (message),
4463 g_dbus_message_get_path (message),
4464 sender != NULL ? sender : "(none)");
4465 _g_dbus_debug_print_unlock ();
4468 /* collect subscribers that match on sender */
4471 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
4472 if (signal_data_array != NULL)
4473 schedule_callbacks (connection, signal_data_array, message, sender);
4476 /* collect subscribers not matching on sender */
4477 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
4478 if (signal_data_array != NULL)
4479 schedule_callbacks (connection, signal_data_array, message, sender);
4482 /* ---------------------------------------------------------------------------------------------------- */
4484 /* only called from finalize(), removes all subscriptions */
4486 purge_all_signal_subscriptions (GDBusConnection *connection)
4488 GHashTableIter iter;
4491 GArray *subscribers;
4494 ids = g_array_new (FALSE, FALSE, sizeof (guint));
4495 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
4496 while (g_hash_table_iter_next (&iter, &key, NULL))
4498 guint subscription_id = GPOINTER_TO_UINT (key);
4499 g_array_append_val (ids, subscription_id);
4502 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
4503 for (n = 0; n < ids->len; n++)
4505 guint subscription_id = g_array_index (ids, guint, n);
4506 unsubscribe_id_internal (connection,
4510 g_array_free (ids, TRUE);
4512 /* call GDestroyNotify without lock held */
4513 for (n = 0; n < subscribers->len; n++)
4515 SignalSubscriber *subscriber;
4516 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
4517 call_destroy_notify (subscriber->context,
4518 subscriber->user_data_free_func,
4519 subscriber->user_data);
4520 g_main_context_unref (subscriber->context);
4523 g_array_free (subscribers, TRUE);
4526 /* ---------------------------------------------------------------------------------------------------- */
4528 static GDBusInterfaceVTable *
4529 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
4531 /* Don't waste memory by copying padding - remember to update this
4532 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
4534 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4538 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
4543 /* ---------------------------------------------------------------------------------------------------- */
4545 static GDBusSubtreeVTable *
4546 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
4548 /* Don't waste memory by copying padding - remember to update this
4549 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
4551 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4555 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
4560 /* ---------------------------------------------------------------------------------------------------- */
4562 struct ExportedObject
4565 GDBusConnection *connection;
4567 /* maps gchar* -> ExportedInterface* */
4568 GHashTable *map_if_name_to_ei;
4571 /* only called with lock held */
4573 exported_object_free (ExportedObject *eo)
4575 g_free (eo->object_path);
4576 g_hash_table_unref (eo->map_if_name_to_ei);
4585 gchar *interface_name;
4586 GDBusInterfaceVTable *vtable;
4587 GDBusInterfaceInfo *interface_info;
4589 GMainContext *context;
4591 GDestroyNotify user_data_free_func;
4592 } ExportedInterface;
4594 /* called with lock held */
4596 exported_interface_free (ExportedInterface *ei)
4598 g_dbus_interface_info_cache_release (ei->interface_info);
4599 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
4601 call_destroy_notify (ei->context,
4602 ei->user_data_free_func,
4605 g_main_context_unref (ei->context);
4607 g_free (ei->interface_name);
4608 _g_dbus_interface_vtable_free (ei->vtable);
4612 /* ---------------------------------------------------------------------------------------------------- */
4614 /* Convenience function to check if @registration_id (if not zero) or
4615 * @subtree_registration_id (if not zero) has been unregistered. If
4616 * so, returns %TRUE.
4618 * May be called by any thread. Caller must *not* hold lock.
4621 has_object_been_unregistered (GDBusConnection *connection,
4622 guint registration_id,
4623 guint subtree_registration_id)
4627 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4631 CONNECTION_LOCK (connection);
4632 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
4633 GUINT_TO_POINTER (registration_id)) == NULL)
4637 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
4638 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
4642 CONNECTION_UNLOCK (connection);
4647 /* ---------------------------------------------------------------------------------------------------- */
4651 GDBusConnection *connection;
4652 GDBusMessage *message;
4654 const gchar *property_name;
4655 const GDBusInterfaceVTable *vtable;
4656 GDBusInterfaceInfo *interface_info;
4657 const GDBusPropertyInfo *property_info;
4658 guint registration_id;
4659 guint subtree_registration_id;
4663 property_data_free (PropertyData *data)
4665 g_object_unref (data->connection);
4666 g_object_unref (data->message);
4670 /* called in thread where object was registered - no locks held */
4672 invoke_get_property_in_idle_cb (gpointer _data)
4674 PropertyData *data = _data;
4677 GDBusMessage *reply;
4679 if (has_object_been_unregistered (data->connection,
4680 data->registration_id,
4681 data->subtree_registration_id))
4683 reply = g_dbus_message_new_method_error (data->message,
4684 "org.freedesktop.DBus.Error.UnknownMethod",
4685 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4686 g_dbus_message_get_path (data->message));
4687 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4688 g_object_unref (reply);
4693 value = data->vtable->get_property (data->connection,
4694 g_dbus_message_get_sender (data->message),
4695 g_dbus_message_get_path (data->message),
4696 data->interface_info->name,
4697 data->property_name,
4704 g_assert_no_error (error);
4706 g_variant_take_ref (value);
4707 reply = g_dbus_message_new_method_reply (data->message);
4708 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4709 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4710 g_variant_unref (value);
4711 g_object_unref (reply);
4715 gchar *dbus_error_name;
4716 g_assert (error != NULL);
4717 dbus_error_name = g_dbus_error_encode_gerror (error);
4718 reply = g_dbus_message_new_method_error_literal (data->message,
4721 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4722 g_free (dbus_error_name);
4723 g_error_free (error);
4724 g_object_unref (reply);
4731 /* called in thread where object was registered - no locks held */
4733 invoke_set_property_in_idle_cb (gpointer _data)
4735 PropertyData *data = _data;
4737 GDBusMessage *reply;
4743 g_variant_get (g_dbus_message_get_body (data->message),
4749 if (!data->vtable->set_property (data->connection,
4750 g_dbus_message_get_sender (data->message),
4751 g_dbus_message_get_path (data->message),
4752 data->interface_info->name,
4753 data->property_name,
4758 gchar *dbus_error_name;
4759 g_assert (error != NULL);
4760 dbus_error_name = g_dbus_error_encode_gerror (error);
4761 reply = g_dbus_message_new_method_error_literal (data->message,
4764 g_free (dbus_error_name);
4765 g_error_free (error);
4769 reply = g_dbus_message_new_method_reply (data->message);
4772 g_assert (reply != NULL);
4773 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4774 g_object_unref (reply);
4775 g_variant_unref (value);
4780 /* called in any thread with connection's lock held */
4782 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4783 GDBusMessage *message,
4784 guint registration_id,
4785 guint subtree_registration_id,
4787 GDBusInterfaceInfo *interface_info,
4788 const GDBusInterfaceVTable *vtable,
4789 GMainContext *main_context,
4793 const char *interface_name;
4794 const char *property_name;
4795 const GDBusPropertyInfo *property_info;
4796 GSource *idle_source;
4797 PropertyData *property_data;
4798 GDBusMessage *reply;
4803 g_variant_get (g_dbus_message_get_body (message),
4808 g_variant_get (g_dbus_message_get_body (message),
4817 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4819 property_info = NULL;
4821 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4822 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4823 if (property_info == NULL)
4825 reply = g_dbus_message_new_method_error (message,
4826 "org.freedesktop.DBus.Error.InvalidArgs",
4827 _("No such property '%s'"),
4829 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4830 g_object_unref (reply);
4835 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4837 reply = g_dbus_message_new_method_error (message,
4838 "org.freedesktop.DBus.Error.InvalidArgs",
4839 _("Property '%s' is not readable"),
4841 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4842 g_object_unref (reply);
4846 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4848 reply = g_dbus_message_new_method_error (message,
4849 "org.freedesktop.DBus.Error.InvalidArgs",
4850 _("Property '%s' is not writable"),
4852 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4853 g_object_unref (reply);
4862 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4863 * of the given value is wrong
4865 g_variant_get_child (g_dbus_message_get_body (message), 2, "v", &value);
4866 if (g_strcmp0 (g_variant_get_type_string (value), property_info->signature) != 0)
4868 reply = g_dbus_message_new_method_error (message,
4869 "org.freedesktop.DBus.Error.InvalidArgs",
4870 _("Error setting property '%s': Expected type '%s' but got '%s'"),
4871 property_name, property_info->signature,
4872 g_variant_get_type_string (value));
4873 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4874 g_variant_unref (value);
4875 g_object_unref (reply);
4880 g_variant_unref (value);
4883 /* If the vtable pointer for get_property() resp. set_property() is
4884 * NULL then dispatch the call via the method_call() handler.
4888 if (vtable->get_property == NULL)
4890 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4891 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4892 vtable, main_context, user_data);
4899 if (vtable->set_property == NULL)
4901 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4902 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4903 vtable, main_context, user_data);
4909 /* ok, got the property info - call user code in an idle handler */
4910 property_data = g_new0 (PropertyData, 1);
4911 property_data->connection = g_object_ref (connection);
4912 property_data->message = g_object_ref (message);
4913 property_data->user_data = user_data;
4914 property_data->property_name = property_name;
4915 property_data->vtable = vtable;
4916 property_data->interface_info = interface_info;
4917 property_data->property_info = property_info;
4918 property_data->registration_id = registration_id;
4919 property_data->subtree_registration_id = subtree_registration_id;
4921 idle_source = g_idle_source_new ();
4922 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4923 g_source_set_callback (idle_source,
4924 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4926 (GDestroyNotify) property_data_free);
4928 g_source_set_name (idle_source, "[gio] invoke_get_property_in_idle_cb");
4930 g_source_set_name (idle_source, "[gio] invoke_set_property_in_idle_cb");
4931 g_source_attach (idle_source, main_context);
4932 g_source_unref (idle_source);
4940 /* called in GDBusWorker thread with connection's lock held */
4942 handle_getset_property (GDBusConnection *connection,
4944 GDBusMessage *message,
4947 ExportedInterface *ei;
4949 const char *interface_name;
4950 const char *property_name;
4955 g_variant_get (g_dbus_message_get_body (message),
4960 g_variant_get (g_dbus_message_get_body (message),
4966 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4967 * no such interface registered
4969 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4972 GDBusMessage *reply;
4973 reply = g_dbus_message_new_method_error (message,
4974 "org.freedesktop.DBus.Error.InvalidArgs",
4975 _("No such interface '%s'"),
4977 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4978 g_object_unref (reply);
4983 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4996 /* ---------------------------------------------------------------------------------------------------- */
5000 GDBusConnection *connection;
5001 GDBusMessage *message;
5003 const GDBusInterfaceVTable *vtable;
5004 GDBusInterfaceInfo *interface_info;
5005 guint registration_id;
5006 guint subtree_registration_id;
5007 } PropertyGetAllData;
5010 property_get_all_data_free (PropertyData *data)
5012 g_object_unref (data->connection);
5013 g_object_unref (data->message);
5017 /* called in thread where object was registered - no locks held */
5019 invoke_get_all_properties_in_idle_cb (gpointer _data)
5021 PropertyGetAllData *data = _data;
5022 GVariantBuilder builder;
5023 GDBusMessage *reply;
5026 if (has_object_been_unregistered (data->connection,
5027 data->registration_id,
5028 data->subtree_registration_id))
5030 reply = g_dbus_message_new_method_error (data->message,
5031 "org.freedesktop.DBus.Error.UnknownMethod",
5032 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
5033 g_dbus_message_get_path (data->message));
5034 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5035 g_object_unref (reply);
5039 /* TODO: Right now we never fail this call - we just omit values if
5040 * a get_property() call is failing.
5042 * We could fail the whole call if just a single get_property() call
5043 * returns an error. We need clarification in the D-Bus spec about this.
5045 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
5046 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
5047 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
5049 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
5052 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
5055 value = data->vtable->get_property (data->connection,
5056 g_dbus_message_get_sender (data->message),
5057 g_dbus_message_get_path (data->message),
5058 data->interface_info->name,
5059 property_info->name,
5066 g_variant_take_ref (value);
5067 g_variant_builder_add (&builder,
5069 property_info->name,
5071 g_variant_unref (value);
5073 g_variant_builder_close (&builder);
5075 reply = g_dbus_message_new_method_reply (data->message);
5076 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
5077 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5078 g_object_unref (reply);
5085 interface_has_readable_properties (GDBusInterfaceInfo *interface_info)
5089 if (!interface_info->properties)
5092 for (i = 0; interface_info->properties[i]; i++)
5093 if (interface_info->properties[i]->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE)
5099 /* called in any thread with connection's lock held */
5101 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
5102 GDBusMessage *message,
5103 guint registration_id,
5104 guint subtree_registration_id,
5105 GDBusInterfaceInfo *interface_info,
5106 const GDBusInterfaceVTable *vtable,
5107 GMainContext *main_context,
5111 GSource *idle_source;
5112 PropertyGetAllData *property_get_all_data;
5119 /* If the vtable pointer for get_property() is NULL but we have a
5120 * non-zero number of readable properties, then dispatch the call via
5121 * the method_call() handler.
5123 if (vtable->get_property == NULL && interface_has_readable_properties (interface_info))
5125 schedule_method_call (connection, message, registration_id, subtree_registration_id,
5126 interface_info, NULL, NULL, g_dbus_message_get_body (message),
5127 vtable, main_context, user_data);
5132 /* ok, got the property info - call user in an idle handler */
5133 property_get_all_data = g_new0 (PropertyGetAllData, 1);
5134 property_get_all_data->connection = g_object_ref (connection);
5135 property_get_all_data->message = g_object_ref (message);
5136 property_get_all_data->user_data = user_data;
5137 property_get_all_data->vtable = vtable;
5138 property_get_all_data->interface_info = interface_info;
5139 property_get_all_data->registration_id = registration_id;
5140 property_get_all_data->subtree_registration_id = subtree_registration_id;
5142 idle_source = g_idle_source_new ();
5143 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
5144 g_source_set_callback (idle_source,
5145 invoke_get_all_properties_in_idle_cb,
5146 property_get_all_data,
5147 (GDestroyNotify) property_get_all_data_free);
5148 g_source_set_name (idle_source, "[gio] invoke_get_all_properties_in_idle_cb");
5149 g_source_attach (idle_source, main_context);
5150 g_source_unref (idle_source);
5158 /* called in GDBusWorker thread with connection's lock held */
5160 handle_get_all_properties (GDBusConnection *connection,
5162 GDBusMessage *message)
5164 ExportedInterface *ei;
5166 const char *interface_name;
5170 g_variant_get (g_dbus_message_get_body (message),
5174 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
5175 * no such interface registered
5177 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5180 GDBusMessage *reply;
5181 reply = g_dbus_message_new_method_error (message,
5182 "org.freedesktop.DBus.Error.InvalidArgs",
5183 _("No such interface"),
5185 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5186 g_object_unref (reply);
5191 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
5203 /* ---------------------------------------------------------------------------------------------------- */
5205 static const gchar introspect_header[] =
5206 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
5207 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
5208 "<!-- GDBus " PACKAGE_VERSION " -->\n"
5211 static const gchar introspect_tail[] =
5214 static const gchar introspect_properties_interface[] =
5215 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
5216 " <method name=\"Get\">\n"
5217 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5218 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
5219 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
5221 " <method name=\"GetAll\">\n"
5222 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5223 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
5225 " <method name=\"Set\">\n"
5226 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5227 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
5228 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
5230 " <signal name=\"PropertiesChanged\">\n"
5231 " <arg type=\"s\" name=\"interface_name\"/>\n"
5232 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
5233 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
5237 static const gchar introspect_introspectable_interface[] =
5238 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
5239 " <method name=\"Introspect\">\n"
5240 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
5243 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
5244 " <method name=\"Ping\"/>\n"
5245 " <method name=\"GetMachineId\">\n"
5246 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
5251 introspect_append_header (GString *s)
5253 g_string_append (s, introspect_header);
5257 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
5259 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
5265 begin = object_path + path_len;
5266 end = strchr (begin, '/');
5268 s = g_strndup (begin, end - begin);
5270 s = g_strdup (begin);
5272 if (g_hash_table_lookup (set, s) == NULL)
5273 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
5279 /* TODO: we want a nicer public interface for this */
5280 /* called in any thread with connection's lock held */
5282 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
5287 GHashTableIter hash_iter;
5288 const gchar *object_path;
5294 CONNECTION_ENSURE_LOCK (connection);
5296 path_len = strlen (path);
5300 set = g_hash_table_new (g_str_hash, g_str_equal);
5302 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
5303 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
5304 maybe_add_path (path, path_len, object_path, set);
5306 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
5307 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
5308 maybe_add_path (path, path_len, object_path, set);
5310 p = g_ptr_array_new ();
5311 keys = g_hash_table_get_keys (set);
5312 for (l = keys; l != NULL; l = l->next)
5313 g_ptr_array_add (p, l->data);
5314 g_hash_table_unref (set);
5317 g_ptr_array_add (p, NULL);
5318 ret = (gchar **) g_ptr_array_free (p, FALSE);
5322 /* called in any thread with connection's lock not held */
5324 g_dbus_connection_list_registered (GDBusConnection *connection,
5328 CONNECTION_LOCK (connection);
5329 ret = g_dbus_connection_list_registered_unlocked (connection, path);
5330 CONNECTION_UNLOCK (connection);
5334 /* called in GDBusWorker thread with connection's lock held */
5336 handle_introspect (GDBusConnection *connection,
5338 GDBusMessage *message)
5342 GDBusMessage *reply;
5343 GHashTableIter hash_iter;
5344 ExportedInterface *ei;
5347 /* first the header with the standard interfaces */
5348 s = g_string_sized_new (sizeof (introspect_header) +
5349 sizeof (introspect_properties_interface) +
5350 sizeof (introspect_introspectable_interface) +
5351 sizeof (introspect_tail));
5352 introspect_append_header (s);
5353 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
5354 "org.freedesktop.DBus.Properties"))
5355 g_string_append (s, introspect_properties_interface);
5357 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
5358 "org.freedesktop.DBus.Introspectable"))
5359 g_string_append (s, introspect_introspectable_interface);
5361 /* then include the registered interfaces */
5362 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
5363 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
5364 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
5366 /* finally include nodes registered below us */
5367 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
5368 for (n = 0; registered != NULL && registered[n] != NULL; n++)
5369 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
5370 g_strfreev (registered);
5371 g_string_append (s, introspect_tail);
5373 reply = g_dbus_message_new_method_reply (message);
5374 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5375 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5376 g_object_unref (reply);
5377 g_string_free (s, TRUE);
5382 /* called in thread where object was registered - no locks held */
5384 call_in_idle_cb (gpointer user_data)
5386 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
5387 GDBusInterfaceVTable *vtable;
5388 guint registration_id;
5389 guint subtree_registration_id;
5391 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
5392 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
5394 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
5396 subtree_registration_id))
5398 GDBusMessage *reply;
5399 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
5400 "org.freedesktop.DBus.Error.UnknownMethod",
5401 _("No such interface '%s' on object at path %s"),
5402 g_dbus_method_invocation_get_interface_name (invocation),
5403 g_dbus_method_invocation_get_object_path (invocation));
5404 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5405 g_object_unref (reply);
5409 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
5410 g_assert (vtable != NULL && vtable->method_call != NULL);
5412 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
5413 g_dbus_method_invocation_get_sender (invocation),
5414 g_dbus_method_invocation_get_object_path (invocation),
5415 g_dbus_method_invocation_get_interface_name (invocation),
5416 g_dbus_method_invocation_get_method_name (invocation),
5417 g_dbus_method_invocation_get_parameters (invocation),
5418 g_object_ref (invocation),
5419 g_dbus_method_invocation_get_user_data (invocation));
5425 /* called in GDBusWorker thread with connection's lock held */
5427 schedule_method_call (GDBusConnection *connection,
5428 GDBusMessage *message,
5429 guint registration_id,
5430 guint subtree_registration_id,
5431 const GDBusInterfaceInfo *interface_info,
5432 const GDBusMethodInfo *method_info,
5433 const GDBusPropertyInfo *property_info,
5434 GVariant *parameters,
5435 const GDBusInterfaceVTable *vtable,
5436 GMainContext *main_context,
5439 GDBusMethodInvocation *invocation;
5440 GSource *idle_source;
5442 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
5443 g_dbus_message_get_path (message),
5444 g_dbus_message_get_interface (message),
5445 g_dbus_message_get_member (message),
5453 /* TODO: would be nicer with a real MethodData like we already
5454 * have PropertyData and PropertyGetAllData... */
5455 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
5456 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
5457 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
5459 idle_source = g_idle_source_new ();
5460 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
5461 g_source_set_callback (idle_source,
5465 g_source_set_name (idle_source, "[gio] call_in_idle_cb");
5466 g_source_attach (idle_source, main_context);
5467 g_source_unref (idle_source);
5470 /* called in GDBusWorker thread with connection's lock held */
5472 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
5473 GDBusMessage *message,
5474 guint registration_id,
5475 guint subtree_registration_id,
5476 GDBusInterfaceInfo *interface_info,
5477 const GDBusInterfaceVTable *vtable,
5478 GMainContext *main_context,
5481 GDBusMethodInfo *method_info;
5482 GDBusMessage *reply;
5483 GVariant *parameters;
5485 GVariantType *in_type;
5489 /* TODO: the cost of this is O(n) - it might be worth caching the result */
5490 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
5492 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
5493 * error to the caller
5495 if (method_info == NULL)
5497 reply = g_dbus_message_new_method_error (message,
5498 "org.freedesktop.DBus.Error.UnknownMethod",
5499 _("No such method '%s'"),
5500 g_dbus_message_get_member (message));
5501 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5502 g_object_unref (reply);
5507 parameters = g_dbus_message_get_body (message);
5508 if (parameters == NULL)
5510 parameters = g_variant_new ("()");
5511 g_variant_ref_sink (parameters);
5515 g_variant_ref (parameters);
5518 /* Check that the incoming args are of the right type - if they are not, return
5519 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
5521 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
5522 if (!g_variant_is_of_type (parameters, in_type))
5526 type_string = g_variant_type_dup_string (in_type);
5528 reply = g_dbus_message_new_method_error (message,
5529 "org.freedesktop.DBus.Error.InvalidArgs",
5530 _("Type of message, '%s', does not match expected type '%s'"),
5531 g_variant_get_type_string (parameters),
5533 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5534 g_variant_type_free (in_type);
5535 g_variant_unref (parameters);
5536 g_object_unref (reply);
5537 g_free (type_string);
5541 g_variant_type_free (in_type);
5543 /* schedule the call in idle */
5544 schedule_method_call (connection, message, registration_id, subtree_registration_id,
5545 interface_info, method_info, NULL, parameters,
5546 vtable, main_context, user_data);
5547 g_variant_unref (parameters);
5554 /* ---------------------------------------------------------------------------------------------------- */
5556 /* called in GDBusWorker thread with connection's lock held */
5558 obj_message_func (GDBusConnection *connection,
5560 GDBusMessage *message)
5562 const gchar *interface_name;
5563 const gchar *member;
5564 const gchar *signature;
5569 interface_name = g_dbus_message_get_interface (message);
5570 member = g_dbus_message_get_member (message);
5571 signature = g_dbus_message_get_signature (message);
5573 /* see if we have an interface for handling this call */
5574 if (interface_name != NULL)
5576 ExportedInterface *ei;
5577 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5580 /* we do - invoke the handler in idle in the right thread */
5582 /* handle no vtable or handler being present */
5583 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
5586 handled = validate_and_maybe_schedule_method_call (connection,
5598 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5599 g_strcmp0 (member, "Introspect") == 0 &&
5600 g_strcmp0 (signature, "") == 0)
5602 handled = handle_introspect (connection, eo, message);
5605 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5606 g_strcmp0 (member, "Get") == 0 &&
5607 g_strcmp0 (signature, "ss") == 0)
5609 handled = handle_getset_property (connection, eo, message, TRUE);
5612 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5613 g_strcmp0 (member, "Set") == 0 &&
5614 g_strcmp0 (signature, "ssv") == 0)
5616 handled = handle_getset_property (connection, eo, message, FALSE);
5619 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5620 g_strcmp0 (member, "GetAll") == 0 &&
5621 g_strcmp0 (signature, "s") == 0)
5623 handled = handle_get_all_properties (connection, eo, message);
5632 * g_dbus_connection_register_object:
5633 * @connection: a #GDBusConnection
5634 * @object_path: the object path to register at
5635 * @interface_info: introspection data for the interface
5636 * @vtable: (allow-none): a #GDBusInterfaceVTable to call into or %NULL
5637 * @user_data: (allow-none): data to pass to functions in @vtable
5638 * @user_data_free_func: function to call when the object path is unregistered
5639 * @error: return location for error or %NULL
5641 * Registers callbacks for exported objects at @object_path with the
5642 * D-Bus interface that is described in @interface_info.
5644 * Calls to functions in @vtable (and @user_data_free_func) will happen
5646 * [thread-default main context][g-main-context-push-thread-default]
5647 * of the thread you are calling this method from.
5649 * Note that all #GVariant values passed to functions in @vtable will match
5650 * the signature given in @interface_info - if a remote caller passes
5651 * incorrect values, the `org.freedesktop.DBus.Error.InvalidArgs`
5652 * is returned to the remote caller.
5654 * Additionally, if the remote caller attempts to invoke methods or
5655 * access properties not mentioned in @interface_info the
5656 * `org.freedesktop.DBus.Error.UnknownMethod` resp.
5657 * `org.freedesktop.DBus.Error.InvalidArgs` errors
5658 * are returned to the caller.
5660 * It is considered a programming error if the
5661 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
5662 * #GVariant of incorrect type.
5664 * If an existing callback is already registered at @object_path and
5665 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
5667 * GDBus automatically implements the standard D-Bus interfaces
5668 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
5669 * and org.freedesktop.Peer, so you don't have to implement those for the
5670 * objects you export. You can implement org.freedesktop.DBus.Properties
5671 * yourself, e.g. to handle getting and setting of properties asynchronously.
5673 * Note that the reference count on @interface_info will be
5674 * incremented by 1 (unless allocated statically, e.g. if the
5675 * reference count is -1, see g_dbus_interface_info_ref()) for as long
5676 * as the object is exported. Also note that @vtable will be copied.
5678 * See this [server][gdbus-server] for an example of how to use this method.
5680 * Returns: 0 if @error is set, otherwise a registration id (never 0)
5681 * that can be used with g_dbus_connection_unregister_object()
5686 g_dbus_connection_register_object (GDBusConnection *connection,
5687 const gchar *object_path,
5688 GDBusInterfaceInfo *interface_info,
5689 const GDBusInterfaceVTable *vtable,
5691 GDestroyNotify user_data_free_func,
5695 ExportedInterface *ei;
5698 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5699 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5700 g_return_val_if_fail (interface_info != NULL, 0);
5701 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
5702 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5703 g_return_val_if_fail (check_initialized (connection), 0);
5707 CONNECTION_LOCK (connection);
5709 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5712 eo = g_new0 (ExportedObject, 1);
5713 eo->object_path = g_strdup (object_path);
5714 eo->connection = connection;
5715 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
5718 (GDestroyNotify) exported_interface_free);
5719 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
5722 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
5728 _("An object is already exported for the interface %s at %s"),
5729 interface_info->name,
5734 ei = g_new0 (ExportedInterface, 1);
5735 ei->id = _global_registration_id++; /* TODO: overflow etc. */
5737 ei->user_data = user_data;
5738 ei->user_data_free_func = user_data_free_func;
5739 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
5740 ei->interface_info = g_dbus_interface_info_ref (interface_info);
5741 g_dbus_interface_info_cache_build (ei->interface_info);
5742 ei->interface_name = g_strdup (interface_info->name);
5743 ei->context = g_main_context_ref_thread_default ();
5745 g_hash_table_insert (eo->map_if_name_to_ei,
5746 (gpointer) ei->interface_name,
5748 g_hash_table_insert (connection->map_id_to_ei,
5749 GUINT_TO_POINTER (ei->id),
5755 CONNECTION_UNLOCK (connection);
5761 * g_dbus_connection_unregister_object:
5762 * @connection: a #GDBusConnection
5763 * @registration_id: a registration id obtained from
5764 * g_dbus_connection_register_object()
5766 * Unregisters an object.
5768 * Returns: %TRUE if the object was unregistered, %FALSE otherwise
5773 g_dbus_connection_unregister_object (GDBusConnection *connection,
5774 guint registration_id)
5776 ExportedInterface *ei;
5780 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5781 g_return_val_if_fail (check_initialized (connection), FALSE);
5785 CONNECTION_LOCK (connection);
5787 ei = g_hash_table_lookup (connection->map_id_to_ei,
5788 GUINT_TO_POINTER (registration_id));
5794 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5795 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5796 /* unregister object path if we have no more exported interfaces */
5797 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5798 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5804 CONNECTION_UNLOCK (connection);
5809 /* ---------------------------------------------------------------------------------------------------- */
5812 * g_dbus_connection_emit_signal:
5813 * @connection: a #GDBusConnection
5814 * @destination_bus_name: (allow-none): the unique bus name for the destination
5815 * for the signal or %NULL to emit to all listeners
5816 * @object_path: path of remote object
5817 * @interface_name: D-Bus interface to emit a signal on
5818 * @signal_name: the name of the signal to emit
5819 * @parameters: (allow-none): a #GVariant tuple with parameters for the signal
5820 * or %NULL if not passing parameters
5821 * @error: Return location for error or %NULL
5825 * If the parameters GVariant is floating, it is consumed.
5827 * This can only fail if @parameters is not compatible with the D-Bus protocol.
5829 * Returns: %TRUE unless @error is set
5834 g_dbus_connection_emit_signal (GDBusConnection *connection,
5835 const gchar *destination_bus_name,
5836 const gchar *object_path,
5837 const gchar *interface_name,
5838 const gchar *signal_name,
5839 GVariant *parameters,
5842 GDBusMessage *message;
5848 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5849 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5850 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5851 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5852 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5853 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5854 g_return_val_if_fail (check_initialized (connection), FALSE);
5856 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5858 _g_dbus_debug_print_lock ();
5859 g_print ("========================================================================\n"
5860 "GDBus-debug:Emission:\n"
5861 " >>>> SIGNAL EMISSION %s.%s()\n"
5863 " destination %s\n",
5864 interface_name, signal_name,
5866 destination_bus_name != NULL ? destination_bus_name : "(none)");
5867 _g_dbus_debug_print_unlock ();
5870 message = g_dbus_message_new_signal (object_path,
5874 if (destination_bus_name != NULL)
5875 g_dbus_message_set_header (message,
5876 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5877 g_variant_new_string (destination_bus_name));
5879 if (parameters != NULL)
5880 g_dbus_message_set_body (message, parameters);
5882 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5883 g_object_unref (message);
5889 add_call_flags (GDBusMessage *message,
5890 GDBusCallFlags flags)
5892 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5893 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
5897 decode_method_reply (GDBusMessage *reply,
5898 const gchar *method_name,
5899 const GVariantType *reply_type,
5900 GUnixFDList **out_fd_list,
5906 switch (g_dbus_message_get_message_type (reply))
5908 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5909 result = g_dbus_message_get_body (reply);
5912 result = g_variant_new ("()");
5913 g_variant_ref_sink (result);
5917 g_variant_ref (result);
5920 if (!g_variant_is_of_type (result, reply_type))
5922 gchar *type_string = g_variant_type_dup_string (reply_type);
5926 G_IO_ERROR_INVALID_ARGUMENT,
5927 _("Method '%s' returned type '%s', but expected '%s'"),
5928 method_name, g_variant_get_type_string (result), type_string);
5930 g_variant_unref (result);
5931 g_free (type_string);
5938 if (out_fd_list != NULL)
5940 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5941 if (*out_fd_list != NULL)
5942 g_object_ref (*out_fd_list);
5948 case G_DBUS_MESSAGE_TYPE_ERROR:
5949 g_dbus_message_to_gerror (reply, error);
5953 g_assert_not_reached ();
5963 GSimpleAsyncResult *simple;
5964 GVariantType *reply_type;
5965 gchar *method_name; /* for error message */
5969 GUnixFDList *fd_list;
5973 call_state_free (CallState *state)
5975 g_variant_type_free (state->reply_type);
5976 g_free (state->method_name);
5978 if (state->value != NULL)
5979 g_variant_unref (state->value);
5980 if (state->fd_list != NULL)
5981 g_object_unref (state->fd_list);
5982 g_slice_free (CallState, state);
5985 /* called in any thread, with the connection's lock not held */
5987 g_dbus_connection_call_done (GObject *source,
5988 GAsyncResult *result,
5991 GSimpleAsyncResult *simple;
5992 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5993 CallState *state = user_data;
5995 GDBusMessage *reply;
5998 reply = g_dbus_connection_send_message_with_reply_finish (connection,
6002 if (G_UNLIKELY (_g_dbus_debug_call ()))
6004 _g_dbus_debug_print_lock ();
6005 g_print ("========================================================================\n"
6006 "GDBus-debug:Call:\n"
6007 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
6013 g_print ("SUCCESS\n");
6017 g_print ("FAILED: %s\n",
6020 _g_dbus_debug_print_unlock ();
6024 state->value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
6026 simple = state->simple; /* why? because state is freed before we unref simple.. */
6029 g_simple_async_result_take_error (state->simple, error);
6030 g_simple_async_result_complete (state->simple);
6031 call_state_free (state);
6035 g_simple_async_result_set_op_res_gpointer (state->simple, state, (GDestroyNotify) call_state_free);
6036 g_simple_async_result_complete (state->simple);
6038 g_clear_object (&reply);
6039 g_object_unref (simple);
6042 /* called in any thread, with the connection's lock not held */
6044 g_dbus_connection_call_internal (GDBusConnection *connection,
6045 const gchar *bus_name,
6046 const gchar *object_path,
6047 const gchar *interface_name,
6048 const gchar *method_name,
6049 GVariant *parameters,
6050 const GVariantType *reply_type,
6051 GDBusCallFlags flags,
6053 GUnixFDList *fd_list,
6054 GCancellable *cancellable,
6055 GAsyncReadyCallback callback,
6058 GDBusMessage *message;
6061 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
6062 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
6063 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
6064 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
6065 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
6066 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
6067 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
6068 g_return_if_fail (check_initialized (connection));
6070 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
6072 g_return_if_fail (fd_list == NULL);
6075 message = g_dbus_message_new_method_call (bus_name,
6079 add_call_flags (message, flags);
6080 if (parameters != NULL)
6081 g_dbus_message_set_body (message, parameters);
6084 if (fd_list != NULL)
6085 g_dbus_message_set_unix_fd_list (message, fd_list);
6088 /* If the user has no callback then we can just send the message with
6089 * the G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set and skip all
6090 * the logic for processing the reply. If the service sends the reply
6091 * anyway then it will just be ignored.
6093 if (callback != NULL)
6097 state = g_slice_new0 (CallState);
6098 state->simple = g_simple_async_result_new (G_OBJECT (connection),
6099 callback, user_data,
6100 g_dbus_connection_call_internal);
6101 g_simple_async_result_set_check_cancellable (state->simple, cancellable);
6102 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
6104 if (reply_type == NULL)
6105 reply_type = G_VARIANT_TYPE_ANY;
6107 state->reply_type = g_variant_type_copy (reply_type);
6109 g_dbus_connection_send_message_with_reply (connection,
6111 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
6115 g_dbus_connection_call_done,
6117 serial = state->serial;
6121 GDBusMessageFlags flags;
6123 flags = g_dbus_message_get_flags (message);
6124 flags |= G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
6125 g_dbus_message_set_flags (message, flags);
6127 g_dbus_connection_send_message (connection,
6129 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
6133 if (G_UNLIKELY (_g_dbus_debug_call ()))
6135 _g_dbus_debug_print_lock ();
6136 g_print ("========================================================================\n"
6137 "GDBus-debug:Call:\n"
6138 " >>>> ASYNC %s.%s()\n"
6140 " owned by name %s (serial %d)\n",
6144 bus_name != NULL ? bus_name : "(none)",
6146 _g_dbus_debug_print_unlock ();
6149 if (message != NULL)
6150 g_object_unref (message);
6153 /* called in any thread, with the connection's lock not held */
6155 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
6156 GUnixFDList **out_fd_list,
6160 GSimpleAsyncResult *simple;
6163 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
6164 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
6165 g_dbus_connection_call_internal), NULL);
6166 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6168 simple = G_SIMPLE_ASYNC_RESULT (res);
6170 if (g_simple_async_result_propagate_error (simple, error))
6173 state = g_simple_async_result_get_op_res_gpointer (simple);
6174 if (out_fd_list != NULL)
6175 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
6176 return g_variant_ref (state->value);
6179 /* called in any user thread, with the connection's lock not held */
6181 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
6182 const gchar *bus_name,
6183 const gchar *object_path,
6184 const gchar *interface_name,
6185 const gchar *method_name,
6186 GVariant *parameters,
6187 const GVariantType *reply_type,
6188 GDBusCallFlags flags,
6190 GUnixFDList *fd_list,
6191 GUnixFDList **out_fd_list,
6192 GCancellable *cancellable,
6195 GDBusMessage *message;
6196 GDBusMessage *reply;
6198 GError *local_error;
6199 GDBusSendMessageFlags send_flags;
6205 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
6206 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
6207 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
6208 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
6209 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
6210 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
6211 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
6213 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
6215 g_return_val_if_fail (fd_list == NULL, NULL);
6217 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6219 if (!(flags & CALL_FLAGS_INITIALIZING))
6220 g_return_val_if_fail (check_initialized (connection), FALSE);
6222 if (reply_type == NULL)
6223 reply_type = G_VARIANT_TYPE_ANY;
6225 message = g_dbus_message_new_method_call (bus_name,
6229 add_call_flags (message, flags);
6230 if (parameters != NULL)
6231 g_dbus_message_set_body (message, parameters);
6234 if (fd_list != NULL)
6235 g_dbus_message_set_unix_fd_list (message, fd_list);
6238 if (G_UNLIKELY (_g_dbus_debug_call ()))
6240 _g_dbus_debug_print_lock ();
6241 g_print ("========================================================================\n"
6242 "GDBus-debug:Call:\n"
6243 " >>>> SYNC %s.%s()\n"
6245 " owned by name %s\n",
6249 bus_name != NULL ? bus_name : "(none)");
6250 _g_dbus_debug_print_unlock ();
6255 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
6257 /* translate from one flavour of flags to another... */
6258 if (flags & CALL_FLAGS_INITIALIZING)
6259 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
6261 reply = g_dbus_connection_send_message_with_reply_sync (connection,
6265 NULL, /* volatile guint32 *out_serial */
6269 if (G_UNLIKELY (_g_dbus_debug_call ()))
6271 _g_dbus_debug_print_lock ();
6272 g_print ("========================================================================\n"
6273 "GDBus-debug:Call:\n"
6274 " <<<< SYNC COMPLETE %s.%s()\n"
6280 g_print ("SUCCESS\n");
6284 g_print ("FAILED: %s\n",
6285 local_error->message);
6287 _g_dbus_debug_print_unlock ();
6293 *error = local_error;
6295 g_error_free (local_error);
6299 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
6302 if (message != NULL)
6303 g_object_unref (message);
6305 g_object_unref (reply);
6310 /* ---------------------------------------------------------------------------------------------------- */
6313 * g_dbus_connection_call:
6314 * @connection: a #GDBusConnection
6315 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6316 * @connection is not a message bus connection
6317 * @object_path: path of remote object
6318 * @interface_name: D-Bus interface to invoke method on
6319 * @method_name: the name of the method to invoke
6320 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6321 * or %NULL if not passing parameters
6322 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6323 * @flags: flags from the #GDBusCallFlags enumeration
6324 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6325 * timeout or %G_MAXINT for no timeout
6326 * @cancellable: (allow-none): a #GCancellable or %NULL
6327 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request
6328 * is satisfied or %NULL if you don't care about the result of the
6330 * @user_data: the data to pass to @callback
6332 * Asynchronously invokes the @method_name method on the
6333 * @interface_name D-Bus interface on the remote object at
6334 * @object_path owned by @bus_name.
6336 * If @connection is closed then the operation will fail with
6337 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
6338 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
6339 * not compatible with the D-Bus protocol, the operation fails with
6340 * %G_IO_ERROR_INVALID_ARGUMENT.
6342 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
6343 * error will be raised if it does not match. Said another way, if you give a @reply_type
6344 * then any non-%NULL return value will be of this type.
6346 * If the @parameters #GVariant is floating, it is consumed. This allows
6347 * convenient 'inline' use of g_variant_new(), e.g.:
6348 * |[<!-- language="C" -->
6349 * g_dbus_connection_call (connection,
6350 * "org.freedesktop.StringThings",
6351 * "/org/freedesktop/StringThings",
6352 * "org.freedesktop.StringThings",
6354 * g_variant_new ("(ss)",
6358 * G_DBUS_CALL_FLAGS_NONE,
6361 * (GAsyncReadyCallback) two_strings_done,
6365 * This is an asynchronous method. When the operation is finished,
6366 * @callback will be invoked in the
6367 * [thread-default main context][g-main-context-push-thread-default]
6368 * of the thread you are calling this method from. You can then call
6369 * g_dbus_connection_call_finish() to get the result of the operation.
6370 * See g_dbus_connection_call_sync() for the synchronous version of this
6373 * If @callback is %NULL then the D-Bus method call message will be sent with
6374 * the %G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set.
6379 g_dbus_connection_call (GDBusConnection *connection,
6380 const gchar *bus_name,
6381 const gchar *object_path,
6382 const gchar *interface_name,
6383 const gchar *method_name,
6384 GVariant *parameters,
6385 const GVariantType *reply_type,
6386 GDBusCallFlags flags,
6388 GCancellable *cancellable,
6389 GAsyncReadyCallback callback,
6392 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);
6396 * g_dbus_connection_call_finish:
6397 * @connection: a #GDBusConnection
6398 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call()
6399 * @error: return location for error or %NULL
6401 * Finishes an operation started with g_dbus_connection_call().
6403 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6404 * return values. Free with g_variant_unref().
6409 g_dbus_connection_call_finish (GDBusConnection *connection,
6413 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
6417 * g_dbus_connection_call_sync:
6418 * @connection: a #GDBusConnection
6419 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6420 * @connection is not a message bus connection
6421 * @object_path: path of remote object
6422 * @interface_name: D-Bus interface to invoke method on
6423 * @method_name: the name of the method to invoke
6424 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6425 * or %NULL if not passing parameters
6426 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6427 * @flags: flags from the #GDBusCallFlags enumeration
6428 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6429 * timeout or %G_MAXINT for no timeout
6430 * @cancellable: (allow-none): a #GCancellable or %NULL
6431 * @error: return location for error or %NULL
6433 * Synchronously invokes the @method_name method on the
6434 * @interface_name D-Bus interface on the remote object at
6435 * @object_path owned by @bus_name.
6437 * If @connection is closed then the operation will fail with
6438 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
6439 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
6440 * contains a value not compatible with the D-Bus protocol, the operation
6441 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
6443 * If @reply_type is non-%NULL then the reply will be checked for having
6444 * this type and an error will be raised if it does not match. Said
6445 * another way, if you give a @reply_type then any non-%NULL return
6446 * value will be of this type.
6448 * If the @parameters #GVariant is floating, it is consumed.
6449 * This allows convenient 'inline' use of g_variant_new(), e.g.:
6450 * |[<!-- language="C" -->
6451 * g_dbus_connection_call_sync (connection,
6452 * "org.freedesktop.StringThings",
6453 * "/org/freedesktop/StringThings",
6454 * "org.freedesktop.StringThings",
6456 * g_variant_new ("(ss)",
6460 * G_DBUS_CALL_FLAGS_NONE,
6466 * The calling thread is blocked until a reply is received. See
6467 * g_dbus_connection_call() for the asynchronous version of
6470 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6471 * return values. Free with g_variant_unref().
6476 g_dbus_connection_call_sync (GDBusConnection *connection,
6477 const gchar *bus_name,
6478 const gchar *object_path,
6479 const gchar *interface_name,
6480 const gchar *method_name,
6481 GVariant *parameters,
6482 const GVariantType *reply_type,
6483 GDBusCallFlags flags,
6485 GCancellable *cancellable,
6488 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);
6491 /* ---------------------------------------------------------------------------------------------------- */
6496 * g_dbus_connection_call_with_unix_fd_list:
6497 * @connection: a #GDBusConnection
6498 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6499 * @connection is not a message bus connection
6500 * @object_path: path of remote object
6501 * @interface_name: D-Bus interface to invoke method on
6502 * @method_name: the name of the method to invoke
6503 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6504 * or %NULL if not passing parameters
6505 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6506 * @flags: flags from the #GDBusCallFlags enumeration
6507 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6508 * timeout or %G_MAXINT for no timeout
6509 * @fd_list: (allow-none): a #GUnixFDList or %NULL
6510 * @cancellable: (allow-none): a #GCancellable or %NULL
6511 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request is
6512 * satisfied or %NULL if you don't * care about the result of the
6514 * @user_data: The data to pass to @callback.
6516 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
6518 * This method is only available on UNIX.
6523 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
6524 const gchar *bus_name,
6525 const gchar *object_path,
6526 const gchar *interface_name,
6527 const gchar *method_name,
6528 GVariant *parameters,
6529 const GVariantType *reply_type,
6530 GDBusCallFlags flags,
6532 GUnixFDList *fd_list,
6533 GCancellable *cancellable,
6534 GAsyncReadyCallback callback,
6537 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);
6541 * g_dbus_connection_call_with_unix_fd_list_finish:
6542 * @connection: a #GDBusConnection
6543 * @out_fd_list: (out) (allow-none): return location for a #GUnixFDList or %NULL
6544 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
6545 * g_dbus_connection_call_with_unix_fd_list()
6546 * @error: return location for error or %NULL
6548 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
6550 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6551 * return values. Free with g_variant_unref().
6556 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
6557 GUnixFDList **out_fd_list,
6561 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
6565 * g_dbus_connection_call_with_unix_fd_list_sync:
6566 * @connection: a #GDBusConnection
6567 * @bus_name: (allow-none): a unique or well-known bus name or %NULL
6568 * if @connection is not a message bus connection
6569 * @object_path: path of remote object
6570 * @interface_name: D-Bus interface to invoke method on
6571 * @method_name: the name of the method to invoke
6572 * @parameters: (allow-none): a #GVariant tuple with parameters for
6573 * the method or %NULL if not passing parameters
6574 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6575 * @flags: flags from the #GDBusCallFlags enumeration
6576 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6577 * timeout or %G_MAXINT for no timeout
6578 * @fd_list: (allow-none): a #GUnixFDList or %NULL
6579 * @out_fd_list: (out) (allow-none): return location for a #GUnixFDList or %NULL
6580 * @cancellable: (allow-none): a #GCancellable or %NULL
6581 * @error: return location for error or %NULL
6583 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
6585 * This method is only available on UNIX.
6587 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6588 * return values. Free with g_variant_unref().
6593 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
6594 const gchar *bus_name,
6595 const gchar *object_path,
6596 const gchar *interface_name,
6597 const gchar *method_name,
6598 GVariant *parameters,
6599 const GVariantType *reply_type,
6600 GDBusCallFlags flags,
6602 GUnixFDList *fd_list,
6603 GUnixFDList **out_fd_list,
6604 GCancellable *cancellable,
6607 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);
6610 #endif /* G_OS_UNIX */
6612 /* ---------------------------------------------------------------------------------------------------- */
6614 struct ExportedSubtree
6618 GDBusConnection *connection;
6619 GDBusSubtreeVTable *vtable;
6620 GDBusSubtreeFlags flags;
6622 GMainContext *context;
6624 GDestroyNotify user_data_free_func;
6628 exported_subtree_free (ExportedSubtree *es)
6630 call_destroy_notify (es->context,
6631 es->user_data_free_func,
6634 g_main_context_unref (es->context);
6636 _g_dbus_subtree_vtable_free (es->vtable);
6637 g_free (es->object_path);
6641 /* called without lock held in the thread where the caller registered
6645 handle_subtree_introspect (GDBusConnection *connection,
6646 ExportedSubtree *es,
6647 GDBusMessage *message)
6651 GDBusMessage *reply;
6654 const gchar *sender;
6655 const gchar *requested_object_path;
6656 const gchar *requested_node;
6657 GDBusInterfaceInfo **interfaces;
6659 gchar **subnode_paths;
6660 gboolean has_properties_interface;
6661 gboolean has_introspectable_interface;
6665 requested_object_path = g_dbus_message_get_path (message);
6666 sender = g_dbus_message_get_sender (message);
6667 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6669 s = g_string_new (NULL);
6670 introspect_append_header (s);
6672 /* Strictly we don't need the children in dynamic mode, but we avoid the
6673 * conditionals to preserve code clarity
6675 children = es->vtable->enumerate (es->connection,
6682 requested_node = strrchr (requested_object_path, '/') + 1;
6684 /* Assert existence of object if we are not dynamic */
6685 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
6686 !_g_strv_has_string ((const gchar * const *) children, requested_node))
6691 requested_node = NULL;
6694 interfaces = es->vtable->introspect (es->connection,
6699 if (interfaces != NULL)
6701 has_properties_interface = FALSE;
6702 has_introspectable_interface = FALSE;
6704 for (n = 0; interfaces[n] != NULL; n++)
6706 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
6707 has_properties_interface = TRUE;
6708 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
6709 has_introspectable_interface = TRUE;
6711 if (!has_properties_interface)
6712 g_string_append (s, introspect_properties_interface);
6713 if (!has_introspectable_interface)
6714 g_string_append (s, introspect_introspectable_interface);
6716 for (n = 0; interfaces[n] != NULL; n++)
6718 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
6719 g_dbus_interface_info_unref (interfaces[n]);
6721 g_free (interfaces);
6724 /* then include <node> entries from the Subtree for the root */
6727 for (n = 0; children != NULL && children[n] != NULL; n++)
6728 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
6731 /* finally include nodes registered below us */
6732 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
6733 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
6734 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
6735 g_strfreev (subnode_paths);
6737 g_string_append (s, "</node>\n");
6739 reply = g_dbus_message_new_method_reply (message);
6740 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6741 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6742 g_object_unref (reply);
6747 g_string_free (s, TRUE);
6748 g_strfreev (children);
6752 /* called without lock held in the thread where the caller registered
6756 handle_subtree_method_invocation (GDBusConnection *connection,
6757 ExportedSubtree *es,
6758 GDBusMessage *message)
6761 const gchar *sender;
6762 const gchar *interface_name;
6763 const gchar *member;
6764 const gchar *signature;
6765 const gchar *requested_object_path;
6766 const gchar *requested_node;
6768 GDBusInterfaceInfo *interface_info;
6769 const GDBusInterfaceVTable *interface_vtable;
6770 gpointer interface_user_data;
6772 GDBusInterfaceInfo **interfaces;
6773 gboolean is_property_get;
6774 gboolean is_property_set;
6775 gboolean is_property_get_all;
6780 requested_object_path = g_dbus_message_get_path (message);
6781 sender = g_dbus_message_get_sender (message);
6782 interface_name = g_dbus_message_get_interface (message);
6783 member = g_dbus_message_get_member (message);
6784 signature = g_dbus_message_get_signature (message);
6785 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6787 is_property_get = FALSE;
6788 is_property_set = FALSE;
6789 is_property_get_all = FALSE;
6790 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6792 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6793 is_property_get = TRUE;
6794 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6795 is_property_set = TRUE;
6796 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6797 is_property_get_all = TRUE;
6802 requested_node = strrchr (requested_object_path, '/') + 1;
6804 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6806 /* We don't want to dispatch to unenumerated
6807 * nodes, so ensure that the child exists.
6812 children = es->vtable->enumerate (es->connection,
6817 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6818 g_strfreev (children);
6826 requested_node = NULL;
6829 /* get introspection data for the node */
6830 interfaces = es->vtable->introspect (es->connection,
6832 requested_object_path,
6836 if (interfaces == NULL)
6839 interface_info = NULL;
6840 for (n = 0; interfaces[n] != NULL; n++)
6842 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6843 interface_info = interfaces[n];
6846 /* dispatch the call if the user wants to handle it */
6847 if (interface_info != NULL)
6849 /* figure out where to dispatch the method call */
6850 interface_user_data = NULL;
6851 interface_vtable = es->vtable->dispatch (es->connection,
6856 &interface_user_data,
6858 if (interface_vtable == NULL)
6861 CONNECTION_LOCK (connection);
6862 handled = validate_and_maybe_schedule_method_call (es->connection,
6869 interface_user_data);
6870 CONNECTION_UNLOCK (connection);
6872 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6873 else if (is_property_get || is_property_set || is_property_get_all)
6875 if (is_property_get)
6876 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6877 else if (is_property_set)
6878 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6879 else if (is_property_get_all)
6880 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6882 g_assert_not_reached ();
6884 /* see if the object supports this interface at all */
6885 for (n = 0; interfaces[n] != NULL; n++)
6887 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6888 interface_info = interfaces[n];
6891 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6892 * claims it won't support the interface
6894 if (interface_info == NULL)
6896 GDBusMessage *reply;
6897 reply = g_dbus_message_new_method_error (message,
6898 "org.freedesktop.DBus.Error.InvalidArgs",
6899 _("No such interface '%s'"),
6901 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6902 g_object_unref (reply);
6907 /* figure out where to dispatch the property get/set/getall calls */
6908 interface_user_data = NULL;
6909 interface_vtable = es->vtable->dispatch (es->connection,
6914 &interface_user_data,
6916 if (interface_vtable == NULL)
6918 g_warning ("The subtree introspection function indicates that '%s' "
6919 "is a valid interface name, but calling the dispatch "
6920 "function on that interface gave us NULL", interface_name);
6924 if (is_property_get || is_property_set)
6926 CONNECTION_LOCK (connection);
6927 handled = validate_and_maybe_schedule_property_getset (es->connection,
6935 interface_user_data);
6936 CONNECTION_UNLOCK (connection);
6938 else if (is_property_get_all)
6940 CONNECTION_LOCK (connection);
6941 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6948 interface_user_data);
6949 CONNECTION_UNLOCK (connection);
6954 if (interfaces != NULL)
6956 for (n = 0; interfaces[n] != NULL; n++)
6957 g_dbus_interface_info_unref (interfaces[n]);
6958 g_free (interfaces);
6966 GDBusMessage *message;
6967 ExportedSubtree *es;
6968 } SubtreeDeferredData;
6971 subtree_deferred_data_free (SubtreeDeferredData *data)
6973 g_object_unref (data->message);
6977 /* called without lock held in the thread where the caller registered the subtree */
6979 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6981 SubtreeDeferredData *data = _data;
6986 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6987 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6988 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6989 handled = handle_subtree_introspect (data->es->connection,
6993 handled = handle_subtree_method_invocation (data->es->connection,
6999 CONNECTION_LOCK (data->es->connection);
7000 handled = handle_generic_unlocked (data->es->connection, data->message);
7001 CONNECTION_UNLOCK (data->es->connection);
7004 /* if we couldn't handle the request, just bail with the UnknownMethod error */
7007 GDBusMessage *reply;
7008 reply = g_dbus_message_new_method_error (data->message,
7009 "org.freedesktop.DBus.Error.UnknownMethod",
7010 _("Method '%s' on interface '%s' with signature '%s' does not exist"),
7011 g_dbus_message_get_member (data->message),
7012 g_dbus_message_get_interface (data->message),
7013 g_dbus_message_get_signature (data->message));
7014 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7015 g_object_unref (reply);
7021 /* called in GDBusWorker thread with connection's lock held */
7023 subtree_message_func (GDBusConnection *connection,
7024 ExportedSubtree *es,
7025 GDBusMessage *message)
7027 GSource *idle_source;
7028 SubtreeDeferredData *data;
7030 data = g_new0 (SubtreeDeferredData, 1);
7031 data->message = g_object_ref (message);
7034 /* defer this call to an idle handler in the right thread */
7035 idle_source = g_idle_source_new ();
7036 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
7037 g_source_set_callback (idle_source,
7038 process_subtree_vtable_message_in_idle_cb,
7040 (GDestroyNotify) subtree_deferred_data_free);
7041 g_source_set_name (idle_source, "[gio] process_subtree_vtable_message_in_idle_cb");
7042 g_source_attach (idle_source, es->context);
7043 g_source_unref (idle_source);
7045 /* since we own the entire subtree, handlers for objects not in the subtree have been
7046 * tried already by libdbus-1 - so we just need to ensure that we're always going
7047 * to reply to the message
7053 * g_dbus_connection_register_subtree:
7054 * @connection: a #GDBusConnection
7055 * @object_path: the object path to register the subtree at
7056 * @vtable: a #GDBusSubtreeVTable to enumerate, introspect and
7057 * dispatch nodes in the subtree
7058 * @flags: flags used to fine tune the behavior of the subtree
7059 * @user_data: data to pass to functions in @vtable
7060 * @user_data_free_func: function to call when the subtree is unregistered
7061 * @error: return location for error or %NULL
7063 * Registers a whole subtree of dynamic objects.
7065 * The @enumerate and @introspection functions in @vtable are used to
7066 * convey, to remote callers, what nodes exist in the subtree rooted
7069 * When handling remote calls into any node in the subtree, first the
7070 * @enumerate function is used to check if the node exists. If the node exists
7071 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
7072 * the @introspection function is used to check if the node supports the
7073 * requested method. If so, the @dispatch function is used to determine
7074 * where to dispatch the call. The collected #GDBusInterfaceVTable and
7075 * #gpointer will be used to call into the interface vtable for processing
7078 * All calls into user-provided code will be invoked in the
7079 * [thread-default main context][g-main-context-push-thread-default]
7080 * of the thread you are calling this method from.
7082 * If an existing subtree is already registered at @object_path or
7083 * then @error is set to #G_IO_ERROR_EXISTS.
7085 * Note that it is valid to register regular objects (using
7086 * g_dbus_connection_register_object()) in a subtree registered with
7087 * g_dbus_connection_register_subtree() - if so, the subtree handler
7088 * is tried as the last resort. One way to think about a subtree
7089 * handler is to consider it a fallback handler for object paths not
7090 * registered via g_dbus_connection_register_object() or other bindings.
7092 * Note that @vtable will be copied so you cannot change it after
7095 * See this [server][gdbus-subtree-server] for an example of how to use
7098 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
7099 * that can be used with g_dbus_connection_unregister_subtree() .
7104 g_dbus_connection_register_subtree (GDBusConnection *connection,
7105 const gchar *object_path,
7106 const GDBusSubtreeVTable *vtable,
7107 GDBusSubtreeFlags flags,
7109 GDestroyNotify user_data_free_func,
7113 ExportedSubtree *es;
7115 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
7116 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
7117 g_return_val_if_fail (vtable != NULL, 0);
7118 g_return_val_if_fail (error == NULL || *error == NULL, 0);
7119 g_return_val_if_fail (check_initialized (connection), 0);
7123 CONNECTION_LOCK (connection);
7125 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
7131 _("A subtree is already exported for %s"),
7136 es = g_new0 (ExportedSubtree, 1);
7137 es->object_path = g_strdup (object_path);
7138 es->connection = connection;
7140 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
7142 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
7143 es->user_data = user_data;
7144 es->user_data_free_func = user_data_free_func;
7145 es->context = g_main_context_ref_thread_default ();
7147 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
7148 g_hash_table_insert (connection->map_id_to_es,
7149 GUINT_TO_POINTER (es->id),
7155 CONNECTION_UNLOCK (connection);
7160 /* ---------------------------------------------------------------------------------------------------- */
7163 * g_dbus_connection_unregister_subtree:
7164 * @connection: a #GDBusConnection
7165 * @registration_id: a subtree registration id obtained from
7166 * g_dbus_connection_register_subtree()
7168 * Unregisters a subtree.
7170 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise
7175 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
7176 guint registration_id)
7178 ExportedSubtree *es;
7181 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
7182 g_return_val_if_fail (check_initialized (connection), FALSE);
7186 CONNECTION_LOCK (connection);
7188 es = g_hash_table_lookup (connection->map_id_to_es,
7189 GUINT_TO_POINTER (registration_id));
7193 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
7194 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
7199 CONNECTION_UNLOCK (connection);
7204 /* ---------------------------------------------------------------------------------------------------- */
7206 /* may be called in any thread, with connection's lock held */
7208 handle_generic_ping_unlocked (GDBusConnection *connection,
7209 const gchar *object_path,
7210 GDBusMessage *message)
7212 GDBusMessage *reply;
7213 reply = g_dbus_message_new_method_reply (message);
7214 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7215 g_object_unref (reply);
7218 /* may be called in any thread, with connection's lock held */
7220 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
7221 const gchar *object_path,
7222 GDBusMessage *message)
7224 GDBusMessage *reply;
7227 if (connection->machine_id == NULL)
7232 connection->machine_id = _g_dbus_get_machine_id (&error);
7233 if (connection->machine_id == NULL)
7235 reply = g_dbus_message_new_method_error_literal (message,
7236 "org.freedesktop.DBus.Error.Failed",
7238 g_error_free (error);
7244 reply = g_dbus_message_new_method_reply (message);
7245 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
7247 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7248 g_object_unref (reply);
7251 /* may be called in any thread, with connection's lock held */
7253 handle_generic_introspect_unlocked (GDBusConnection *connection,
7254 const gchar *object_path,
7255 GDBusMessage *message)
7260 GDBusMessage *reply;
7262 /* first the header */
7263 s = g_string_new (NULL);
7264 introspect_append_header (s);
7266 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
7267 for (n = 0; registered != NULL && registered[n] != NULL; n++)
7268 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
7269 g_strfreev (registered);
7270 g_string_append (s, "</node>\n");
7272 reply = g_dbus_message_new_method_reply (message);
7273 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
7274 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7275 g_object_unref (reply);
7276 g_string_free (s, TRUE);
7279 /* may be called in any thread, with connection's lock held */
7281 handle_generic_unlocked (GDBusConnection *connection,
7282 GDBusMessage *message)
7285 const gchar *interface_name;
7286 const gchar *member;
7287 const gchar *signature;
7290 CONNECTION_ENSURE_LOCK (connection);
7294 interface_name = g_dbus_message_get_interface (message);
7295 member = g_dbus_message_get_member (message);
7296 signature = g_dbus_message_get_signature (message);
7297 path = g_dbus_message_get_path (message);
7299 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
7300 g_strcmp0 (member, "Introspect") == 0 &&
7301 g_strcmp0 (signature, "") == 0)
7303 handle_generic_introspect_unlocked (connection, path, message);
7306 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7307 g_strcmp0 (member, "Ping") == 0 &&
7308 g_strcmp0 (signature, "") == 0)
7310 handle_generic_ping_unlocked (connection, path, message);
7313 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7314 g_strcmp0 (member, "GetMachineId") == 0 &&
7315 g_strcmp0 (signature, "") == 0)
7317 handle_generic_get_machine_id_unlocked (connection, path, message);
7324 /* ---------------------------------------------------------------------------------------------------- */
7326 /* called in GDBusWorker thread with connection's lock held */
7328 distribute_method_call (GDBusConnection *connection,
7329 GDBusMessage *message)
7331 GDBusMessage *reply;
7333 ExportedSubtree *es;
7334 const gchar *object_path;
7335 const gchar *interface_name;
7336 const gchar *member;
7338 gchar *subtree_path;
7341 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
7343 interface_name = g_dbus_message_get_interface (message);
7344 member = g_dbus_message_get_member (message);
7345 path = g_dbus_message_get_path (message);
7346 subtree_path = g_strdup (path);
7347 needle = strrchr (subtree_path, '/');
7348 if (needle != NULL && needle != subtree_path)
7354 g_free (subtree_path);
7355 subtree_path = NULL;
7359 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
7361 _g_dbus_debug_print_lock ();
7362 g_print ("========================================================================\n"
7363 "GDBus-debug:Incoming:\n"
7364 " <<<< METHOD INVOCATION %s.%s()\n"
7366 " invoked by name %s\n"
7368 interface_name, member,
7370 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
7371 g_dbus_message_get_serial (message));
7372 _g_dbus_debug_print_unlock ();
7375 object_path = g_dbus_message_get_path (message);
7376 g_assert (object_path != NULL);
7378 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
7381 if (obj_message_func (connection, eo, message))
7385 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
7388 if (subtree_message_func (connection, es, message))
7392 if (subtree_path != NULL)
7394 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
7397 if (subtree_message_func (connection, es, message))
7402 if (handle_generic_unlocked (connection, message))
7405 /* if we end up here, the message has not been not handled - so return an error saying this */
7406 reply = g_dbus_message_new_method_error (message,
7407 "org.freedesktop.DBus.Error.UnknownMethod",
7408 _("No such interface '%s' on object at path %s"),
7411 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7412 g_object_unref (reply);
7415 g_free (subtree_path);
7418 /* ---------------------------------------------------------------------------------------------------- */
7420 /* Called in any user thread, with the message_bus_lock held. */
7422 message_bus_get_singleton (GBusType bus_type,
7426 const gchar *starter_bus;
7432 case G_BUS_TYPE_SESSION:
7433 ret = &the_session_bus;
7436 case G_BUS_TYPE_SYSTEM:
7437 ret = &the_system_bus;
7440 case G_BUS_TYPE_USER:
7441 ret = &the_user_bus;
7444 case G_BUS_TYPE_MACHINE:
7445 ret = &the_machine_bus;
7448 case G_BUS_TYPE_STARTER:
7449 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
7450 if (g_strcmp0 (starter_bus, "session") == 0)
7452 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
7455 else if (g_strcmp0 (starter_bus, "system") == 0)
7457 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
7462 if (starter_bus != NULL)
7466 G_IO_ERROR_INVALID_ARGUMENT,
7467 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
7468 " - unknown value '%s'"),
7473 g_set_error_literal (error,
7475 G_IO_ERROR_INVALID_ARGUMENT,
7476 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
7477 "variable is not set"));
7483 g_assert_not_reached ();
7491 /* Called in any user thread, without holding locks. */
7492 static GDBusConnection *
7493 get_uninitialized_connection (GBusType bus_type,
7494 GCancellable *cancellable,
7497 GWeakRef *singleton;
7498 GDBusConnection *ret;
7502 G_LOCK (message_bus_lock);
7503 singleton = message_bus_get_singleton (bus_type, error);
7504 if (singleton == NULL)
7507 ret = g_weak_ref_get (singleton);
7512 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
7513 if (address == NULL)
7515 ret = g_object_new (G_TYPE_DBUS_CONNECTION,
7517 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
7518 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
7519 "exit-on-close", TRUE,
7522 g_weak_ref_set (singleton, ret);
7526 g_assert (ret != NULL);
7529 G_UNLOCK (message_bus_lock);
7533 /* May be called from any thread. Must not hold message_bus_lock. */
7535 _g_bus_get_singleton_if_exists (GBusType bus_type)
7537 GWeakRef *singleton;
7538 GDBusConnection *ret = NULL;
7540 G_LOCK (message_bus_lock);
7541 singleton = message_bus_get_singleton (bus_type, NULL);
7542 if (singleton == NULL)
7545 ret = g_weak_ref_get (singleton);
7548 G_UNLOCK (message_bus_lock);
7554 * @bus_type: a #GBusType
7555 * @cancellable: (allow-none): a #GCancellable or %NULL
7556 * @error: return location for error or %NULL
7558 * Synchronously connects to the message bus specified by @bus_type.
7559 * Note that the returned object may shared with other callers,
7560 * e.g. if two separate parts of a process calls this function with
7561 * the same @bus_type, they will share the same object.
7563 * This is a synchronous failable function. See g_bus_get() and
7564 * g_bus_get_finish() for the asynchronous version.
7566 * The returned object is a singleton, that is, shared with other
7567 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7568 * event that you need a private message bus connection, use
7569 * g_dbus_address_get_for_bus_sync() and
7570 * g_dbus_connection_new_for_address().
7572 * Note that the returned #GDBusConnection object will (usually) have
7573 * the #GDBusConnection:exit-on-close property set to %TRUE.
7575 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7576 * Free with g_object_unref().
7581 g_bus_get_sync (GBusType bus_type,
7582 GCancellable *cancellable,
7585 GDBusConnection *connection;
7587 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7589 connection = get_uninitialized_connection (bus_type, cancellable, error);
7590 if (connection == NULL)
7593 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
7595 g_object_unref (connection);
7604 bus_get_async_initable_cb (GObject *source_object,
7608 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
7612 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
7616 g_assert (error != NULL);
7617 g_simple_async_result_take_error (simple, error);
7618 g_object_unref (source_object);
7622 g_simple_async_result_set_op_res_gpointer (simple,
7626 g_simple_async_result_complete_in_idle (simple);
7627 g_object_unref (simple);
7632 * @bus_type: a #GBusType
7633 * @cancellable: (allow-none): a #GCancellable or %NULL
7634 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
7635 * @user_data: the data to pass to @callback
7637 * Asynchronously connects to the message bus specified by @bus_type.
7639 * When the operation is finished, @callback will be invoked. You can
7640 * then call g_bus_get_finish() to get the result of the operation.
7642 * This is a asynchronous failable function. See g_bus_get_sync() for
7643 * the synchronous version.
7648 g_bus_get (GBusType bus_type,
7649 GCancellable *cancellable,
7650 GAsyncReadyCallback callback,
7653 GDBusConnection *connection;
7654 GSimpleAsyncResult *simple;
7657 simple = g_simple_async_result_new (NULL,
7661 g_simple_async_result_set_check_cancellable (simple, cancellable);
7664 connection = get_uninitialized_connection (bus_type, cancellable, &error);
7665 if (connection == NULL)
7667 g_assert (error != NULL);
7668 g_simple_async_result_take_error (simple, error);
7669 g_simple_async_result_complete_in_idle (simple);
7670 g_object_unref (simple);
7674 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
7677 bus_get_async_initable_cb,
7684 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
7686 * @error: return location for error or %NULL
7688 * Finishes an operation started with g_bus_get().
7690 * The returned object is a singleton, that is, shared with other
7691 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7692 * event that you need a private message bus connection, use
7693 * g_dbus_address_get_for_bus_sync() and
7694 * g_dbus_connection_new_for_address().
7696 * Note that the returned #GDBusConnection object will (usually) have
7697 * the #GDBusConnection:exit-on-close property set to %TRUE.
7699 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7700 * Free with g_object_unref().
7705 g_bus_get_finish (GAsyncResult *res,
7708 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
7710 GDBusConnection *ret;
7712 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7714 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
7718 if (g_simple_async_result_propagate_error (simple, error))
7721 object = g_simple_async_result_get_op_res_gpointer (simple);
7722 g_assert (object != NULL);
7723 ret = g_object_ref (G_DBUS_CONNECTION (object));
7729 /* ---------------------------------------------------------------------------------------------------- */