1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
18 * Author: David Zeuthen <davidz@redhat.com>
24 * - would be nice to expose GDBusAuthMechanism and an extension point
26 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
27 * the mechanism VFuncs need to be able to set an error.
29 * - Need to document other mechanisms/sources for determining the D-Bus
30 * address of a well-known bus.
32 * - e.g. on Win32 we need code like from here
34 * http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
36 * that was never copied over here because it originally was copy-paste
37 * from the GPLv2 / AFL 2.1 libdbus sources.
39 * - on OS X we need to look in launchd for the address
41 * https://bugs.freedesktop.org/show_bug.cgi?id=14259
43 * - on X11 we need to look in a X11 property on the X server
44 * - (we can also just use dbus-launch(1) from the D-Bus
47 * - (ideally) this requires D-Bus spec work because none of
48 * this has never really been specced out properly (except
51 * - Related to the above, we also need to be able to launch a message bus
52 * instance.... Since we don't want to write our own bus daemon we should
53 * launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
55 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
56 * to specify where the nonce is stored. This will allow people to use
57 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
58 * to easily achieve secure RPC via nonce-tcp.
60 * - need to expose an extension point for resolving D-Bus address and
61 * turning them into GIOStream objects. This will allow us to implement
62 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
64 * - see g_dbus_address_connect() in gdbusaddress.c
66 * - would be cute to use kernel-specific APIs to resolve fds for
67 * debug output when using G_DBUS_DEBUG=message, e.g. in addition to
69 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
71 * maybe we can show more information about what fd 21 really is.
72 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
73 * Initial experiments on Linux 2.6 suggests that the symlink looks
78 * e.g. not of much use.
80 * - GDBus High-Level docs
81 * - Proxy: properties, signals...
82 * - Connection: IOStream based, ::close, connection setup steps
83 * mainloop integration, threading
84 * - Differences from libdbus (extend "Migrating from")
85 * - the message handling thread
86 * - Using GVariant instead of GValue
87 * - Explain why the high-level API is a good thing and what
88 * kind of pitfalls it avoids
89 * - Export objects before claiming names
90 * - Talk about auto-starting services (cf. GBusNameWatcherFlags)
92 * - use abstract sockets in test code
93 * - right now it doesn't work, dbus-daemon(1) fails with
95 * /gdbus/connection/filter: Failed to start message bus: Failed to bind
96 * socket "/tmp/g-dbus-tests-pid-28531": Address already in use
97 * ** WARNING **: Error reading address from dbus daemon, 0 bytes read
107 #include "gdbusauth.h"
108 #include "gdbusutils.h"
109 #include "gdbusaddress.h"
110 #include "gdbusmessage.h"
111 #include "gdbusconnection.h"
112 #include "gdbuserror.h"
113 #include "gioenumtypes.h"
114 #include "gdbusintrospection.h"
115 #include "gdbusmethodinvocation.h"
116 #include "gdbusprivate.h"
117 #include "gdbusauthobserver.h"
118 #include "ginitable.h"
119 #include "gasyncinitable.h"
120 #include "giostream.h"
121 #include "gasyncresult.h"
122 #include "gsimpleasyncresult.h"
125 #include "gunixconnection.h"
126 #include "gunixfdmessage.h"
129 #include "glibintl.h"
132 * SECTION:gdbusconnection
133 * @short_description: D-Bus Connections
134 * @include: gio/gio.h
136 * The #GDBusConnection type is used for D-Bus connections to remote
137 * peers such as a message buses. It is a low-level API that offers a
138 * lot of flexibility. For instance, it lets you establish a connection
139 * over any transport that can by represented as an #GIOStream.
141 * This class is rarely used directly in D-Bus clients. If you are writing
142 * a D-Bus client, it is often easier to use the g_bus_own_name(),
143 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
145 * As an exception to the usual GLib rule that a particular object must not
146 * be used by two threads at the same time, #GDBusConnection's methods may be
147 * called from any thread. This is so that g_bus_get() and g_bus_get_sync()
148 * can safely return the same #GDBusConnection when called from any thread.
150 * Most of the ways to obtain a #GDBusConnection automatically initialize it
151 * (i.e. connect to D-Bus): for instance, g_dbus_connection_new() and
152 * g_bus_get(), and the synchronous versions of those methods, give you an
153 * initialized connection. Language bindings for GIO should use
154 * g_initable_new() or g_async_initable_new_async(), which also initialize the
157 * If you construct an uninitialized #GDBusConnection, such as via
158 * g_object_new(), you must initialize it via g_initable_init() or
159 * g_async_initable_init_async() before using its methods or properties.
160 * Calling methods or accessing properties on a #GDBusConnection that has not
161 * completed initialization successfully is considered to be invalid, and leads
162 * to undefined behaviour. In particular, if initialization fails with a
163 * #GError, the only valid thing you can do with that #GDBusConnection is to
164 * free it with g_object_unref().
166 * ## An example D-Bus server # {#gdbus-server}
168 * Here is an example for a D-Bus server:
169 * [gdbus-example-server.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-server.c)
171 * ## An example for exporting a subtree # {#gdbus-subtree-server}
173 * Here is an example for exporting a subtree:
174 * [gdbus-example-subtree.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-subtree.c)
176 * ## An example for file descriptor passing # {#gdbus-unix-fd-client}
178 * Here is an example for passing UNIX file descriptors:
179 * [gdbus-unix-fd-client.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-unix-fd-client.c)
181 * ## An example for exporting a GObject # {#gdbus-export}
183 * Here is an example for exporting a #GObject:
184 * [gdbus-example-export.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-export.c)
187 /* ---------------------------------------------------------------------------------------------------- */
189 typedef struct _GDBusConnectionClass GDBusConnectionClass;
192 * GDBusConnectionClass:
193 * @closed: Signal class handler for the #GDBusConnection::closed signal.
195 * Class structure for #GDBusConnection.
199 struct _GDBusConnectionClass
202 GObjectClass parent_class;
206 void (*closed) (GDBusConnection *connection,
207 gboolean remote_peer_vanished,
211 G_LOCK_DEFINE_STATIC (message_bus_lock);
213 static GWeakRef the_session_bus;
214 static GWeakRef the_system_bus;
215 static GWeakRef the_user_bus;
216 static GWeakRef the_machine_bus;
218 /* Extra pseudo-member of GDBusSendMessageFlags.
219 * Set by initable_init() to indicate that despite not being initialized yet,
220 * enough of the only-valid-after-init members are set that we can send a
221 * message, and we're being called from its thread, so no memory barrier is
222 * required before accessing them.
224 #define SEND_MESSAGE_FLAGS_INITIALIZING (1<<31)
226 /* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
227 #define CALL_FLAGS_INITIALIZING (1<<31)
229 /* ---------------------------------------------------------------------------------------------------- */
233 GDestroyNotify callback;
235 GMainContext *context;
236 } CallDestroyNotifyData;
239 call_destroy_notify_data_in_idle (gpointer user_data)
241 CallDestroyNotifyData *data = user_data;
242 data->callback (data->user_data);
247 call_destroy_notify_data_free (CallDestroyNotifyData *data)
249 if (data->context != NULL)
250 g_main_context_unref (data->context);
255 * call_destroy_notify: <internal>
256 * @context: (allow-none): A #GMainContext or %NULL.
257 * @callback: (allow-none): A #GDestroyNotify or %NULL.
258 * @user_data: Data to pass to @callback.
260 * Schedules @callback to run in @context.
263 call_destroy_notify (GMainContext *context,
264 GDestroyNotify callback,
267 GSource *idle_source;
268 CallDestroyNotifyData *data;
270 if (callback == NULL)
273 data = g_new0 (CallDestroyNotifyData, 1);
274 data->callback = callback;
275 data->user_data = user_data;
276 data->context = context;
277 if (data->context != NULL)
278 g_main_context_ref (data->context);
280 idle_source = g_idle_source_new ();
281 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
282 g_source_set_callback (idle_source,
283 call_destroy_notify_data_in_idle,
285 (GDestroyNotify) call_destroy_notify_data_free);
286 g_source_set_name (idle_source, "[gio] call_destroy_notify_data_in_idle");
287 g_source_attach (idle_source, data->context);
288 g_source_unref (idle_source);
294 /* ---------------------------------------------------------------------------------------------------- */
297 _g_strv_has_string (const gchar* const *haystack,
302 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
304 if (g_strcmp0 (haystack[n], needle) == 0)
310 /* ---------------------------------------------------------------------------------------------------- */
313 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
315 // TODO: for some reason this doesn't work on Windows
316 #define CONNECTION_ENSURE_LOCK(obj) do { \
317 if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock))) \
319 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
320 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
325 #define CONNECTION_LOCK(obj) do { \
326 g_mutex_lock (&(obj)->lock); \
329 #define CONNECTION_UNLOCK(obj) do { \
330 g_mutex_unlock (&(obj)->lock); \
333 /* Flags in connection->atomic_flags */
335 FLAG_INITIALIZED = 1 << 0,
336 FLAG_EXIT_ON_CLOSE = 1 << 1,
343 * The #GDBusConnection structure contains only private data and
344 * should only be accessed using the provided API.
348 struct _GDBusConnection
351 GObject parent_instance;
353 /* ------------------------------------------------------------------------ */
354 /* -- General object state ------------------------------------------------ */
355 /* ------------------------------------------------------------------------ */
357 /* General-purpose lock for most fields */
360 /* A lock used in the init() method of the GInitable interface - see comments
361 * in initable_init() for why a separate lock is needed.
363 * If you need both @lock and @init_lock, you must take @init_lock first.
367 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
368 * someone calls org.freedesktop.DBus.Peer.GetMachineId(). Protected by @lock.
372 /* The underlying stream used for communication
373 * Read-only after initable_init(), so it may be read if you either
374 * hold @init_lock or check for initialization first.
378 /* The object used for authentication (if any).
379 * Read-only after initable_init(), so it may be read if you either
380 * hold @init_lock or check for initialization first.
384 /* Last serial used. Protected by @lock. */
387 /* The object used to send/receive messages.
388 * Read-only after initable_init(), so it may be read if you either
389 * hold @init_lock or check for initialization first.
393 /* If connected to a message bus, this contains the unique name assigned to
394 * us by the bus (e.g. ":1.42").
395 * Read-only after initable_init(), so it may be read if you either
396 * hold @init_lock or check for initialization first.
398 gchar *bus_unique_name;
400 /* The GUID returned by the other side if we authenticed as a client or
401 * the GUID to use if authenticating as a server.
402 * Read-only after initable_init(), so it may be read if you either
403 * hold @init_lock or check for initialization first.
407 /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
408 * Inspect @initialization_error to see whether it succeeded or failed.
410 * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
412 * FLAG_CLOSED is the closed property. It may be read at any time, but
413 * may only be written while holding @lock.
415 volatile gint atomic_flags;
417 /* If the connection could not be established during initable_init(),
418 * this GError will be set.
419 * Read-only after initable_init(), so it may be read if you either
420 * hold @init_lock or check for initialization first.
422 GError *initialization_error;
424 /* The result of g_main_context_ref_thread_default() when the object
425 * was created (the GObject _init() function) - this is used for delivery
426 * of the :closed GObject signal.
428 * Only set in the GObject init function, so no locks are needed.
430 GMainContext *main_context_at_construction;
432 /* Read-only construct properties, no locks needed */
434 GDBusConnectionFlags flags;
436 /* Map used for managing method replies, protected by @lock */
437 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
439 /* Maps used for managing signal subscription, protected by @lock */
440 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
441 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
442 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
444 /* Maps used for managing exported objects and subtrees,
447 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
448 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
449 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
450 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
452 /* Map used for storing last used serials for each thread, protected by @lock */
453 GHashTable *map_thread_to_last_serial;
455 /* Structure used for message filters, protected by @lock */
458 /* Capabilities negotiated during authentication
459 * Read-only after initable_init(), so it may be read without holding a
460 * lock, if you check for initialization first.
462 GDBusCapabilityFlags capabilities;
464 /* Protected by @init_lock */
465 GDBusAuthObserver *authentication_observer;
467 /* Read-only after initable_init(), so it may be read if you either
468 * hold @init_lock or check for initialization first.
470 GCredentials *credentials;
472 /* set to TRUE when finalizing */
476 typedef struct ExportedObject ExportedObject;
477 static void exported_object_free (ExportedObject *eo);
479 typedef struct ExportedSubtree ExportedSubtree;
480 static void exported_subtree_free (ExportedSubtree *es);
498 PROP_CAPABILITY_FLAGS,
499 PROP_AUTHENTICATION_OBSERVER,
502 static void distribute_signals (GDBusConnection *connection,
503 GDBusMessage *message);
505 static void distribute_method_call (GDBusConnection *connection,
506 GDBusMessage *message);
508 static gboolean handle_generic_unlocked (GDBusConnection *connection,
509 GDBusMessage *message);
512 static void purge_all_signal_subscriptions (GDBusConnection *connection);
513 static void purge_all_filters (GDBusConnection *connection);
515 static void schedule_method_call (GDBusConnection *connection,
516 GDBusMessage *message,
517 guint registration_id,
518 guint subtree_registration_id,
519 const GDBusInterfaceInfo *interface_info,
520 const GDBusMethodInfo *method_info,
521 const GDBusPropertyInfo *property_info,
522 GVariant *parameters,
523 const GDBusInterfaceVTable *vtable,
524 GMainContext *main_context,
527 #define _G_ENSURE_LOCK(name) do { \
528 if (G_UNLIKELY (G_TRYLOCK(name))) \
530 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
531 "_G_ENSURE_LOCK: Lock '" #name "' is not locked"); \
535 static guint signals[LAST_SIGNAL] = { 0 };
537 static void initable_iface_init (GInitableIface *initable_iface);
538 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
540 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
541 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
542 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
546 * Check that all members of @connection that can only be accessed after
547 * the connection is initialized can safely be accessed. If not,
548 * log a critical warning. This function is a memory barrier.
550 * Returns: %TRUE if initialized
553 check_initialized (GDBusConnection *connection)
555 /* The access to @atomic_flags isn't conditional, so that this function
556 * provides a memory barrier for thread-safety even if checks are disabled.
557 * (If you don't want this stricter guarantee, you can call
558 * g_return_if_fail (check_initialized (c)).)
560 * This isn't strictly necessary now that we've decided use of an
561 * uninitialized GDBusConnection is undefined behaviour, but it seems
562 * better to be as deterministic as is feasible.
564 * (Anything that could suffer a crash from seeing undefined values
565 * must have a race condition - thread A initializes the connection while
566 * thread B calls a method without initialization, hoping that thread A will
567 * win the race - so its behaviour is undefined anyway.)
569 gint flags = g_atomic_int_get (&connection->atomic_flags);
571 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
573 /* We can safely access this, due to the memory barrier above */
574 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
580 MAY_BE_UNINITIALIZED = (1<<1)
581 } CheckUnclosedFlags;
584 * Check the same thing as check_initialized(), and also that the
585 * connection is not closed. If the connection is uninitialized,
586 * raise a critical warning (it's programmer error); if it's closed,
587 * raise a recoverable GError (it's a runtime error).
589 * This function is a memory barrier.
591 * Returns: %TRUE if initialized and not closed
594 check_unclosed (GDBusConnection *connection,
595 CheckUnclosedFlags check,
598 /* check_initialized() is effectively inlined, so we don't waste time
599 * doing two memory barriers
601 gint flags = g_atomic_int_get (&connection->atomic_flags);
603 if (!(check & MAY_BE_UNINITIALIZED))
605 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
606 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
609 if (flags & FLAG_CLOSED)
611 g_set_error_literal (error,
614 _("The connection is closed"));
621 static GHashTable *alive_connections = NULL;
624 g_dbus_connection_dispose (GObject *object)
626 GDBusConnection *connection = G_DBUS_CONNECTION (object);
628 G_LOCK (message_bus_lock);
629 CONNECTION_LOCK (connection);
630 if (connection->worker != NULL)
632 _g_dbus_worker_stop (connection->worker);
633 connection->worker = NULL;
634 if (alive_connections != NULL)
635 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
639 if (alive_connections != NULL)
640 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
642 CONNECTION_UNLOCK (connection);
643 G_UNLOCK (message_bus_lock);
645 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
646 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
650 g_dbus_connection_finalize (GObject *object)
652 GDBusConnection *connection = G_DBUS_CONNECTION (object);
654 connection->finalizing = TRUE;
656 purge_all_signal_subscriptions (connection);
658 purge_all_filters (connection);
659 g_ptr_array_unref (connection->filters);
661 if (connection->authentication_observer != NULL)
662 g_object_unref (connection->authentication_observer);
664 if (connection->auth != NULL)
665 g_object_unref (connection->auth);
667 if (connection->credentials)
668 g_object_unref (connection->credentials);
670 if (connection->stream != NULL)
672 g_object_unref (connection->stream);
673 connection->stream = NULL;
676 g_free (connection->address);
678 g_free (connection->guid);
679 g_free (connection->bus_unique_name);
681 if (connection->initialization_error != NULL)
682 g_error_free (connection->initialization_error);
684 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
686 g_hash_table_unref (connection->map_rule_to_signal_data);
687 g_hash_table_unref (connection->map_id_to_signal_data);
688 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
690 g_hash_table_unref (connection->map_id_to_ei);
691 g_hash_table_unref (connection->map_object_path_to_eo);
692 g_hash_table_unref (connection->map_id_to_es);
693 g_hash_table_unref (connection->map_object_path_to_es);
695 g_hash_table_unref (connection->map_thread_to_last_serial);
697 g_main_context_unref (connection->main_context_at_construction);
699 g_free (connection->machine_id);
701 g_mutex_clear (&connection->init_lock);
702 g_mutex_clear (&connection->lock);
704 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
707 /* called in any user thread, with the connection's lock not held */
709 g_dbus_connection_get_property (GObject *object,
714 GDBusConnection *connection = G_DBUS_CONNECTION (object);
719 g_value_set_object (value, g_dbus_connection_get_stream (connection));
723 g_value_set_string (value, g_dbus_connection_get_guid (connection));
726 case PROP_UNIQUE_NAME:
727 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
731 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
734 case PROP_EXIT_ON_CLOSE:
735 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
738 case PROP_CAPABILITY_FLAGS:
739 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
743 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
748 /* called in any user thread, with the connection's lock not held */
750 g_dbus_connection_set_property (GObject *object,
755 GDBusConnection *connection = G_DBUS_CONNECTION (object);
760 connection->stream = g_value_dup_object (value);
764 connection->guid = g_value_dup_string (value);
768 connection->address = g_value_dup_string (value);
772 connection->flags = g_value_get_flags (value);
775 case PROP_EXIT_ON_CLOSE:
776 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
779 case PROP_AUTHENTICATION_OBSERVER:
780 connection->authentication_observer = g_value_dup_object (value);
784 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
789 /* Base-class implementation of GDBusConnection::closed.
791 * Called in a user thread, by the main context that was thread-default when
792 * the object was constructed.
795 g_dbus_connection_real_closed (GDBusConnection *connection,
796 gboolean remote_peer_vanished,
799 gint flags = g_atomic_int_get (&connection->atomic_flags);
801 /* Because atomic int access is a memory barrier, we can safely read
802 * initialization_error without a lock, as long as we do it afterwards.
804 if (remote_peer_vanished &&
805 (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
806 (flags & FLAG_INITIALIZED) != 0 &&
807 connection->initialization_error == NULL)
811 g_printerr ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
814 g_quark_to_string (error->domain), error->code);
818 g_printerr ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
825 g_dbus_connection_class_init (GDBusConnectionClass *klass)
827 GObjectClass *gobject_class;
829 gobject_class = G_OBJECT_CLASS (klass);
831 gobject_class->finalize = g_dbus_connection_finalize;
832 gobject_class->dispose = g_dbus_connection_dispose;
833 gobject_class->set_property = g_dbus_connection_set_property;
834 gobject_class->get_property = g_dbus_connection_get_property;
836 klass->closed = g_dbus_connection_real_closed;
839 * GDBusConnection:stream:
841 * The underlying #GIOStream used for I/O.
843 * If this is passed on construction and is a #GSocketConnection,
844 * then the corresponding #GSocket will be put into non-blocking mode.
846 * While the #GDBusConnection is active, it will interact with this
847 * stream from a worker thread, so it is not safe to interact with
848 * the stream directly.
852 g_object_class_install_property (gobject_class,
854 g_param_spec_object ("stream",
856 P_("The underlying streams used for I/O"),
860 G_PARAM_CONSTRUCT_ONLY |
861 G_PARAM_STATIC_NAME |
862 G_PARAM_STATIC_BLURB |
863 G_PARAM_STATIC_NICK));
866 * GDBusConnection:address:
868 * A D-Bus address specifying potential endpoints that can be used
869 * when establishing the connection.
873 g_object_class_install_property (gobject_class,
875 g_param_spec_string ("address",
877 P_("D-Bus address specifying potential socket endpoints"),
880 G_PARAM_CONSTRUCT_ONLY |
881 G_PARAM_STATIC_NAME |
882 G_PARAM_STATIC_BLURB |
883 G_PARAM_STATIC_NICK));
886 * GDBusConnection:flags:
888 * Flags from the #GDBusConnectionFlags enumeration.
892 g_object_class_install_property (gobject_class,
894 g_param_spec_flags ("flags",
897 G_TYPE_DBUS_CONNECTION_FLAGS,
898 G_DBUS_CONNECTION_FLAGS_NONE,
900 G_PARAM_CONSTRUCT_ONLY |
901 G_PARAM_STATIC_NAME |
902 G_PARAM_STATIC_BLURB |
903 G_PARAM_STATIC_NICK));
906 * GDBusConnection:guid:
908 * The GUID of the peer performing the role of server when
911 * If you are constructing a #GDBusConnection and pass
912 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
913 * #GDBusConnection:flags property then you MUST also set this
914 * property to a valid guid.
916 * If you are constructing a #GDBusConnection and pass
917 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
918 * #GDBusConnection:flags property you will be able to read the GUID
919 * of the other peer here after the connection has been successfully
924 g_object_class_install_property (gobject_class,
926 g_param_spec_string ("guid",
928 P_("GUID of the server peer"),
932 G_PARAM_CONSTRUCT_ONLY |
933 G_PARAM_STATIC_NAME |
934 G_PARAM_STATIC_BLURB |
935 G_PARAM_STATIC_NICK));
938 * GDBusConnection:unique-name:
940 * The unique name as assigned by the message bus or %NULL if the
941 * connection is not open or not a message bus connection.
945 g_object_class_install_property (gobject_class,
947 g_param_spec_string ("unique-name",
949 P_("Unique name of bus connection"),
952 G_PARAM_STATIC_NAME |
953 G_PARAM_STATIC_BLURB |
954 G_PARAM_STATIC_NICK));
957 * GDBusConnection:closed:
959 * A boolean specifying whether the connection has been closed.
963 g_object_class_install_property (gobject_class,
965 g_param_spec_boolean ("closed",
967 P_("Whether the connection is closed"),
970 G_PARAM_STATIC_NAME |
971 G_PARAM_STATIC_BLURB |
972 G_PARAM_STATIC_NICK));
975 * GDBusConnection:exit-on-close:
977 * A boolean specifying whether the process will be terminated (by
978 * calling `raise(SIGTERM)`) if the connection is closed by the
981 * Note that #GDBusConnection objects returned by g_bus_get_finish()
982 * and g_bus_get_sync() will (usually) have this property set to %TRUE.
986 g_object_class_install_property (gobject_class,
988 g_param_spec_boolean ("exit-on-close",
990 P_("Whether the process is terminated when the connection is closed"),
994 G_PARAM_STATIC_NAME |
995 G_PARAM_STATIC_BLURB |
996 G_PARAM_STATIC_NICK));
999 * GDBusConnection:capabilities:
1001 * Flags from the #GDBusCapabilityFlags enumeration
1002 * representing connection features negotiated with the other peer.
1006 g_object_class_install_property (gobject_class,
1007 PROP_CAPABILITY_FLAGS,
1008 g_param_spec_flags ("capabilities",
1011 G_TYPE_DBUS_CAPABILITY_FLAGS,
1012 G_DBUS_CAPABILITY_FLAGS_NONE,
1014 G_PARAM_STATIC_NAME |
1015 G_PARAM_STATIC_BLURB |
1016 G_PARAM_STATIC_NICK));
1019 * GDBusConnection:authentication-observer:
1021 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
1025 g_object_class_install_property (gobject_class,
1026 PROP_AUTHENTICATION_OBSERVER,
1027 g_param_spec_object ("authentication-observer",
1028 P_("Authentication Observer"),
1029 P_("Object used to assist in the authentication process"),
1030 G_TYPE_DBUS_AUTH_OBSERVER,
1032 G_PARAM_CONSTRUCT_ONLY |
1033 G_PARAM_STATIC_NAME |
1034 G_PARAM_STATIC_BLURB |
1035 G_PARAM_STATIC_NICK));
1038 * GDBusConnection::closed:
1039 * @connection: the #GDBusConnection emitting the signal
1040 * @remote_peer_vanished: %TRUE if @connection is closed because the
1041 * remote peer closed its end of the connection
1042 * @error: (allow-none): a #GError with more details about the event or %NULL
1044 * Emitted when the connection is closed.
1046 * The cause of this event can be
1048 * - If g_dbus_connection_close() is called. In this case
1049 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
1051 * - If the remote peer closes the connection. In this case
1052 * @remote_peer_vanished is set to %TRUE and @error is set.
1054 * - If the remote peer sends invalid or malformed data. In this
1055 * case @remote_peer_vanished is set to %FALSE and @error is set.
1057 * Upon receiving this signal, you should give up your reference to
1058 * @connection. You are guaranteed that this signal is emitted only
1063 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
1064 G_TYPE_DBUS_CONNECTION,
1066 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1077 g_dbus_connection_init (GDBusConnection *connection)
1079 g_mutex_init (&connection->lock);
1080 g_mutex_init (&connection->init_lock);
1082 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
1084 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1086 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1088 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1091 (GDestroyNotify) g_ptr_array_unref);
1093 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1096 (GDestroyNotify) exported_object_free);
1098 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1101 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1104 (GDestroyNotify) exported_subtree_free);
1106 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1109 connection->map_thread_to_last_serial = g_hash_table_new (g_direct_hash,
1112 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1114 connection->filters = g_ptr_array_new ();
1118 * g_dbus_connection_get_stream:
1119 * @connection: a #GDBusConnection
1121 * Gets the underlying stream used for IO.
1123 * While the #GDBusConnection is active, it will interact with this
1124 * stream from a worker thread, so it is not safe to interact with
1125 * the stream directly.
1127 * Returns: (transfer none): the stream used for IO
1132 g_dbus_connection_get_stream (GDBusConnection *connection)
1134 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1136 /* do not use g_return_val_if_fail(), we want the memory barrier */
1137 if (!check_initialized (connection))
1140 return connection->stream;
1144 * g_dbus_connection_start_message_processing:
1145 * @connection: a #GDBusConnection
1147 * If @connection was created with
1148 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1149 * starts processing messages. Does nothing on if @connection wasn't
1150 * created with this flag or if the method has already been called.
1155 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1157 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1159 /* do not use g_return_val_if_fail(), we want the memory barrier */
1160 if (!check_initialized (connection))
1163 g_assert (connection->worker != NULL);
1164 _g_dbus_worker_unfreeze (connection->worker);
1168 * g_dbus_connection_is_closed:
1169 * @connection: a #GDBusConnection
1171 * Gets whether @connection is closed.
1173 * Returns: %TRUE if the connection is closed, %FALSE otherwise
1178 g_dbus_connection_is_closed (GDBusConnection *connection)
1182 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1184 flags = g_atomic_int_get (&connection->atomic_flags);
1186 return (flags & FLAG_CLOSED) ? TRUE : FALSE;
1190 * g_dbus_connection_get_capabilities:
1191 * @connection: a #GDBusConnection
1193 * Gets the capabilities negotiated with the remote peer
1195 * Returns: zero or more flags from the #GDBusCapabilityFlags enumeration
1199 GDBusCapabilityFlags
1200 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1202 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1204 /* do not use g_return_val_if_fail(), we want the memory barrier */
1205 if (!check_initialized (connection))
1206 return G_DBUS_CAPABILITY_FLAGS_NONE;
1208 return connection->capabilities;
1211 /* ---------------------------------------------------------------------------------------------------- */
1213 /* Called in a temporary thread without holding locks. */
1215 flush_in_thread_func (GSimpleAsyncResult *res,
1217 GCancellable *cancellable)
1222 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1225 g_simple_async_result_take_error (res, error);
1229 * g_dbus_connection_flush:
1230 * @connection: a #GDBusConnection
1231 * @cancellable: (allow-none): a #GCancellable or %NULL
1232 * @callback: (allow-none): a #GAsyncReadyCallback to call when the
1233 * request is satisfied or %NULL if you don't care about the result
1234 * @user_data: The data to pass to @callback
1236 * Asynchronously flushes @connection, that is, writes all queued
1237 * outgoing message to the transport and then flushes the transport
1238 * (using g_output_stream_flush_async()). This is useful in programs
1239 * that wants to emit a D-Bus signal and then exit immediately. Without
1240 * flushing the connection, there is no guaranteed that the message has
1241 * been sent to the networking buffers in the OS kernel.
1243 * This is an asynchronous method. When the operation is finished,
1244 * @callback will be invoked in the
1245 * [thread-default main context][g-main-context-push-thread-default]
1246 * of the thread you are calling this method from. You can
1247 * then call g_dbus_connection_flush_finish() to get the result of the
1248 * operation. See g_dbus_connection_flush_sync() for the synchronous
1254 g_dbus_connection_flush (GDBusConnection *connection,
1255 GCancellable *cancellable,
1256 GAsyncReadyCallback callback,
1259 GSimpleAsyncResult *simple;
1261 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1263 simple = g_simple_async_result_new (G_OBJECT (connection),
1266 g_dbus_connection_flush);
1267 g_simple_async_result_set_check_cancellable (simple, cancellable);
1268 g_simple_async_result_run_in_thread (simple,
1269 flush_in_thread_func,
1272 g_object_unref (simple);
1276 * g_dbus_connection_flush_finish:
1277 * @connection: a #GDBusConnection
1278 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1279 * to g_dbus_connection_flush()
1280 * @error: return location for error or %NULL
1282 * Finishes an operation started with g_dbus_connection_flush().
1284 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1289 g_dbus_connection_flush_finish (GDBusConnection *connection,
1293 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1298 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1299 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1300 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1302 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1304 if (g_simple_async_result_propagate_error (simple, error))
1314 * g_dbus_connection_flush_sync:
1315 * @connection: a #GDBusConnection
1316 * @cancellable: (allow-none): a #GCancellable or %NULL
1317 * @error: return location for error or %NULL
1319 * Synchronously flushes @connection. The calling thread is blocked
1320 * until this is done. See g_dbus_connection_flush() for the
1321 * asynchronous version of this method and more details about what it
1324 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1329 g_dbus_connection_flush_sync (GDBusConnection *connection,
1330 GCancellable *cancellable,
1335 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1336 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1340 /* This is only a best-effort attempt to see whether the connection is
1341 * closed, so it doesn't need the lock. If the connection closes just
1342 * after this check, but before scheduling the flush operation, the
1343 * result will be more or less the same as if the connection closed while
1344 * the flush operation was pending - it'll fail with either CLOSED or
1347 if (!check_unclosed (connection, 0, error))
1350 g_assert (connection->worker != NULL);
1352 ret = _g_dbus_worker_flush_sync (connection->worker,
1360 /* ---------------------------------------------------------------------------------------------------- */
1364 GDBusConnection *connection;
1366 gboolean remote_peer_vanished;
1370 emit_closed_data_free (EmitClosedData *data)
1372 g_object_unref (data->connection);
1373 if (data->error != NULL)
1374 g_error_free (data->error);
1378 /* Called in a user thread that has acquired the main context that was
1379 * thread-default when the object was constructed
1382 emit_closed_in_idle (gpointer user_data)
1384 EmitClosedData *data = user_data;
1387 g_object_notify (G_OBJECT (data->connection), "closed");
1388 g_signal_emit (data->connection,
1389 signals[CLOSED_SIGNAL],
1391 data->remote_peer_vanished,
1397 /* Can be called from any thread, must hold lock.
1398 * FLAG_CLOSED must already have been set.
1401 schedule_closed_unlocked (GDBusConnection *connection,
1402 gboolean remote_peer_vanished,
1405 GSource *idle_source;
1406 EmitClosedData *data;
1408 CONNECTION_ENSURE_LOCK (connection);
1410 data = g_new0 (EmitClosedData, 1);
1411 data->connection = g_object_ref (connection);
1412 data->remote_peer_vanished = remote_peer_vanished;
1413 data->error = error != NULL ? g_error_copy (error) : NULL;
1415 idle_source = g_idle_source_new ();
1416 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1417 g_source_set_callback (idle_source,
1418 emit_closed_in_idle,
1420 (GDestroyNotify) emit_closed_data_free);
1421 g_source_set_name (idle_source, "[gio] emit_closed_in_idle");
1422 g_source_attach (idle_source, connection->main_context_at_construction);
1423 g_source_unref (idle_source);
1426 /* ---------------------------------------------------------------------------------------------------- */
1429 * g_dbus_connection_close:
1430 * @connection: a #GDBusConnection
1431 * @cancellable: (allow-none): a #GCancellable or %NULL
1432 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request is
1433 * satisfied or %NULL if you don't care about the result
1434 * @user_data: The data to pass to @callback
1436 * Closes @connection. Note that this never causes the process to
1437 * exit (this might only happen if the other end of a shared message
1438 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1440 * Once the connection is closed, operations such as sending a message
1441 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1442 * will not automatically flush the connection so queued messages may
1443 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1445 * If @connection is already closed, this method fails with
1446 * %G_IO_ERROR_CLOSED.
1448 * When @connection has been closed, the #GDBusConnection::closed
1449 * signal is emitted in the
1450 * [thread-default main context][g-main-context-push-thread-default]
1451 * of the thread that @connection was constructed in.
1453 * This is an asynchronous method. When the operation is finished,
1454 * @callback will be invoked in the
1455 * [thread-default main context][g-main-context-push-thread-default]
1456 * of the thread you are calling this method from. You can
1457 * then call g_dbus_connection_close_finish() to get the result of the
1458 * operation. See g_dbus_connection_close_sync() for the synchronous
1464 g_dbus_connection_close (GDBusConnection *connection,
1465 GCancellable *cancellable,
1466 GAsyncReadyCallback callback,
1469 GSimpleAsyncResult *simple;
1471 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1473 /* do not use g_return_val_if_fail(), we want the memory barrier */
1474 if (!check_initialized (connection))
1477 g_assert (connection->worker != NULL);
1479 simple = g_simple_async_result_new (G_OBJECT (connection),
1482 g_dbus_connection_close);
1483 g_simple_async_result_set_check_cancellable (simple, cancellable);
1484 _g_dbus_worker_close (connection->worker, cancellable, simple);
1485 g_object_unref (simple);
1489 * g_dbus_connection_close_finish:
1490 * @connection: a #GDBusConnection
1491 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1492 * to g_dbus_connection_close()
1493 * @error: return location for error or %NULL
1495 * Finishes an operation started with g_dbus_connection_close().
1497 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1502 g_dbus_connection_close_finish (GDBusConnection *connection,
1506 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1511 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1512 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1513 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1515 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1517 if (g_simple_async_result_propagate_error (simple, error))
1528 GAsyncResult *result;
1531 /* Can be called by any thread, without the connection lock */
1533 sync_close_cb (GObject *source_object,
1537 SyncCloseData *data = user_data;
1539 data->result = g_object_ref (res);
1540 g_main_loop_quit (data->loop);
1544 * g_dbus_connection_close_sync:
1545 * @connection: a #GDBusConnection
1546 * @cancellable: (allow-none): a #GCancellable or %NULL
1547 * @error: return location for error or %NULL
1549 * Synchronously closees @connection. The calling thread is blocked
1550 * until this is done. See g_dbus_connection_close() for the
1551 * asynchronous version of this method and more details about what it
1554 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1559 g_dbus_connection_close_sync (GDBusConnection *connection,
1560 GCancellable *cancellable,
1565 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1566 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1570 if (check_unclosed (connection, 0, error))
1572 GMainContext *context;
1575 context = g_main_context_new ();
1576 g_main_context_push_thread_default (context);
1577 data.loop = g_main_loop_new (context, TRUE);
1580 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1581 g_main_loop_run (data.loop);
1582 ret = g_dbus_connection_close_finish (connection, data.result, error);
1584 g_object_unref (data.result);
1585 g_main_loop_unref (data.loop);
1586 g_main_context_pop_thread_default (context);
1587 g_main_context_unref (context);
1593 /* ---------------------------------------------------------------------------------------------------- */
1596 * g_dbus_get_bus_id:
1597 * @connection: a #GDBusConnection
1598 * @timeout_msec: the timeout in milliseconds, -1 to use the default timeout
1599 * @error: return location for error or %NULL
1601 * Synchronously returns the unique ID of the bus.
1603 * If @connection is closed then the operation will fail with
1604 * %G_IO_ERROR_CLOSED.
1606 * The calling thread is blocked until a reply is received.
1608 * Returns: the unique ID of the bus or %NULL if @error is set.
1609 * Free with g_free().
1614 g_dbus_get_bus_id (GDBusConnection *connection,
1621 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1622 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1623 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1628 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1629 "org.freedesktop.DBus", "GetId",
1630 NULL, G_VARIANT_TYPE ("(s)"),
1631 G_DBUS_CALL_FLAGS_NONE, timeout_msec, NULL, error);
1634 g_variant_get (result, "(s)", &bus_id);
1635 g_variant_unref (result);
1644 LIST_ACTIVATABLE_NAMES,
1646 } GDBusListNameType;
1649 _g_dbus_get_list_internal (GDBusConnection *connection,
1651 GDBusListNameType list_name_type,
1664 if (list_name_type == LIST_QUEUED_OWNERS)
1666 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1667 "org.freedesktop.DBus", "ListQueuedOwners",
1668 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(as)"),
1669 G_DBUS_CALL_FLAGS_NONE, timeout_msec, NULL, error);
1675 if (list_name_type == LIST_NAMES)
1676 method_name = "ListNames";
1678 method_name = "ListActivatableNames";
1680 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1681 "org.freedesktop.DBus", method_name,
1682 NULL, G_VARIANT_TYPE ("(as)"),
1683 G_DBUS_CALL_FLAGS_NONE, timeout_msec, NULL, error);
1688 g_variant_get (result, "(as)", &iter);
1689 n = g_variant_iter_n_children (iter);
1690 strv = g_new (gchar *, n + 1);
1693 while (g_variant_iter_loop (iter, "s", &str))
1695 strv[i] = g_strdup (str);
1700 g_variant_iter_free (iter);
1701 g_variant_unref (result);
1708 * g_dbus_get_list_names:
1709 * @connection: a #GDBusConnection
1710 * @timeout_msec: the timeout in milliseconds, -1 to use the default timeout
1711 * @error: return location for error or %NULL
1713 * Synchronously returns a list of all currently-owned names on the bus.
1715 * If @connection is closed then the operation will fail with
1716 * %G_IO_ERROR_CLOSED.
1718 * The calling thread is blocked until a reply is received.
1720 * Returns: a list of all currently-owned names on the bus.
1721 * Free with g_strfreev().
1726 g_dbus_get_list_names (GDBusConnection *connection,
1732 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1733 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1734 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1736 strv = _g_dbus_get_list_internal (connection, NULL, LIST_NAMES, timeout_msec, error);
1742 * g_dbus_get_list_activatable_names:
1743 * @connection: a #GDBusConnection
1744 * @timeout_msec: the timeout in milliseconds, -1 to use the default timeout
1745 * @error: return location for error or %NULL
1747 * Synchronously returns a list of all names that can be activated on the bus.
1749 * If @connection is closed then the operation will fail with
1750 * %G_IO_ERROR_CLOSED.
1752 * The calling thread is blocked until a reply is received.
1754 * Returns: a list of all names that can be activated on the bus.
1755 * Free with g_strfreev().
1760 g_dbus_get_list_activatable_names (GDBusConnection *connection,
1766 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1767 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1768 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1770 strv = _g_dbus_get_list_internal (connection, NULL, LIST_ACTIVATABLE_NAMES, timeout_msec, error);
1776 * g_dbus_get_list_queued_names:
1777 * @connection: a #GDBusConnection
1778 * @name: a unique or well-known bus name
1779 * @timeout_msec: the timeout in milliseconds, -1 to use the default timeout
1780 * @error: return location for error or %NULL
1782 * Synchronously returns the unique bus names of connections currently queued
1785 * If @connection is closed then the operation will fail with
1786 * %G_IO_ERROR_CLOSED. If @name contains a value not compatible with
1787 * the D-Bus syntax and naming conventions for bus names, the operation
1790 * The calling thread is blocked until a reply is received.
1792 * Returns: the unique bus names of connections currently queued for the @name
1793 * or %NULL if @error is set. Free with g_strfreev().
1798 g_dbus_get_list_queued_owners (GDBusConnection *connection,
1805 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1806 g_return_val_if_fail (name == NULL || g_dbus_is_name (name), NULL);
1807 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1808 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1810 strv = _g_dbus_get_list_internal (connection, name, LIST_QUEUED_OWNERS, timeout_msec, error);
1816 * g_dbus_get_name_owner:
1817 * @connection: a #GDBusConnection
1818 * @name: well-known bus name to get the owner of
1819 * @timeout_msec: the timeout in milliseconds, -1 to use the default timeout
1820 * @error: return location for error or %NULL
1822 * Synchronously returns the unique connection name of the primary owner of
1823 * the name given. If the requested name doesn't have an owner, an @error is
1826 * If @connection is closed then the operation will fail with
1827 * %G_IO_ERROR_CLOSED. If @name contains a value not compatible with
1828 * the D-Bus syntax and naming conventions for bus names, the operation
1831 * The calling thread is blocked until a reply is received.
1833 * Returns: the unique connection name of the primary owner of the
1834 * name given. If the requested name doesn't have an owner, function
1835 * returns %NULL and @error is set. Free with g_free().
1840 g_dbus_get_name_owner (GDBusConnection *connection,
1848 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1849 g_return_val_if_fail (name == NULL || g_dbus_is_name (name), NULL);
1850 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1851 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1856 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1857 "org.freedesktop.DBus", "GetNameOwner",
1858 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(s)"),
1859 G_DBUS_CALL_FLAGS_NONE, timeout_msec, NULL, error);
1862 g_variant_get (result, "(s)", &name_owner);
1863 g_variant_unref (result);
1872 * g_dbus_name_has_owner:
1873 * @connection: a #GDBusConnection
1874 * @name: a unique or well-known bus name
1875 * @timeout_msec: the timeout in milliseconds, -1 to use the default timeout
1876 * @error: return location for error or %NULL
1878 * Synchronously checks if the specified name exists (currently has an owner).
1880 * If @connection is closed then the operation will fail with
1881 * %G_IO_ERROR_CLOSED. If @name contains a value not compatible with
1882 * the D-Bus syntax and naming conventions for bus names, the operation
1885 * The calling thread is blocked until a reply is received.
1887 * Returns: %TRUE if specified name exists (currently has an owner)
1888 * If the requested name doesn't have an owner or @error is set,
1889 * function returns %FALSE.
1894 g_dbus_name_has_owner (GDBusConnection *connection,
1902 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1903 g_return_val_if_fail (name == NULL || g_dbus_is_name (name), NULL);
1904 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1905 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1909 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1910 "org.freedesktop.DBus", "NameHasOwner",
1911 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(b)"),
1912 G_DBUS_CALL_FLAGS_NONE, timeout_msec, NULL, error);
1915 g_variant_get (result, "(b)", &ret);
1916 g_variant_unref (result);
1925 * g_dbus_get_connection_pid:
1926 * @connection: a #GDBusConnection
1927 * @name: a unique or well-known bus name of the connection to query
1928 * @timeout_msec: the timeout in milliseconds, -1 to use the default timeout
1929 * @error: return location for error or %NULL
1931 * Synchronously returns the Unix process ID of the process connected to the
1932 * bus. If unable to determine it, an @error is returned.
1934 * If @connection is closed then the operation will fail with
1935 * %G_IO_ERROR_CLOSED. If @name contains a value not compatible with
1936 * the D-Bus syntax and naming conventions for bus names, the operation
1937 * returns (guint32) -1.
1939 * The calling thread is blocked until a reply is received.
1941 * Returns: the Unix process ID of the process connected to the bus or
1942 * (guint32) -1 if @error is set.
1947 g_dbus_get_connection_pid (GDBusConnection *connection,
1955 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), -1);
1956 g_return_val_if_fail (name == NULL || g_dbus_is_name (name), -1);
1957 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, -1);
1958 g_return_val_if_fail (error == NULL || *error == NULL, -1);
1963 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1964 "org.freedesktop.DBus", "GetConnectionUnixProcessID",
1965 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(u)"),
1966 G_DBUS_CALL_FLAGS_NONE, timeout_msec, NULL, error);
1969 g_variant_get (result, "(u)", &pid);
1970 g_variant_unref (result);
1977 * g_dbus_get_connection_uid:
1978 * @connection: a #GDBusConnection
1979 * @name: a unique or well-known bus name of the connection to query
1980 * @timeout_msec: the timeout in milliseconds, -1 to use the default timeout
1981 * @error: return location for error or %NULL
1983 * Synchronously returns the Unix user ID of the process connected to the
1984 * bus. If unable to determine it, an @error is returned.
1986 * If @connection is closed then the operation will fail with
1987 * %G_IO_ERROR_CLOSED. If @name contains a value not compatible with
1988 * the D-Bus syntax and naming conventions for bus names, the operation
1989 * returns (guint32) -1.
1991 * The calling thread is blocked until a reply is received.
1993 * Returns: the Unix user ID of the process connected to the bus or
1994 * (guint32) -1 if @error is set.
1999 g_dbus_get_connection_uid (GDBusConnection *connection,
2007 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), -1);
2008 g_return_val_if_fail (name == NULL || g_dbus_is_name (name), -1);
2009 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, -1);
2010 g_return_val_if_fail (error == NULL || *error == NULL, -1);
2015 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
2016 "org.freedesktop.DBus", "GetConnectionUnixUser",
2017 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(u)"),
2018 G_DBUS_CALL_FLAGS_NONE, timeout_msec, NULL, error);
2021 g_variant_get (result, "(u)", &uid);
2022 g_variant_unref (result);
2028 /* ---------------------------------------------------------------------------------------------------- */
2031 * g_dbus_connection_get_last_serial:
2032 * @connection: a #GDBusConnection
2034 * Retrieves the last serial number assigned to a #GDBusMessage on
2035 * the current thread. This includes messages sent via both low-level
2036 * API such as g_dbus_connection_send_message() as well as
2037 * high-level API such as g_dbus_connection_emit_signal(),
2038 * g_dbus_connection_call() or g_dbus_proxy_call().
2040 * Returns: the last used serial or zero when no message has been sent
2041 * within the current thread
2046 g_dbus_connection_get_last_serial (GDBusConnection *connection)
2050 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2052 CONNECTION_LOCK (connection);
2053 ret = GPOINTER_TO_UINT (g_hash_table_lookup (connection->map_thread_to_last_serial,
2055 CONNECTION_UNLOCK (connection);
2060 /* ---------------------------------------------------------------------------------------------------- */
2062 /* Can be called by any thread, with the connection lock held */
2064 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
2065 GDBusMessage *message,
2066 GDBusSendMessageFlags flags,
2067 volatile guint32 *out_serial,
2072 guint32 serial_to_use;
2075 CONNECTION_ENSURE_LOCK (connection);
2077 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2078 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
2080 /* TODO: check all necessary headers are present */
2085 if (out_serial != NULL)
2088 /* If we're in initable_init(), don't check for being initialized, to avoid
2089 * chicken-and-egg problems. initable_init() is responsible for setting up
2090 * our prerequisites (mainly connection->worker), and only calling us
2091 * from its own thread (so no memory barrier is needed).
2093 if (!check_unclosed (connection,
2094 (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
2098 blob = g_dbus_message_to_blob (message,
2100 connection->capabilities,
2105 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
2106 serial_to_use = g_dbus_message_get_serial (message);
2108 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
2113 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
2116 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
2119 g_assert_not_reached ();
2124 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
2125 blob_size, serial_to_use, connection);
2126 g_printerr ("----\n");
2127 hexdump (blob, blob_size);
2128 g_printerr ("----\n");
2131 /* TODO: use connection->auth to encode the blob */
2133 if (out_serial != NULL)
2134 *out_serial = serial_to_use;
2136 /* store used serial for the current thread */
2137 /* TODO: watch the thread disposal and remove associated record
2139 * - see https://bugzilla.gnome.org/show_bug.cgi?id=676825#c7
2141 g_hash_table_replace (connection->map_thread_to_last_serial,
2143 GUINT_TO_POINTER (serial_to_use));
2145 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
2146 g_dbus_message_set_serial (message, serial_to_use);
2148 g_dbus_message_lock (message);
2149 _g_dbus_worker_send_message (connection->worker,
2153 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
2164 * g_dbus_connection_send_message:
2165 * @connection: a #GDBusConnection
2166 * @message: a #GDBusMessage
2167 * @flags: flags affecting how the message is sent
2168 * @out_serial: (out) (allow-none): return location for serial number assigned
2169 * to @message when sending it or %NULL
2170 * @error: Return location for error or %NULL
2172 * Asynchronously sends @message to the peer represented by @connection.
2174 * Unless @flags contain the
2175 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2176 * will be assigned by @connection and set on @message via
2177 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2178 * serial number used will be written to this location prior to
2179 * submitting the message to the underlying transport.
2181 * If @connection is closed then the operation will fail with
2182 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
2183 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2185 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2186 * for an example of how to use this low-level API to send and receive
2187 * UNIX file descriptors.
2189 * Note that @message must be unlocked, unless @flags contain the
2190 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2192 * Returns: %TRUE if the message was well-formed and queued for
2193 * transmission, %FALSE if @error is set
2198 g_dbus_connection_send_message (GDBusConnection *connection,
2199 GDBusMessage *message,
2200 GDBusSendMessageFlags flags,
2201 volatile guint32 *out_serial,
2206 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2207 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
2208 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
2209 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2211 CONNECTION_LOCK (connection);
2212 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
2213 CONNECTION_UNLOCK (connection);
2217 /* ---------------------------------------------------------------------------------------------------- */
2221 volatile gint ref_count;
2222 GDBusConnection *connection;
2224 GSimpleAsyncResult *simple;
2226 GMainContext *main_context;
2228 GCancellable *cancellable;
2230 gulong cancellable_handler_id;
2232 GSource *timeout_source;
2237 /* Can be called from any thread with or without lock held */
2238 static SendMessageData *
2239 send_message_data_ref (SendMessageData *data)
2241 g_atomic_int_inc (&data->ref_count);
2245 /* Can be called from any thread with or without lock held */
2247 send_message_data_unref (SendMessageData *data)
2249 if (g_atomic_int_dec_and_test (&data->ref_count))
2251 g_assert (data->timeout_source == NULL);
2252 g_assert (data->simple == NULL);
2253 g_assert (data->cancellable_handler_id == 0);
2254 g_object_unref (data->connection);
2255 if (data->cancellable != NULL)
2256 g_object_unref (data->cancellable);
2257 g_main_context_unref (data->main_context);
2262 /* ---------------------------------------------------------------------------------------------------- */
2264 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
2266 send_message_with_reply_deliver (SendMessageData *data, gboolean remove)
2268 CONNECTION_ENSURE_LOCK (data->connection);
2270 g_assert (!data->delivered);
2272 data->delivered = TRUE;
2274 g_simple_async_result_complete_in_idle (data->simple);
2275 g_object_unref (data->simple);
2276 data->simple = NULL;
2278 if (data->timeout_source != NULL)
2280 g_source_destroy (data->timeout_source);
2281 data->timeout_source = NULL;
2283 if (data->cancellable_handler_id > 0)
2285 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
2286 data->cancellable_handler_id = 0;
2291 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
2292 GUINT_TO_POINTER (data->serial)));
2295 send_message_data_unref (data);
2298 /* ---------------------------------------------------------------------------------------------------- */
2300 /* Can be called from any thread with lock held */
2302 send_message_data_deliver_reply_unlocked (SendMessageData *data,
2303 GDBusMessage *reply)
2305 if (data->delivered)
2308 g_simple_async_result_set_op_res_gpointer (data->simple,
2309 g_object_ref (reply),
2312 send_message_with_reply_deliver (data, TRUE);
2318 /* ---------------------------------------------------------------------------------------------------- */
2320 /* Called from a user thread, lock is not held */
2322 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
2324 SendMessageData *data = user_data;
2326 CONNECTION_LOCK (data->connection);
2327 if (data->delivered)
2330 g_simple_async_result_set_error (data->simple,
2332 G_IO_ERROR_CANCELLED,
2333 _("Operation was cancelled"));
2335 send_message_with_reply_deliver (data, TRUE);
2338 CONNECTION_UNLOCK (data->connection);
2342 /* Can be called from any thread with or without lock held */
2344 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
2347 SendMessageData *data = user_data;
2348 GSource *idle_source;
2350 /* postpone cancellation to idle handler since we may be called directly
2351 * via g_cancellable_connect() (e.g. holding lock)
2353 idle_source = g_idle_source_new ();
2354 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
2355 g_source_set_callback (idle_source,
2356 send_message_with_reply_cancelled_idle_cb,
2357 send_message_data_ref (data),
2358 (GDestroyNotify) send_message_data_unref);
2359 g_source_set_name (idle_source, "[gio] send_message_with_reply_cancelled_idle_cb");
2360 g_source_attach (idle_source, data->main_context);
2361 g_source_unref (idle_source);
2364 /* ---------------------------------------------------------------------------------------------------- */
2366 /* Called from a user thread, lock is not held */
2368 send_message_with_reply_timeout_cb (gpointer user_data)
2370 SendMessageData *data = user_data;
2372 CONNECTION_LOCK (data->connection);
2373 if (data->delivered)
2376 g_simple_async_result_set_error (data->simple,
2378 G_IO_ERROR_TIMED_OUT,
2379 _("Timeout was reached"));
2381 send_message_with_reply_deliver (data, TRUE);
2384 CONNECTION_UNLOCK (data->connection);
2389 /* ---------------------------------------------------------------------------------------------------- */
2391 /* Called from a user thread, connection's lock is held */
2393 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
2394 GDBusMessage *message,
2395 GDBusSendMessageFlags flags,
2397 volatile guint32 *out_serial,
2398 GCancellable *cancellable,
2399 GAsyncReadyCallback callback,
2402 GSimpleAsyncResult *simple;
2403 SendMessageData *data;
2405 volatile guint32 serial;
2409 if (out_serial == NULL)
2410 out_serial = &serial;
2412 if (timeout_msec == -1)
2413 timeout_msec = 25 * 1000;
2415 simple = g_simple_async_result_new (G_OBJECT (connection),
2418 g_dbus_connection_send_message_with_reply);
2419 g_simple_async_result_set_check_cancellable (simple, cancellable);
2421 if (g_cancellable_is_cancelled (cancellable))
2423 g_simple_async_result_set_error (simple,
2425 G_IO_ERROR_CANCELLED,
2426 _("Operation was cancelled"));
2427 g_simple_async_result_complete_in_idle (simple);
2428 g_object_unref (simple);
2433 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
2435 g_simple_async_result_take_error (simple, error);
2436 g_simple_async_result_complete_in_idle (simple);
2437 g_object_unref (simple);
2441 data = g_new0 (SendMessageData, 1);
2442 data->ref_count = 1;
2443 data->connection = g_object_ref (connection);
2444 data->simple = simple;
2445 data->serial = *out_serial;
2446 data->main_context = g_main_context_ref_thread_default ();
2448 if (cancellable != NULL)
2450 data->cancellable = g_object_ref (cancellable);
2451 data->cancellable_handler_id = g_cancellable_connect (cancellable,
2452 G_CALLBACK (send_message_with_reply_cancelled_cb),
2453 send_message_data_ref (data),
2454 (GDestroyNotify) send_message_data_unref);
2457 if (timeout_msec != G_MAXINT)
2459 data->timeout_source = g_timeout_source_new (timeout_msec);
2460 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
2461 g_source_set_callback (data->timeout_source,
2462 send_message_with_reply_timeout_cb,
2463 send_message_data_ref (data),
2464 (GDestroyNotify) send_message_data_unref);
2465 g_source_attach (data->timeout_source, data->main_context);
2466 g_source_unref (data->timeout_source);
2469 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
2470 GUINT_TO_POINTER (*out_serial),
2478 * g_dbus_connection_send_message_with_reply:
2479 * @connection: a #GDBusConnection
2480 * @message: a #GDBusMessage
2481 * @flags: flags affecting how the message is sent
2482 * @timeout_msec: the timeout in milliseconds, -1 to use the default
2483 * timeout or %G_MAXINT for no timeout
2484 * @out_serial: (out) (allow-none): return location for serial number assigned
2485 * to @message when sending it or %NULL
2486 * @cancellable: (allow-none): a #GCancellable or %NULL
2487 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request
2488 * is satisfied or %NULL if you don't care about the result
2489 * @user_data: The data to pass to @callback
2491 * Asynchronously sends @message to the peer represented by @connection.
2493 * Unless @flags contain the
2494 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2495 * will be assigned by @connection and set on @message via
2496 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2497 * serial number used will be written to this location prior to
2498 * submitting the message to the underlying transport.
2500 * If @connection is closed then the operation will fail with
2501 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2502 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2503 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2505 * This is an asynchronous method. When the operation is finished, @callback
2506 * will be invoked in the
2507 * [thread-default main context][g-main-context-push-thread-default]
2508 * of the thread you are calling this method from. You can then call
2509 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
2510 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
2512 * Note that @message must be unlocked, unless @flags contain the
2513 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2515 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2516 * for an example of how to use this low-level API to send and receive
2517 * UNIX file descriptors.
2522 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
2523 GDBusMessage *message,
2524 GDBusSendMessageFlags flags,
2526 volatile guint32 *out_serial,
2527 GCancellable *cancellable,
2528 GAsyncReadyCallback callback,
2531 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2532 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2533 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2534 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2536 CONNECTION_LOCK (connection);
2537 g_dbus_connection_send_message_with_reply_unlocked (connection,
2545 CONNECTION_UNLOCK (connection);
2549 * g_dbus_connection_send_message_with_reply_finish:
2550 * @connection: a #GDBusConnection
2551 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
2552 * g_dbus_connection_send_message_with_reply()
2553 * @error: teturn location for error or %NULL
2555 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2557 * Note that @error is only set if a local in-process error
2558 * occurred. That is to say that the returned #GDBusMessage object may
2559 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2560 * g_dbus_message_to_gerror() to transcode this to a #GError.
2562 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2563 * for an example of how to use this low-level API to send and receive
2564 * UNIX file descriptors.
2566 * Returns: (transfer full): a locked #GDBusMessage or %NULL if @error is set
2571 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2575 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2576 GDBusMessage *reply;
2578 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2579 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2583 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
2585 if (g_simple_async_result_propagate_error (simple, error))
2588 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
2594 /* ---------------------------------------------------------------------------------------------------- */
2599 GMainContext *context;
2601 } SendMessageSyncData;
2603 /* Called from a user thread, lock is not held */
2605 send_message_with_reply_sync_cb (GDBusConnection *connection,
2609 SendMessageSyncData *data = user_data;
2610 data->res = g_object_ref (res);
2611 g_main_loop_quit (data->loop);
2615 * g_dbus_connection_send_message_with_reply_sync:
2616 * @connection: a #GDBusConnection
2617 * @message: a #GDBusMessage
2618 * @flags: flags affecting how the message is sent.
2619 * @timeout_msec: the timeout in milliseconds, -1 to use the default
2620 * timeout or %G_MAXINT for no timeout
2621 * @out_serial: (out) (allow-none): return location for serial number
2622 * assigned to @message when sending it or %NULL
2623 * @cancellable: (allow-none): a #GCancellable or %NULL
2624 * @error: return location for error or %NULL
2626 * Synchronously sends @message to the peer represented by @connection
2627 * and blocks the calling thread until a reply is received or the
2628 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2629 * for the asynchronous version of this method.
2631 * Unless @flags contain the
2632 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2633 * will be assigned by @connection and set on @message via
2634 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2635 * serial number used will be written to this location prior to
2636 * submitting the message to the underlying transport.
2638 * If @connection is closed then the operation will fail with
2639 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2640 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2641 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2643 * Note that @error is only set if a local in-process error
2644 * occurred. That is to say that the returned #GDBusMessage object may
2645 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2646 * g_dbus_message_to_gerror() to transcode this to a #GError.
2648 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2649 * for an example of how to use this low-level API to send and receive
2650 * UNIX file descriptors.
2652 * Note that @message must be unlocked, unless @flags contain the
2653 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2655 * Returns: (transfer full): a locked #GDBusMessage that is the reply
2656 * to @message or %NULL if @error is set
2661 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2662 GDBusMessage *message,
2663 GDBusSendMessageFlags flags,
2665 volatile guint32 *out_serial,
2666 GCancellable *cancellable,
2669 SendMessageSyncData *data;
2670 GDBusMessage *reply;
2672 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2673 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2674 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2675 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2676 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2678 data = g_new0 (SendMessageSyncData, 1);
2679 data->context = g_main_context_new ();
2680 data->loop = g_main_loop_new (data->context, FALSE);
2682 g_main_context_push_thread_default (data->context);
2684 g_dbus_connection_send_message_with_reply (connection,
2690 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2692 g_main_loop_run (data->loop);
2693 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2697 g_main_context_pop_thread_default (data->context);
2699 g_main_context_unref (data->context);
2700 g_main_loop_unref (data->loop);
2701 g_object_unref (data->res);
2707 /* ---------------------------------------------------------------------------------------------------- */
2711 GDBusMessageFilterFunction func;
2718 GDBusMessageFilterFunction filter_function;
2720 GDestroyNotify user_data_free_func;
2723 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2725 on_worker_message_received (GDBusWorker *worker,
2726 GDBusMessage *message,
2729 GDBusConnection *connection;
2730 FilterCallback *filters;
2735 G_LOCK (message_bus_lock);
2736 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2739 G_UNLOCK (message_bus_lock);
2742 connection = G_DBUS_CONNECTION (user_data);
2743 g_object_ref (connection);
2744 G_UNLOCK (message_bus_lock);
2746 //g_debug ("in on_worker_message_received");
2748 g_object_ref (message);
2749 g_dbus_message_lock (message);
2751 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2753 /* First collect the set of callback functions */
2754 CONNECTION_LOCK (connection);
2755 num_filters = connection->filters->len;
2756 filters = g_new0 (FilterCallback, num_filters);
2757 for (n = 0; n < num_filters; n++)
2759 FilterData *data = connection->filters->pdata[n];
2760 filters[n].func = data->filter_function;
2761 filters[n].user_data = data->user_data;
2763 CONNECTION_UNLOCK (connection);
2765 /* then call the filters in order (without holding the lock) */
2766 for (n = 0; n < num_filters; n++)
2768 message = filters[n].func (connection,
2771 filters[n].user_data);
2772 if (message == NULL)
2774 g_dbus_message_lock (message);
2777 /* Standard dispatch unless the filter ate the message - no need to
2778 * do anything if the message was altered
2780 if (message != NULL)
2782 GDBusMessageType message_type;
2784 message_type = g_dbus_message_get_message_type (message);
2785 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2787 guint32 reply_serial;
2788 SendMessageData *send_message_data;
2790 reply_serial = g_dbus_message_get_reply_serial (message);
2791 CONNECTION_LOCK (connection);
2792 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2793 GUINT_TO_POINTER (reply_serial));
2794 if (send_message_data != NULL)
2796 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2797 send_message_data_deliver_reply_unlocked (send_message_data, message);
2801 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2803 CONNECTION_UNLOCK (connection);
2805 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2807 CONNECTION_LOCK (connection);
2808 distribute_signals (connection, message);
2809 CONNECTION_UNLOCK (connection);
2811 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2813 CONNECTION_LOCK (connection);
2814 distribute_method_call (connection, message);
2815 CONNECTION_UNLOCK (connection);
2819 if (message != NULL)
2820 g_object_unref (message);
2821 g_object_unref (connection);
2825 /* Called in GDBusWorker's thread, lock is not held */
2826 static GDBusMessage *
2827 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2828 GDBusMessage *message,
2831 GDBusConnection *connection;
2832 FilterCallback *filters;
2837 G_LOCK (message_bus_lock);
2838 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2841 G_UNLOCK (message_bus_lock);
2844 connection = G_DBUS_CONNECTION (user_data);
2845 g_object_ref (connection);
2846 G_UNLOCK (message_bus_lock);
2848 //g_debug ("in on_worker_message_about_to_be_sent");
2850 /* First collect the set of callback functions */
2851 CONNECTION_LOCK (connection);
2852 num_filters = connection->filters->len;
2853 filters = g_new0 (FilterCallback, num_filters);
2854 for (n = 0; n < num_filters; n++)
2856 FilterData *data = connection->filters->pdata[n];
2857 filters[n].func = data->filter_function;
2858 filters[n].user_data = data->user_data;
2860 CONNECTION_UNLOCK (connection);
2862 /* then call the filters in order (without holding the lock) */
2863 for (n = 0; n < num_filters; n++)
2865 g_dbus_message_lock (message);
2866 message = filters[n].func (connection,
2869 filters[n].user_data);
2870 if (message == NULL)
2874 g_object_unref (connection);
2880 /* called with connection lock held, in GDBusWorker thread */
2882 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2884 SendMessageData *data = value;
2886 if (data->delivered)
2889 g_simple_async_result_set_error (data->simple,
2892 _("The connection is closed"));
2894 /* Ask send_message_with_reply_deliver not to remove the element from the
2895 * hash table - we're in the middle of a foreach; that would be unsafe.
2896 * Instead, return TRUE from this function so that it gets removed safely.
2898 send_message_with_reply_deliver (data, FALSE);
2902 /* Called in GDBusWorker's thread - we must not block - without lock held */
2904 on_worker_closed (GDBusWorker *worker,
2905 gboolean remote_peer_vanished,
2909 GDBusConnection *connection;
2911 guint old_atomic_flags;
2913 G_LOCK (message_bus_lock);
2914 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2917 G_UNLOCK (message_bus_lock);
2920 connection = G_DBUS_CONNECTION (user_data);
2921 g_object_ref (connection);
2922 G_UNLOCK (message_bus_lock);
2924 //g_debug ("in on_worker_closed: %s", error->message);
2926 CONNECTION_LOCK (connection);
2927 /* Even though this is atomic, we do it inside the lock to avoid breaking
2928 * assumptions in remove_match_rule(). We'd need the lock in a moment
2929 * anyway, so, no loss.
2931 old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
2933 if (!(old_atomic_flags & FLAG_CLOSED))
2935 g_hash_table_foreach_remove (connection->map_method_serial_to_send_message_data, cancel_method_on_close, NULL);
2936 schedule_closed_unlocked (connection, remote_peer_vanished, error);
2938 CONNECTION_UNLOCK (connection);
2940 g_object_unref (connection);
2943 /* ---------------------------------------------------------------------------------------------------- */
2945 /* Determines the biggest set of capabilities we can support on this
2948 * Called with the init_lock held.
2950 static GDBusCapabilityFlags
2951 get_offered_capabilities_max (GDBusConnection *connection)
2953 GDBusCapabilityFlags ret;
2954 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2956 if (G_IS_UNIX_CONNECTION (connection->stream))
2957 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2962 /* Called in a user thread, lock is not held */
2964 initable_init (GInitable *initable,
2965 GCancellable *cancellable,
2968 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2971 /* This method needs to be idempotent to work with the singleton
2972 * pattern. See the docs for g_initable_init(). We implement this by
2975 * Unfortunately we can't use the main lock since the on_worker_*()
2976 * callbacks above needs the lock during initialization (for message
2977 * bus connections we do a synchronous Hello() call on the bus).
2979 g_mutex_lock (&connection->init_lock);
2983 /* Make this a no-op if we're already initialized (successfully or
2986 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
2988 ret = (connection->initialization_error == NULL);
2992 /* Because of init_lock, we can't get here twice in different threads */
2993 g_assert (connection->initialization_error == NULL);
2995 /* The user can pass multiple (but mutally exclusive) construct
2998 * - stream (of type GIOStream)
2999 * - address (of type gchar*)
3001 * At the end of the day we end up with a non-NULL GIOStream
3002 * object in connection->stream.
3004 if (connection->address != NULL)
3006 g_assert (connection->stream == NULL);
3008 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
3009 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
3011 g_set_error_literal (&connection->initialization_error,
3013 G_IO_ERROR_INVALID_ARGUMENT,
3014 _("Unsupported flags encountered when constructing a client-side connection"));
3018 connection->stream = g_dbus_address_get_stream_sync (connection->address,
3019 NULL, /* TODO: out_guid */
3021 &connection->initialization_error);
3022 if (connection->stream == NULL)
3025 else if (connection->stream != NULL)
3031 g_assert_not_reached ();
3034 /* Authenticate the connection */
3035 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
3037 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
3038 g_assert (connection->guid != NULL);
3039 connection->auth = _g_dbus_auth_new (connection->stream);
3040 if (!_g_dbus_auth_run_server (connection->auth,
3041 connection->authentication_observer,
3043 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
3044 get_offered_capabilities_max (connection),
3045 &connection->capabilities,
3046 &connection->credentials,
3048 &connection->initialization_error))
3051 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
3053 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
3054 g_assert (connection->guid == NULL);
3055 connection->auth = _g_dbus_auth_new (connection->stream);
3056 connection->guid = _g_dbus_auth_run_client (connection->auth,
3057 connection->authentication_observer,
3058 get_offered_capabilities_max (connection),
3059 &connection->capabilities,
3061 &connection->initialization_error);
3062 if (connection->guid == NULL)
3066 if (connection->authentication_observer != NULL)
3068 g_object_unref (connection->authentication_observer);
3069 connection->authentication_observer = NULL;
3072 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
3074 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
3077 /* We want all IO operations to be non-blocking since they happen in
3078 * the worker thread which is shared by _all_ connections.
3080 if (G_IS_SOCKET_CONNECTION (connection->stream))
3082 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
3086 G_LOCK (message_bus_lock);
3087 if (alive_connections == NULL)
3088 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
3089 g_hash_table_insert (alive_connections, connection, connection);
3090 G_UNLOCK (message_bus_lock);
3092 connection->worker = _g_dbus_worker_new (connection->stream,
3093 connection->capabilities,
3094 ((connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) != 0),
3095 on_worker_message_received,
3096 on_worker_message_about_to_be_sent,
3100 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
3101 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3103 GVariant *hello_result;
3105 /* we could lift this restriction by adding code in gdbusprivate.c */
3106 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
3108 g_set_error_literal (&connection->initialization_error,
3111 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
3115 hello_result = g_dbus_connection_call_sync (connection,
3116 "org.freedesktop.DBus", /* name */
3117 "/org/freedesktop/DBus", /* path */
3118 "org.freedesktop.DBus", /* interface */
3120 NULL, /* parameters */
3121 G_VARIANT_TYPE ("(s)"),
3122 CALL_FLAGS_INITIALIZING,
3124 NULL, /* TODO: cancellable */
3125 &connection->initialization_error);
3126 if (hello_result == NULL)
3129 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
3130 g_variant_unref (hello_result);
3131 //g_debug ("unique name is '%s'", connection->bus_unique_name);
3138 g_assert (connection->initialization_error != NULL);
3139 g_propagate_error (error, g_error_copy (connection->initialization_error));
3142 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
3143 g_mutex_unlock (&connection->init_lock);
3149 initable_iface_init (GInitableIface *initable_iface)
3151 initable_iface->init = initable_init;
3154 /* ---------------------------------------------------------------------------------------------------- */
3157 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
3162 /* ---------------------------------------------------------------------------------------------------- */
3165 * g_dbus_connection_new:
3166 * @stream: a #GIOStream
3167 * @guid: (allow-none): the GUID to use if a authenticating as a server or %NULL
3168 * @flags: flags describing how to make the connection
3169 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3170 * @cancellable: (allow-none): a #GCancellable or %NULL
3171 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
3172 * @user_data: the data to pass to @callback
3174 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
3175 * with the end represented by @stream.
3177 * If @stream is a #GSocketConnection, then the corresponding #GSocket
3178 * will be put into non-blocking mode.
3180 * The D-Bus connection will interact with @stream from a worker thread.
3181 * As a result, the caller should not interact with @stream after this
3182 * method has been called, except by calling g_object_unref() on it.
3184 * If @observer is not %NULL it may be used to control the
3185 * authentication process.
3187 * When the operation is finished, @callback will be invoked. You can
3188 * then call g_dbus_connection_new_finish() to get the result of the
3191 * This is a asynchronous failable constructor. See
3192 * g_dbus_connection_new_sync() for the synchronous
3198 g_dbus_connection_new (GIOStream *stream,
3200 GDBusConnectionFlags flags,
3201 GDBusAuthObserver *observer,
3202 GCancellable *cancellable,
3203 GAsyncReadyCallback callback,
3206 g_return_if_fail (G_IS_IO_STREAM (stream));
3207 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
3215 "authentication-observer", observer,
3220 * g_dbus_connection_new_finish:
3221 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback
3222 * passed to g_dbus_connection_new().
3223 * @error: return location for error or %NULL
3225 * Finishes an operation started with g_dbus_connection_new().
3227 * Returns: a #GDBusConnection or %NULL if @error is set. Free
3228 * with g_object_unref().
3233 g_dbus_connection_new_finish (GAsyncResult *res,
3237 GObject *source_object;
3239 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
3240 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3242 source_object = g_async_result_get_source_object (res);
3243 g_assert (source_object != NULL);
3244 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
3247 g_object_unref (source_object);
3249 return G_DBUS_CONNECTION (object);
3255 * g_dbus_connection_new_sync:
3256 * @stream: a #GIOStream
3257 * @guid: (allow-none): the GUID to use if a authenticating as a server or %NULL
3258 * @flags: flags describing how to make the connection
3259 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3260 * @cancellable: (allow-none): a #GCancellable or %NULL
3261 * @error: return location for error or %NULL
3263 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
3264 * with the end represented by @stream.
3266 * If @stream is a #GSocketConnection, then the corresponding #GSocket
3267 * will be put into non-blocking mode.
3269 * The D-Bus connection will interact with @stream from a worker thread.
3270 * As a result, the caller should not interact with @stream after this
3271 * method has been called, except by calling g_object_unref() on it.
3273 * If @observer is not %NULL it may be used to control the
3274 * authentication process.
3276 * This is a synchronous failable constructor. See
3277 * g_dbus_connection_new() for the asynchronous version.
3279 * Returns: a #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
3284 g_dbus_connection_new_sync (GIOStream *stream,
3286 GDBusConnectionFlags flags,
3287 GDBusAuthObserver *observer,
3288 GCancellable *cancellable,
3291 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
3292 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3293 return g_initable_new (G_TYPE_DBUS_CONNECTION,
3299 "authentication-observer", observer,
3303 /* ---------------------------------------------------------------------------------------------------- */
3306 * g_dbus_connection_new_for_address:
3307 * @address: a D-Bus address
3308 * @flags: flags describing how to make the connection
3309 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3310 * @cancellable: (allow-none): a #GCancellable or %NULL
3311 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
3312 * @user_data: the data to pass to @callback
3314 * Asynchronously connects and sets up a D-Bus client connection for
3315 * exchanging D-Bus messages with an endpoint specified by @address
3316 * which must be in the D-Bus address format.
3318 * This constructor can only be used to initiate client-side
3319 * connections - use g_dbus_connection_new() if you need to act as the
3320 * server. In particular, @flags cannot contain the
3321 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
3322 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
3324 * When the operation is finished, @callback will be invoked. You can
3325 * then call g_dbus_connection_new_finish() to get the result of the
3328 * If @observer is not %NULL it may be used to control the
3329 * authentication process.
3331 * This is a asynchronous failable constructor. See
3332 * g_dbus_connection_new_for_address_sync() for the synchronous
3338 g_dbus_connection_new_for_address (const gchar *address,
3339 GDBusConnectionFlags flags,
3340 GDBusAuthObserver *observer,
3341 GCancellable *cancellable,
3342 GAsyncReadyCallback callback,
3345 g_return_if_fail (address != NULL);
3346 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
3353 "authentication-observer", observer,
3358 * g_dbus_connection_new_for_address_finish:
3359 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
3360 * to g_dbus_connection_new()
3361 * @error: return location for error or %NULL
3363 * Finishes an operation started with g_dbus_connection_new_for_address().
3365 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
3371 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
3375 GObject *source_object;
3377 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
3378 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3380 source_object = g_async_result_get_source_object (res);
3381 g_assert (source_object != NULL);
3382 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
3385 g_object_unref (source_object);
3387 return G_DBUS_CONNECTION (object);
3393 * g_dbus_connection_new_for_address_sync:
3394 * @address: a D-Bus address
3395 * @flags: flags describing how to make the connection
3396 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3397 * @cancellable: (allow-none): a #GCancellable or %NULL
3398 * @error: return location for error or %NULL
3400 * Synchronously connects and sets up a D-Bus client connection for
3401 * exchanging D-Bus messages with an endpoint specified by @address
3402 * which must be in the D-Bus address format.
3404 * This constructor can only be used to initiate client-side
3405 * connections - use g_dbus_connection_new_sync() if you need to act
3406 * as the server. In particular, @flags cannot contain the
3407 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
3408 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
3410 * This is a synchronous failable constructor. See
3411 * g_dbus_connection_new_for_address() for the asynchronous version.
3413 * If @observer is not %NULL it may be used to control the
3414 * authentication process.
3416 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
3422 g_dbus_connection_new_for_address_sync (const gchar *address,
3423 GDBusConnectionFlags flags,
3424 GDBusAuthObserver *observer,
3425 GCancellable *cancellable,
3428 g_return_val_if_fail (address != NULL, NULL);
3429 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3430 return g_initable_new (G_TYPE_DBUS_CONNECTION,
3435 "authentication-observer", observer,
3439 /* ---------------------------------------------------------------------------------------------------- */
3442 * g_dbus_connection_set_exit_on_close:
3443 * @connection: a #GDBusConnection
3444 * @exit_on_close: whether the process should be terminated
3445 * when @connection is closed by the remote peer
3447 * Sets whether the process should be terminated when @connection is
3448 * closed by the remote peer. See #GDBusConnection:exit-on-close for
3451 * Note that this function should be used with care. Most modern UNIX
3452 * desktops tie the notion of a user session the session bus, and expect
3453 * all of a users applications to quit when their bus connection goes away.
3454 * If you are setting @exit_on_close to %FALSE for the shared session
3455 * bus connection, you should make sure that your application exits
3456 * when the user session ends.
3461 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
3462 gboolean exit_on_close)
3464 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3467 g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
3469 g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
3474 * g_dbus_connection_get_exit_on_close:
3475 * @connection: a #GDBusConnection
3477 * Gets whether the process is terminated when @connection is
3478 * closed by the remote peer. See
3479 * #GDBusConnection:exit-on-close for more details.
3481 * Returns: whether the process is terminated when @connection is
3482 * closed by the remote peer
3487 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
3489 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3491 if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
3498 * g_dbus_connection_get_guid:
3499 * @connection: a #GDBusConnection
3501 * The GUID of the peer performing the role of server when
3502 * authenticating. See #GDBusConnection:guid for more details.
3504 * Returns: The GUID. Do not free this string, it is owned by
3510 g_dbus_connection_get_guid (GDBusConnection *connection)
3512 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3513 return connection->guid;
3517 * g_dbus_connection_get_unique_name:
3518 * @connection: a #GDBusConnection
3520 * Gets the unique name of @connection as assigned by the message
3521 * bus. This can also be used to figure out if @connection is a
3522 * message bus connection.
3524 * Returns: the unique name or %NULL if @connection is not a message
3525 * bus connection. Do not free this string, it is owned by
3531 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3533 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3535 /* do not use g_return_val_if_fail(), we want the memory barrier */
3536 if (!check_initialized (connection))
3539 return connection->bus_unique_name;
3543 * g_dbus_connection_get_peer_credentials:
3544 * @connection: a #GDBusConnection
3546 * Gets the credentials of the authenticated peer. This will always
3547 * return %NULL unless @connection acted as a server
3548 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3549 * when set up and the client passed credentials as part of the
3550 * authentication process.
3552 * In a message bus setup, the message bus is always the server and
3553 * each application is a client. So this method will always return
3554 * %NULL for message bus clients.
3556 * Returns: (transfer none): a #GCredentials or %NULL if not available.
3557 * Do not free this object, it is owned by @connection.
3562 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3564 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3566 /* do not use g_return_val_if_fail(), we want the memory barrier */
3567 if (!check_initialized (connection))
3570 return connection->credentials;
3573 /* ---------------------------------------------------------------------------------------------------- */
3575 static guint _global_filter_id = 1;
3578 * g_dbus_connection_add_filter:
3579 * @connection: a #GDBusConnection
3580 * @filter_function: a filter function
3581 * @user_data: user data to pass to @filter_function
3582 * @user_data_free_func: function to free @user_data with when filter
3583 * is removed or %NULL
3585 * Adds a message filter. Filters are handlers that are run on all
3586 * incoming and outgoing messages, prior to standard dispatch. Filters
3587 * are run in the order that they were added. The same handler can be
3588 * added as a filter more than once, in which case it will be run more
3589 * than once. Filters added during a filter callback won't be run on
3590 * the message being processed. Filter functions are allowed to modify
3591 * and even drop messages.
3593 * Note that filters are run in a dedicated message handling thread so
3594 * they can't block and, generally, can't do anything but signal a
3595 * worker thread. Also note that filters are rarely needed - use API
3596 * such as g_dbus_connection_send_message_with_reply(),
3597 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3599 * If a filter consumes an incoming message the message is not
3600 * dispatched anywhere else - not even the standard dispatch machinery
3601 * (that API such as g_dbus_connection_signal_subscribe() and
3602 * g_dbus_connection_send_message_with_reply() relies on) will see the
3603 * message. Similary, if a filter consumes an outgoing message, the
3604 * message will not be sent to the other peer.
3606 * Returns: a filter identifier that can be used with
3607 * g_dbus_connection_remove_filter()
3612 g_dbus_connection_add_filter (GDBusConnection *connection,
3613 GDBusMessageFilterFunction filter_function,
3615 GDestroyNotify user_data_free_func)
3619 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3620 g_return_val_if_fail (filter_function != NULL, 0);
3621 g_return_val_if_fail (check_initialized (connection), 0);
3623 CONNECTION_LOCK (connection);
3624 data = g_new0 (FilterData, 1);
3625 data->id = _global_filter_id++; /* TODO: overflow etc. */
3626 data->filter_function = filter_function;
3627 data->user_data = user_data;
3628 data->user_data_free_func = user_data_free_func;
3629 g_ptr_array_add (connection->filters, data);
3630 CONNECTION_UNLOCK (connection);
3635 /* only called from finalize(), removes all filters */
3637 purge_all_filters (GDBusConnection *connection)
3640 for (n = 0; n < connection->filters->len; n++)
3642 FilterData *data = connection->filters->pdata[n];
3643 if (data->user_data_free_func != NULL)
3644 data->user_data_free_func (data->user_data);
3650 * g_dbus_connection_remove_filter:
3651 * @connection: a #GDBusConnection
3652 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3659 g_dbus_connection_remove_filter (GDBusConnection *connection,
3663 FilterData *to_destroy;
3665 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3666 g_return_if_fail (check_initialized (connection));
3668 CONNECTION_LOCK (connection);
3670 for (n = 0; n < connection->filters->len; n++)
3672 FilterData *data = connection->filters->pdata[n];
3673 if (data->id == filter_id)
3675 g_ptr_array_remove_index (connection->filters, n);
3680 CONNECTION_UNLOCK (connection);
3682 /* do free without holding lock */
3683 if (to_destroy != NULL)
3685 if (to_destroy->user_data_free_func != NULL)
3686 to_destroy->user_data_free_func (to_destroy->user_data);
3687 g_free (to_destroy);
3691 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3695 /* ---------------------------------------------------------------------------------------------------- */
3701 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3702 gchar *interface_name;
3706 GDBusSignalFlags flags;
3707 GArray *subscribers;
3712 GDBusSignalCallback callback;
3714 GDestroyNotify user_data_free_func;
3716 GMainContext *context;
3720 signal_data_free (SignalData *signal_data)
3722 g_free (signal_data->rule);
3723 g_free (signal_data->sender);
3724 g_free (signal_data->sender_unique_name);
3725 g_free (signal_data->interface_name);
3726 g_free (signal_data->member);
3727 g_free (signal_data->object_path);
3728 g_free (signal_data->arg0);
3729 g_array_free (signal_data->subscribers, TRUE);
3730 g_free (signal_data);
3734 args_to_rule (const gchar *sender,
3735 const gchar *interface_name,
3736 const gchar *member,
3737 const gchar *object_path,
3739 GDBusSignalFlags flags)
3743 rule = g_string_new ("type='signal'");
3744 if (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE)
3745 g_string_prepend_c (rule, '-');
3747 g_string_append_printf (rule, ",sender='%s'", sender);
3748 if (interface_name != NULL)
3749 g_string_append_printf (rule, ",interface='%s'", interface_name);
3751 g_string_append_printf (rule, ",member='%s'", member);
3752 if (object_path != NULL)
3753 g_string_append_printf (rule, ",path='%s'", object_path);
3757 if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3758 g_string_append_printf (rule, ",arg0path='%s'", arg0);
3759 else if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3760 g_string_append_printf (rule, ",arg0namespace='%s'", arg0);
3762 g_string_append_printf (rule, ",arg0='%s'", arg0);
3765 return g_string_free (rule, FALSE);
3768 static guint _global_subscriber_id = 1;
3769 static guint _global_registration_id = 1;
3770 static guint _global_subtree_registration_id = 1;
3772 /* ---------------------------------------------------------------------------------------------------- */
3774 /* Called in a user thread, lock is held */
3776 add_match_rule (GDBusConnection *connection,
3777 const gchar *match_rule)
3780 GDBusMessage *message;
3782 if (match_rule[0] == '-')
3785 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3786 "/org/freedesktop/DBus", /* path */
3787 "org.freedesktop.DBus", /* interface */
3789 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3791 if (!g_dbus_connection_send_message_unlocked (connection,
3793 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3797 g_critical ("Error while sending AddMatch() message: %s", error->message);
3798 g_error_free (error);
3800 g_object_unref (message);
3803 /* ---------------------------------------------------------------------------------------------------- */
3805 /* Called in a user thread, lock is held */
3807 remove_match_rule (GDBusConnection *connection,
3808 const gchar *match_rule)
3811 GDBusMessage *message;
3813 if (match_rule[0] == '-')
3816 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3817 "/org/freedesktop/DBus", /* path */
3818 "org.freedesktop.DBus", /* interface */
3820 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3823 if (!g_dbus_connection_send_message_unlocked (connection,
3825 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3829 /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
3830 * critical; but we're holding the lock, and our caller checked whether
3831 * we were already closed, so we can't get that error.
3833 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3834 g_error_free (error);
3836 g_object_unref (message);
3839 /* ---------------------------------------------------------------------------------------------------- */
3842 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3844 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3845 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3846 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3847 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3848 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3851 /* ---------------------------------------------------------------------------------------------------- */
3854 * g_dbus_connection_signal_subscribe:
3855 * @connection: a #GDBusConnection
3856 * @sender: (allow-none): sender name to match on (unique or well-known name)
3857 * or %NULL to listen from all senders
3858 * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3859 * match on all interfaces
3860 * @member: (allow-none): D-Bus signal name to match on or %NULL to match on
3862 * @object_path: (allow-none): object path to match on or %NULL to match on
3864 * @arg0: (allow-none): contents of first string argument to match on or %NULL
3865 * to match on all kinds of arguments
3866 * @flags: flags describing how to subscribe to the signal (currently unused)
3867 * @callback: callback to invoke when there is a signal matching the requested data
3868 * @user_data: user data to pass to @callback
3869 * @user_data_free_func: (allow-none): function to free @user_data with when
3870 * subscription is removed or %NULL
3872 * Subscribes to signals on @connection and invokes @callback with a whenever
3873 * the signal is received. Note that @callback will be invoked in the
3874 * [thread-default main context][g-main-context-push-thread-default]
3875 * of the thread you are calling this method from.
3877 * If @connection is not a message bus connection, @sender must be
3880 * If @sender is a well-known name note that @callback is invoked with
3881 * the unique name for the owner of @sender, not the well-known name
3882 * as one would expect. This is because the message bus rewrites the
3883 * name. As such, to avoid certain race conditions, users should be
3884 * tracking the name owner of the well-known name and use that when
3885 * processing the received signal.
3887 * If one of %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE or
3888 * %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH are given, @arg0 is
3889 * interpreted as part of a namespace or path. The first argument
3890 * of a signal is matched against that part as specified by D-Bus.
3892 * Returns: a subscription identifier that can be used with g_dbus_connection_signal_unsubscribe()
3897 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3898 const gchar *sender,
3899 const gchar *interface_name,
3900 const gchar *member,
3901 const gchar *object_path,
3903 GDBusSignalFlags flags,
3904 GDBusSignalCallback callback,
3906 GDestroyNotify user_data_free_func)
3909 SignalData *signal_data;
3910 SignalSubscriber subscriber;
3911 GPtrArray *signal_data_array;
3912 const gchar *sender_unique_name;
3914 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3915 * an OOM condition. We might want to change that but that would involve making
3916 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3917 * handle that. And there's really no sensible way of handling this short of retrying
3918 * to add the match rule... and then there's the little thing that, hey, maybe there's
3919 * a reason the bus in an OOM condition.
3921 * Doable, but not really sure it's worth it...
3924 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3925 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3926 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3927 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3928 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3929 g_return_val_if_fail (callback != NULL, 0);
3930 g_return_val_if_fail (check_initialized (connection), 0);
3931 g_return_val_if_fail (!((flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH) && (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)), 0);
3932 g_return_val_if_fail (!(arg0 == NULL && (flags & (G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH | G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE))), 0);
3934 CONNECTION_LOCK (connection);
3936 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3937 * with a '-' character to prefix the rule (which will otherwise be
3940 * This allows us to hash the rule and do our lifecycle tracking in
3941 * the usual way, but the '-' prevents the match rule from ever
3942 * actually being send to the bus (either for add or remove).
3944 rule = args_to_rule (sender, interface_name, member, object_path, arg0, flags);
3946 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3947 sender_unique_name = sender;
3949 sender_unique_name = "";
3951 subscriber.callback = callback;
3952 subscriber.user_data = user_data;
3953 subscriber.user_data_free_func = user_data_free_func;
3954 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3955 subscriber.context = g_main_context_ref_thread_default ();
3957 /* see if we've already have this rule */
3958 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3959 if (signal_data != NULL)
3961 g_array_append_val (signal_data->subscribers, subscriber);
3966 signal_data = g_new0 (SignalData, 1);
3967 signal_data->rule = rule;
3968 signal_data->sender = g_strdup (sender);
3969 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3970 signal_data->interface_name = g_strdup (interface_name);
3971 signal_data->member = g_strdup (member);
3972 signal_data->object_path = g_strdup (object_path);
3973 signal_data->arg0 = g_strdup (arg0);
3974 signal_data->flags = flags;
3975 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3976 g_array_append_val (signal_data->subscribers, subscriber);
3978 g_hash_table_insert (connection->map_rule_to_signal_data,
3982 /* Add the match rule to the bus...
3984 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3985 * always send such messages to us.
3987 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3989 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3990 add_match_rule (connection, signal_data->rule);
3993 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3994 signal_data->sender_unique_name);
3995 if (signal_data_array == NULL)
3997 signal_data_array = g_ptr_array_new ();
3998 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3999 g_strdup (signal_data->sender_unique_name),
4002 g_ptr_array_add (signal_data_array, signal_data);
4005 g_hash_table_insert (connection->map_id_to_signal_data,
4006 GUINT_TO_POINTER (subscriber.id),
4009 CONNECTION_UNLOCK (connection);
4011 return subscriber.id;
4014 /* ---------------------------------------------------------------------------------------------------- */
4016 /* called in any thread */
4017 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
4019 unsubscribe_id_internal (GDBusConnection *connection,
4020 guint subscription_id,
4021 GArray *out_removed_subscribers)
4023 SignalData *signal_data;
4024 GPtrArray *signal_data_array;
4027 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
4028 GUINT_TO_POINTER (subscription_id));
4029 if (signal_data == NULL)
4031 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
4035 for (n = 0; n < signal_data->subscribers->len; n++)
4037 SignalSubscriber *subscriber;
4039 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
4040 if (subscriber->id != subscription_id)
4043 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
4044 GUINT_TO_POINTER (subscription_id)));
4045 g_array_append_val (out_removed_subscribers, *subscriber);
4046 g_array_remove_index (signal_data->subscribers, n);
4048 if (signal_data->subscribers->len == 0)
4050 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
4052 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
4053 signal_data->sender_unique_name);
4054 g_warn_if_fail (signal_data_array != NULL);
4055 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
4057 if (signal_data_array->len == 0)
4059 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
4060 signal_data->sender_unique_name));
4063 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
4064 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
4065 !is_signal_data_for_name_lost_or_acquired (signal_data) &&
4066 !g_dbus_connection_is_closed (connection) &&
4067 !connection->finalizing)
4069 /* The check for g_dbus_connection_is_closed() means that
4070 * sending the RemoveMatch message can't fail with
4071 * G_IO_ERROR_CLOSED, because we're holding the lock,
4072 * so on_worker_closed() can't happen between the check we just
4073 * did, and releasing the lock later.
4075 remove_match_rule (connection, signal_data->rule);
4078 signal_data_free (signal_data);
4084 g_assert_not_reached ();
4091 * g_dbus_connection_signal_unsubscribe:
4092 * @connection: a #GDBusConnection
4093 * @subscription_id: a subscription id obtained from
4094 * g_dbus_connection_signal_subscribe()
4096 * Unsubscribes from signals.
4101 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
4102 guint subscription_id)
4104 GArray *subscribers;
4107 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4108 g_return_if_fail (check_initialized (connection));
4110 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
4112 CONNECTION_LOCK (connection);
4113 unsubscribe_id_internal (connection,
4116 CONNECTION_UNLOCK (connection);
4119 g_assert (subscribers->len == 0 || subscribers->len == 1);
4121 /* call GDestroyNotify without lock held */
4122 for (n = 0; n < subscribers->len; n++)
4124 SignalSubscriber *subscriber;
4125 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
4126 call_destroy_notify (subscriber->context,
4127 subscriber->user_data_free_func,
4128 subscriber->user_data);
4129 g_main_context_unref (subscriber->context);
4132 g_array_free (subscribers, TRUE);
4135 /* ---------------------------------------------------------------------------------------------------- */
4139 guint subscription_id;
4140 GDBusSignalCallback callback;
4142 GDBusMessage *message;
4143 GDBusConnection *connection;
4144 const gchar *sender;
4146 const gchar *interface;
4147 const gchar *member;
4150 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
4154 emit_signal_instance_in_idle_cb (gpointer data)
4156 SignalInstance *signal_instance = data;
4157 GVariant *parameters;
4158 gboolean has_subscription;
4160 parameters = g_dbus_message_get_body (signal_instance->message);
4161 if (parameters == NULL)
4163 parameters = g_variant_new ("()");
4164 g_variant_ref_sink (parameters);
4168 g_variant_ref_sink (parameters);
4172 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
4173 signal_instance->subscription_id,
4174 signal_instance->sender,
4175 signal_instance->path,
4176 signal_instance->interface,
4177 signal_instance->member,
4178 g_variant_print (parameters, TRUE));
4181 /* Careful here, don't do the callback if we no longer has the subscription */
4182 CONNECTION_LOCK (signal_instance->connection);
4183 has_subscription = FALSE;
4184 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
4185 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
4186 has_subscription = TRUE;
4187 CONNECTION_UNLOCK (signal_instance->connection);
4189 if (has_subscription)
4190 signal_instance->callback (signal_instance->connection,
4191 signal_instance->sender,
4192 signal_instance->path,
4193 signal_instance->interface,
4194 signal_instance->member,
4196 signal_instance->user_data);
4198 g_variant_unref (parameters);
4204 signal_instance_free (SignalInstance *signal_instance)
4206 g_object_unref (signal_instance->message);
4207 g_object_unref (signal_instance->connection);
4208 g_free (signal_instance);
4212 namespace_rule_matches (const gchar *namespace,
4218 len_namespace = strlen (namespace);
4219 len_name = strlen (name);
4221 if (len_name < len_namespace)
4224 if (memcmp (namespace, name, len_namespace) != 0)
4227 return len_namespace == len_name || name[len_namespace] == '.';
4231 path_rule_matches (const gchar *path_a,
4232 const gchar *path_b)
4236 len_a = strlen (path_a);
4237 len_b = strlen (path_b);
4239 if (len_a < len_b && path_a[len_a - 1] != '/')
4242 if (len_b < len_a && path_b[len_b - 1] != '/')
4245 return memcmp (path_a, path_b, MIN (len_a, len_b)) == 0;
4248 /* called in GDBusWorker thread WITH lock held */
4250 schedule_callbacks (GDBusConnection *connection,
4251 GPtrArray *signal_data_array,
4252 GDBusMessage *message,
4253 const gchar *sender)
4256 const gchar *interface;
4257 const gchar *member;
4266 interface = g_dbus_message_get_interface (message);
4267 member = g_dbus_message_get_member (message);
4268 path = g_dbus_message_get_path (message);
4269 arg0 = g_dbus_message_get_arg0 (message);
4272 g_print ("In schedule_callbacks:\n"
4274 " interface = '%s'\n"
4285 /* TODO: if this is slow, then we can change signal_data_array into
4286 * map_object_path_to_signal_data_array or something.
4288 for (n = 0; n < signal_data_array->len; n++)
4290 SignalData *signal_data = signal_data_array->pdata[n];
4292 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
4295 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
4298 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
4301 if (signal_data->arg0 != NULL)
4306 if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
4308 if (!namespace_rule_matches (signal_data->arg0, arg0))
4311 else if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
4313 if (!path_rule_matches (signal_data->arg0, arg0))
4316 else if (!g_str_equal (signal_data->arg0, arg0))
4320 for (m = 0; m < signal_data->subscribers->len; m++)
4322 SignalSubscriber *subscriber;
4323 GSource *idle_source;
4324 SignalInstance *signal_instance;
4326 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
4328 signal_instance = g_new0 (SignalInstance, 1);
4329 signal_instance->subscription_id = subscriber->id;
4330 signal_instance->callback = subscriber->callback;
4331 signal_instance->user_data = subscriber->user_data;
4332 signal_instance->message = g_object_ref (message);
4333 signal_instance->connection = g_object_ref (connection);
4334 signal_instance->sender = sender;
4335 signal_instance->path = path;
4336 signal_instance->interface = interface;
4337 signal_instance->member = member;
4339 idle_source = g_idle_source_new ();
4340 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4341 g_source_set_callback (idle_source,
4342 emit_signal_instance_in_idle_cb,
4344 (GDestroyNotify) signal_instance_free);
4345 g_source_set_name (idle_source, "[gio] emit_signal_instance_in_idle_cb");
4346 g_source_attach (idle_source, subscriber->context);
4347 g_source_unref (idle_source);
4352 /* called in GDBusWorker thread with lock held */
4354 distribute_signals (GDBusConnection *connection,
4355 GDBusMessage *message)
4357 GPtrArray *signal_data_array;
4358 const gchar *sender;
4360 sender = g_dbus_message_get_sender (message);
4362 if (G_UNLIKELY (_g_dbus_debug_signal ()))
4364 _g_dbus_debug_print_lock ();
4365 g_print ("========================================================================\n"
4366 "GDBus-debug:Signal:\n"
4367 " <<<< RECEIVED SIGNAL %s.%s\n"
4369 " sent by name %s\n",
4370 g_dbus_message_get_interface (message),
4371 g_dbus_message_get_member (message),
4372 g_dbus_message_get_path (message),
4373 sender != NULL ? sender : "(none)");
4374 _g_dbus_debug_print_unlock ();
4377 /* collect subscribers that match on sender */
4380 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
4381 if (signal_data_array != NULL)
4382 schedule_callbacks (connection, signal_data_array, message, sender);
4385 /* collect subscribers not matching on sender */
4386 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
4387 if (signal_data_array != NULL)
4388 schedule_callbacks (connection, signal_data_array, message, sender);
4391 /* ---------------------------------------------------------------------------------------------------- */
4393 /* only called from finalize(), removes all subscriptions */
4395 purge_all_signal_subscriptions (GDBusConnection *connection)
4397 GHashTableIter iter;
4400 GArray *subscribers;
4403 ids = g_array_new (FALSE, FALSE, sizeof (guint));
4404 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
4405 while (g_hash_table_iter_next (&iter, &key, NULL))
4407 guint subscription_id = GPOINTER_TO_UINT (key);
4408 g_array_append_val (ids, subscription_id);
4411 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
4412 for (n = 0; n < ids->len; n++)
4414 guint subscription_id = g_array_index (ids, guint, n);
4415 unsubscribe_id_internal (connection,
4419 g_array_free (ids, TRUE);
4421 /* call GDestroyNotify without lock held */
4422 for (n = 0; n < subscribers->len; n++)
4424 SignalSubscriber *subscriber;
4425 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
4426 call_destroy_notify (subscriber->context,
4427 subscriber->user_data_free_func,
4428 subscriber->user_data);
4429 g_main_context_unref (subscriber->context);
4432 g_array_free (subscribers, TRUE);
4435 /* ---------------------------------------------------------------------------------------------------- */
4437 static GDBusInterfaceVTable *
4438 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
4440 /* Don't waste memory by copying padding - remember to update this
4441 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
4443 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4447 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
4452 /* ---------------------------------------------------------------------------------------------------- */
4454 static GDBusSubtreeVTable *
4455 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
4457 /* Don't waste memory by copying padding - remember to update this
4458 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
4460 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4464 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
4469 /* ---------------------------------------------------------------------------------------------------- */
4471 struct ExportedObject
4474 GDBusConnection *connection;
4476 /* maps gchar* -> ExportedInterface* */
4477 GHashTable *map_if_name_to_ei;
4480 /* only called with lock held */
4482 exported_object_free (ExportedObject *eo)
4484 g_free (eo->object_path);
4485 g_hash_table_unref (eo->map_if_name_to_ei);
4494 gchar *interface_name;
4495 GDBusInterfaceVTable *vtable;
4496 GDBusInterfaceInfo *interface_info;
4498 GMainContext *context;
4500 GDestroyNotify user_data_free_func;
4501 } ExportedInterface;
4503 /* called with lock held */
4505 exported_interface_free (ExportedInterface *ei)
4507 g_dbus_interface_info_cache_release (ei->interface_info);
4508 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
4510 call_destroy_notify (ei->context,
4511 ei->user_data_free_func,
4514 g_main_context_unref (ei->context);
4516 g_free (ei->interface_name);
4517 _g_dbus_interface_vtable_free (ei->vtable);
4521 /* ---------------------------------------------------------------------------------------------------- */
4523 /* Convenience function to check if @registration_id (if not zero) or
4524 * @subtree_registration_id (if not zero) has been unregistered. If
4525 * so, returns %TRUE.
4527 * May be called by any thread. Caller must *not* hold lock.
4530 has_object_been_unregistered (GDBusConnection *connection,
4531 guint registration_id,
4532 guint subtree_registration_id)
4536 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4540 CONNECTION_LOCK (connection);
4541 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
4542 GUINT_TO_POINTER (registration_id)) == NULL)
4546 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
4547 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
4551 CONNECTION_UNLOCK (connection);
4556 /* ---------------------------------------------------------------------------------------------------- */
4560 GDBusConnection *connection;
4561 GDBusMessage *message;
4563 const gchar *property_name;
4564 const GDBusInterfaceVTable *vtable;
4565 GDBusInterfaceInfo *interface_info;
4566 const GDBusPropertyInfo *property_info;
4567 guint registration_id;
4568 guint subtree_registration_id;
4572 property_data_free (PropertyData *data)
4574 g_object_unref (data->connection);
4575 g_object_unref (data->message);
4579 /* called in thread where object was registered - no locks held */
4581 invoke_get_property_in_idle_cb (gpointer _data)
4583 PropertyData *data = _data;
4586 GDBusMessage *reply;
4588 if (has_object_been_unregistered (data->connection,
4589 data->registration_id,
4590 data->subtree_registration_id))
4592 reply = g_dbus_message_new_method_error (data->message,
4593 "org.freedesktop.DBus.Error.UnknownMethod",
4594 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4595 g_dbus_message_get_path (data->message));
4596 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4597 g_object_unref (reply);
4602 value = data->vtable->get_property (data->connection,
4603 g_dbus_message_get_sender (data->message),
4604 g_dbus_message_get_path (data->message),
4605 data->interface_info->name,
4606 data->property_name,
4613 g_assert_no_error (error);
4615 g_variant_take_ref (value);
4616 reply = g_dbus_message_new_method_reply (data->message);
4617 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4618 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4619 g_variant_unref (value);
4620 g_object_unref (reply);
4624 gchar *dbus_error_name;
4625 g_assert (error != NULL);
4626 dbus_error_name = g_dbus_error_encode_gerror (error);
4627 reply = g_dbus_message_new_method_error_literal (data->message,
4630 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4631 g_free (dbus_error_name);
4632 g_error_free (error);
4633 g_object_unref (reply);
4640 /* called in thread where object was registered - no locks held */
4642 invoke_set_property_in_idle_cb (gpointer _data)
4644 PropertyData *data = _data;
4646 GDBusMessage *reply;
4652 g_variant_get (g_dbus_message_get_body (data->message),
4658 if (!data->vtable->set_property (data->connection,
4659 g_dbus_message_get_sender (data->message),
4660 g_dbus_message_get_path (data->message),
4661 data->interface_info->name,
4662 data->property_name,
4667 gchar *dbus_error_name;
4668 g_assert (error != NULL);
4669 dbus_error_name = g_dbus_error_encode_gerror (error);
4670 reply = g_dbus_message_new_method_error_literal (data->message,
4673 g_free (dbus_error_name);
4674 g_error_free (error);
4678 reply = g_dbus_message_new_method_reply (data->message);
4681 g_assert (reply != NULL);
4682 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4683 g_object_unref (reply);
4684 g_variant_unref (value);
4689 /* called in any thread with connection's lock held */
4691 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4692 GDBusMessage *message,
4693 guint registration_id,
4694 guint subtree_registration_id,
4696 GDBusInterfaceInfo *interface_info,
4697 const GDBusInterfaceVTable *vtable,
4698 GMainContext *main_context,
4702 const char *interface_name;
4703 const char *property_name;
4704 const GDBusPropertyInfo *property_info;
4705 GSource *idle_source;
4706 PropertyData *property_data;
4707 GDBusMessage *reply;
4712 g_variant_get (g_dbus_message_get_body (message),
4717 g_variant_get (g_dbus_message_get_body (message),
4726 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4728 property_info = NULL;
4730 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4731 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4732 if (property_info == NULL)
4734 reply = g_dbus_message_new_method_error (message,
4735 "org.freedesktop.DBus.Error.InvalidArgs",
4736 _("No such property '%s'"),
4738 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4739 g_object_unref (reply);
4744 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4746 reply = g_dbus_message_new_method_error (message,
4747 "org.freedesktop.DBus.Error.InvalidArgs",
4748 _("Property '%s' is not readable"),
4750 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4751 g_object_unref (reply);
4755 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4757 reply = g_dbus_message_new_method_error (message,
4758 "org.freedesktop.DBus.Error.InvalidArgs",
4759 _("Property '%s' is not writable"),
4761 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4762 g_object_unref (reply);
4771 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4772 * of the given value is wrong
4774 g_variant_get_child (g_dbus_message_get_body (message), 2, "v", &value);
4775 if (g_strcmp0 (g_variant_get_type_string (value), property_info->signature) != 0)
4777 reply = g_dbus_message_new_method_error (message,
4778 "org.freedesktop.DBus.Error.InvalidArgs",
4779 _("Error setting property '%s': Expected type '%s' but got '%s'"),
4780 property_name, property_info->signature,
4781 g_variant_get_type_string (value));
4782 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4783 g_variant_unref (value);
4784 g_object_unref (reply);
4789 g_variant_unref (value);
4792 /* If the vtable pointer for get_property() resp. set_property() is
4793 * NULL then dispatch the call via the method_call() handler.
4797 if (vtable->get_property == NULL)
4799 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4800 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4801 vtable, main_context, user_data);
4808 if (vtable->set_property == NULL)
4810 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4811 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4812 vtable, main_context, user_data);
4818 /* ok, got the property info - call user code in an idle handler */
4819 property_data = g_new0 (PropertyData, 1);
4820 property_data->connection = g_object_ref (connection);
4821 property_data->message = g_object_ref (message);
4822 property_data->user_data = user_data;
4823 property_data->property_name = property_name;
4824 property_data->vtable = vtable;
4825 property_data->interface_info = interface_info;
4826 property_data->property_info = property_info;
4827 property_data->registration_id = registration_id;
4828 property_data->subtree_registration_id = subtree_registration_id;
4830 idle_source = g_idle_source_new ();
4831 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4832 g_source_set_callback (idle_source,
4833 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4835 (GDestroyNotify) property_data_free);
4837 g_source_set_name (idle_source, "[gio] invoke_get_property_in_idle_cb");
4839 g_source_set_name (idle_source, "[gio] invoke_set_property_in_idle_cb");
4840 g_source_attach (idle_source, main_context);
4841 g_source_unref (idle_source);
4849 /* called in GDBusWorker thread with connection's lock held */
4851 handle_getset_property (GDBusConnection *connection,
4853 GDBusMessage *message,
4856 ExportedInterface *ei;
4858 const char *interface_name;
4859 const char *property_name;
4864 g_variant_get (g_dbus_message_get_body (message),
4869 g_variant_get (g_dbus_message_get_body (message),
4875 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4876 * no such interface registered
4878 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4881 GDBusMessage *reply;
4882 reply = g_dbus_message_new_method_error (message,
4883 "org.freedesktop.DBus.Error.InvalidArgs",
4884 _("No such interface '%s'"),
4886 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4887 g_object_unref (reply);
4892 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4905 /* ---------------------------------------------------------------------------------------------------- */
4909 GDBusConnection *connection;
4910 GDBusMessage *message;
4912 const GDBusInterfaceVTable *vtable;
4913 GDBusInterfaceInfo *interface_info;
4914 guint registration_id;
4915 guint subtree_registration_id;
4916 } PropertyGetAllData;
4919 property_get_all_data_free (PropertyData *data)
4921 g_object_unref (data->connection);
4922 g_object_unref (data->message);
4926 /* called in thread where object was registered - no locks held */
4928 invoke_get_all_properties_in_idle_cb (gpointer _data)
4930 PropertyGetAllData *data = _data;
4931 GVariantBuilder builder;
4932 GDBusMessage *reply;
4935 if (has_object_been_unregistered (data->connection,
4936 data->registration_id,
4937 data->subtree_registration_id))
4939 reply = g_dbus_message_new_method_error (data->message,
4940 "org.freedesktop.DBus.Error.UnknownMethod",
4941 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4942 g_dbus_message_get_path (data->message));
4943 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4944 g_object_unref (reply);
4948 /* TODO: Right now we never fail this call - we just omit values if
4949 * a get_property() call is failing.
4951 * We could fail the whole call if just a single get_property() call
4952 * returns an error. We need clarification in the D-Bus spec about this.
4954 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4955 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4956 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4958 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4961 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4964 value = data->vtable->get_property (data->connection,
4965 g_dbus_message_get_sender (data->message),
4966 g_dbus_message_get_path (data->message),
4967 data->interface_info->name,
4968 property_info->name,
4975 g_variant_take_ref (value);
4976 g_variant_builder_add (&builder,
4978 property_info->name,
4980 g_variant_unref (value);
4982 g_variant_builder_close (&builder);
4984 reply = g_dbus_message_new_method_reply (data->message);
4985 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4986 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4987 g_object_unref (reply);
4994 interface_has_readable_properties (GDBusInterfaceInfo *interface_info)
4998 if (!interface_info->properties)
5001 for (i = 0; interface_info->properties[i]; i++)
5002 if (interface_info->properties[i]->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE)
5008 /* called in any thread with connection's lock held */
5010 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
5011 GDBusMessage *message,
5012 guint registration_id,
5013 guint subtree_registration_id,
5014 GDBusInterfaceInfo *interface_info,
5015 const GDBusInterfaceVTable *vtable,
5016 GMainContext *main_context,
5020 GSource *idle_source;
5021 PropertyGetAllData *property_get_all_data;
5028 /* If the vtable pointer for get_property() is NULL but we have a
5029 * non-zero number of readable properties, then dispatch the call via
5030 * the method_call() handler.
5032 if (vtable->get_property == NULL && interface_has_readable_properties (interface_info))
5034 schedule_method_call (connection, message, registration_id, subtree_registration_id,
5035 interface_info, NULL, NULL, g_dbus_message_get_body (message),
5036 vtable, main_context, user_data);
5041 /* ok, got the property info - call user in an idle handler */
5042 property_get_all_data = g_new0 (PropertyGetAllData, 1);
5043 property_get_all_data->connection = g_object_ref (connection);
5044 property_get_all_data->message = g_object_ref (message);
5045 property_get_all_data->user_data = user_data;
5046 property_get_all_data->vtable = vtable;
5047 property_get_all_data->interface_info = interface_info;
5048 property_get_all_data->registration_id = registration_id;
5049 property_get_all_data->subtree_registration_id = subtree_registration_id;
5051 idle_source = g_idle_source_new ();
5052 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
5053 g_source_set_callback (idle_source,
5054 invoke_get_all_properties_in_idle_cb,
5055 property_get_all_data,
5056 (GDestroyNotify) property_get_all_data_free);
5057 g_source_set_name (idle_source, "[gio] invoke_get_all_properties_in_idle_cb");
5058 g_source_attach (idle_source, main_context);
5059 g_source_unref (idle_source);
5067 /* called in GDBusWorker thread with connection's lock held */
5069 handle_get_all_properties (GDBusConnection *connection,
5071 GDBusMessage *message)
5073 ExportedInterface *ei;
5075 const char *interface_name;
5079 g_variant_get (g_dbus_message_get_body (message),
5083 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
5084 * no such interface registered
5086 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5089 GDBusMessage *reply;
5090 reply = g_dbus_message_new_method_error (message,
5091 "org.freedesktop.DBus.Error.InvalidArgs",
5092 _("No such interface"),
5094 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5095 g_object_unref (reply);
5100 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
5112 /* ---------------------------------------------------------------------------------------------------- */
5114 static const gchar introspect_header[] =
5115 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
5116 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
5117 "<!-- GDBus " PACKAGE_VERSION " -->\n"
5120 static const gchar introspect_tail[] =
5123 static const gchar introspect_properties_interface[] =
5124 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
5125 " <method name=\"Get\">\n"
5126 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5127 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
5128 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
5130 " <method name=\"GetAll\">\n"
5131 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5132 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
5134 " <method name=\"Set\">\n"
5135 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5136 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
5137 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
5139 " <signal name=\"PropertiesChanged\">\n"
5140 " <arg type=\"s\" name=\"interface_name\"/>\n"
5141 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
5142 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
5146 static const gchar introspect_introspectable_interface[] =
5147 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
5148 " <method name=\"Introspect\">\n"
5149 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
5152 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
5153 " <method name=\"Ping\"/>\n"
5154 " <method name=\"GetMachineId\">\n"
5155 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
5160 introspect_append_header (GString *s)
5162 g_string_append (s, introspect_header);
5166 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
5168 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
5174 begin = object_path + path_len;
5175 end = strchr (begin, '/');
5177 s = g_strndup (begin, end - begin);
5179 s = g_strdup (begin);
5181 if (g_hash_table_lookup (set, s) == NULL)
5182 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
5188 /* TODO: we want a nicer public interface for this */
5189 /* called in any thread with connection's lock held */
5191 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
5196 GHashTableIter hash_iter;
5197 const gchar *object_path;
5203 CONNECTION_ENSURE_LOCK (connection);
5205 path_len = strlen (path);
5209 set = g_hash_table_new (g_str_hash, g_str_equal);
5211 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
5212 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
5213 maybe_add_path (path, path_len, object_path, set);
5215 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
5216 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
5217 maybe_add_path (path, path_len, object_path, set);
5219 p = g_ptr_array_new ();
5220 keys = g_hash_table_get_keys (set);
5221 for (l = keys; l != NULL; l = l->next)
5222 g_ptr_array_add (p, l->data);
5223 g_hash_table_unref (set);
5226 g_ptr_array_add (p, NULL);
5227 ret = (gchar **) g_ptr_array_free (p, FALSE);
5231 /* called in any thread with connection's lock not held */
5233 g_dbus_connection_list_registered (GDBusConnection *connection,
5237 CONNECTION_LOCK (connection);
5238 ret = g_dbus_connection_list_registered_unlocked (connection, path);
5239 CONNECTION_UNLOCK (connection);
5243 /* called in GDBusWorker thread with connection's lock held */
5245 handle_introspect (GDBusConnection *connection,
5247 GDBusMessage *message)
5251 GDBusMessage *reply;
5252 GHashTableIter hash_iter;
5253 ExportedInterface *ei;
5256 /* first the header with the standard interfaces */
5257 s = g_string_sized_new (sizeof (introspect_header) +
5258 sizeof (introspect_properties_interface) +
5259 sizeof (introspect_introspectable_interface) +
5260 sizeof (introspect_tail));
5261 introspect_append_header (s);
5262 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
5263 "org.freedesktop.DBus.Properties"))
5264 g_string_append (s, introspect_properties_interface);
5266 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
5267 "org.freedesktop.DBus.Introspectable"))
5268 g_string_append (s, introspect_introspectable_interface);
5270 /* then include the registered interfaces */
5271 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
5272 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
5273 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
5275 /* finally include nodes registered below us */
5276 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
5277 for (n = 0; registered != NULL && registered[n] != NULL; n++)
5278 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
5279 g_strfreev (registered);
5280 g_string_append (s, introspect_tail);
5282 reply = g_dbus_message_new_method_reply (message);
5283 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5284 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5285 g_object_unref (reply);
5286 g_string_free (s, TRUE);
5291 /* called in thread where object was registered - no locks held */
5293 call_in_idle_cb (gpointer user_data)
5295 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
5296 GDBusInterfaceVTable *vtable;
5297 guint registration_id;
5298 guint subtree_registration_id;
5300 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
5301 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
5303 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
5305 subtree_registration_id))
5307 GDBusMessage *reply;
5308 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
5309 "org.freedesktop.DBus.Error.UnknownMethod",
5310 _("No such interface '%s' on object at path %s"),
5311 g_dbus_method_invocation_get_interface_name (invocation),
5312 g_dbus_method_invocation_get_object_path (invocation));
5313 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5314 g_object_unref (reply);
5318 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
5319 g_assert (vtable != NULL && vtable->method_call != NULL);
5321 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
5322 g_dbus_method_invocation_get_sender (invocation),
5323 g_dbus_method_invocation_get_object_path (invocation),
5324 g_dbus_method_invocation_get_interface_name (invocation),
5325 g_dbus_method_invocation_get_method_name (invocation),
5326 g_dbus_method_invocation_get_parameters (invocation),
5327 g_object_ref (invocation),
5328 g_dbus_method_invocation_get_user_data (invocation));
5334 /* called in GDBusWorker thread with connection's lock held */
5336 schedule_method_call (GDBusConnection *connection,
5337 GDBusMessage *message,
5338 guint registration_id,
5339 guint subtree_registration_id,
5340 const GDBusInterfaceInfo *interface_info,
5341 const GDBusMethodInfo *method_info,
5342 const GDBusPropertyInfo *property_info,
5343 GVariant *parameters,
5344 const GDBusInterfaceVTable *vtable,
5345 GMainContext *main_context,
5348 GDBusMethodInvocation *invocation;
5349 GSource *idle_source;
5351 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
5352 g_dbus_message_get_path (message),
5353 g_dbus_message_get_interface (message),
5354 g_dbus_message_get_member (message),
5362 /* TODO: would be nicer with a real MethodData like we already
5363 * have PropertyData and PropertyGetAllData... */
5364 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
5365 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
5366 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
5368 idle_source = g_idle_source_new ();
5369 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
5370 g_source_set_callback (idle_source,
5374 g_source_set_name (idle_source, "[gio] call_in_idle_cb");
5375 g_source_attach (idle_source, main_context);
5376 g_source_unref (idle_source);
5379 /* called in GDBusWorker thread with connection's lock held */
5381 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
5382 GDBusMessage *message,
5383 guint registration_id,
5384 guint subtree_registration_id,
5385 GDBusInterfaceInfo *interface_info,
5386 const GDBusInterfaceVTable *vtable,
5387 GMainContext *main_context,
5390 GDBusMethodInfo *method_info;
5391 GDBusMessage *reply;
5392 GVariant *parameters;
5394 GVariantType *in_type;
5398 /* TODO: the cost of this is O(n) - it might be worth caching the result */
5399 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
5401 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
5402 * error to the caller
5404 if (method_info == NULL)
5406 reply = g_dbus_message_new_method_error (message,
5407 "org.freedesktop.DBus.Error.UnknownMethod",
5408 _("No such method '%s'"),
5409 g_dbus_message_get_member (message));
5410 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5411 g_object_unref (reply);
5416 parameters = g_dbus_message_get_body (message);
5417 if (parameters == NULL)
5419 parameters = g_variant_new ("()");
5420 g_variant_ref_sink (parameters);
5424 g_variant_ref (parameters);
5427 /* Check that the incoming args are of the right type - if they are not, return
5428 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
5430 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
5431 if (!g_variant_is_of_type (parameters, in_type))
5435 type_string = g_variant_type_dup_string (in_type);
5437 reply = g_dbus_message_new_method_error (message,
5438 "org.freedesktop.DBus.Error.InvalidArgs",
5439 _("Type of message, '%s', does not match expected type '%s'"),
5440 g_variant_get_type_string (parameters),
5442 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5443 g_variant_type_free (in_type);
5444 g_variant_unref (parameters);
5445 g_object_unref (reply);
5446 g_free (type_string);
5450 g_variant_type_free (in_type);
5452 /* schedule the call in idle */
5453 schedule_method_call (connection, message, registration_id, subtree_registration_id,
5454 interface_info, method_info, NULL, parameters,
5455 vtable, main_context, user_data);
5456 g_variant_unref (parameters);
5463 /* ---------------------------------------------------------------------------------------------------- */
5465 /* called in GDBusWorker thread with connection's lock held */
5467 obj_message_func (GDBusConnection *connection,
5469 GDBusMessage *message)
5471 const gchar *interface_name;
5472 const gchar *member;
5473 const gchar *signature;
5478 interface_name = g_dbus_message_get_interface (message);
5479 member = g_dbus_message_get_member (message);
5480 signature = g_dbus_message_get_signature (message);
5482 /* see if we have an interface for handling this call */
5483 if (interface_name != NULL)
5485 ExportedInterface *ei;
5486 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5489 /* we do - invoke the handler in idle in the right thread */
5491 /* handle no vtable or handler being present */
5492 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
5495 handled = validate_and_maybe_schedule_method_call (connection,
5507 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5508 g_strcmp0 (member, "Introspect") == 0 &&
5509 g_strcmp0 (signature, "") == 0)
5511 handled = handle_introspect (connection, eo, message);
5514 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5515 g_strcmp0 (member, "Get") == 0 &&
5516 g_strcmp0 (signature, "ss") == 0)
5518 handled = handle_getset_property (connection, eo, message, TRUE);
5521 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5522 g_strcmp0 (member, "Set") == 0 &&
5523 g_strcmp0 (signature, "ssv") == 0)
5525 handled = handle_getset_property (connection, eo, message, FALSE);
5528 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5529 g_strcmp0 (member, "GetAll") == 0 &&
5530 g_strcmp0 (signature, "s") == 0)
5532 handled = handle_get_all_properties (connection, eo, message);
5541 * g_dbus_connection_register_object:
5542 * @connection: a #GDBusConnection
5543 * @object_path: the object path to register at
5544 * @interface_info: introspection data for the interface
5545 * @vtable: (allow-none): a #GDBusInterfaceVTable to call into or %NULL
5546 * @user_data: (allow-none): data to pass to functions in @vtable
5547 * @user_data_free_func: function to call when the object path is unregistered
5548 * @error: return location for error or %NULL
5550 * Registers callbacks for exported objects at @object_path with the
5551 * D-Bus interface that is described in @interface_info.
5553 * Calls to functions in @vtable (and @user_data_free_func) will happen
5555 * [thread-default main context][g-main-context-push-thread-default]
5556 * of the thread you are calling this method from.
5558 * Note that all #GVariant values passed to functions in @vtable will match
5559 * the signature given in @interface_info - if a remote caller passes
5560 * incorrect values, the `org.freedesktop.DBus.Error.InvalidArgs`
5561 * is returned to the remote caller.
5563 * Additionally, if the remote caller attempts to invoke methods or
5564 * access properties not mentioned in @interface_info the
5565 * `org.freedesktop.DBus.Error.UnknownMethod` resp.
5566 * `org.freedesktop.DBus.Error.InvalidArgs` errors
5567 * are returned to the caller.
5569 * It is considered a programming error if the
5570 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
5571 * #GVariant of incorrect type.
5573 * If an existing callback is already registered at @object_path and
5574 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
5576 * GDBus automatically implements the standard D-Bus interfaces
5577 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
5578 * and org.freedesktop.Peer, so you don't have to implement those for the
5579 * objects you export. You can implement org.freedesktop.DBus.Properties
5580 * yourself, e.g. to handle getting and setting of properties asynchronously.
5582 * Note that the reference count on @interface_info will be
5583 * incremented by 1 (unless allocated statically, e.g. if the
5584 * reference count is -1, see g_dbus_interface_info_ref()) for as long
5585 * as the object is exported. Also note that @vtable will be copied.
5587 * See this [server][gdbus-server] for an example of how to use this method.
5589 * Returns: 0 if @error is set, otherwise a registration id (never 0)
5590 * that can be used with g_dbus_connection_unregister_object()
5595 g_dbus_connection_register_object (GDBusConnection *connection,
5596 const gchar *object_path,
5597 GDBusInterfaceInfo *interface_info,
5598 const GDBusInterfaceVTable *vtable,
5600 GDestroyNotify user_data_free_func,
5604 ExportedInterface *ei;
5607 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5608 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5609 g_return_val_if_fail (interface_info != NULL, 0);
5610 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
5611 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5612 g_return_val_if_fail (check_initialized (connection), 0);
5616 CONNECTION_LOCK (connection);
5618 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5621 eo = g_new0 (ExportedObject, 1);
5622 eo->object_path = g_strdup (object_path);
5623 eo->connection = connection;
5624 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
5627 (GDestroyNotify) exported_interface_free);
5628 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
5631 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
5637 _("An object is already exported for the interface %s at %s"),
5638 interface_info->name,
5643 ei = g_new0 (ExportedInterface, 1);
5644 ei->id = _global_registration_id++; /* TODO: overflow etc. */
5646 ei->user_data = user_data;
5647 ei->user_data_free_func = user_data_free_func;
5648 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
5649 ei->interface_info = g_dbus_interface_info_ref (interface_info);
5650 g_dbus_interface_info_cache_build (ei->interface_info);
5651 ei->interface_name = g_strdup (interface_info->name);
5652 ei->context = g_main_context_ref_thread_default ();
5654 g_hash_table_insert (eo->map_if_name_to_ei,
5655 (gpointer) ei->interface_name,
5657 g_hash_table_insert (connection->map_id_to_ei,
5658 GUINT_TO_POINTER (ei->id),
5664 CONNECTION_UNLOCK (connection);
5670 * g_dbus_connection_unregister_object:
5671 * @connection: a #GDBusConnection
5672 * @registration_id: a registration id obtained from
5673 * g_dbus_connection_register_object()
5675 * Unregisters an object.
5677 * Returns: %TRUE if the object was unregistered, %FALSE otherwise
5682 g_dbus_connection_unregister_object (GDBusConnection *connection,
5683 guint registration_id)
5685 ExportedInterface *ei;
5689 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5690 g_return_val_if_fail (check_initialized (connection), FALSE);
5694 CONNECTION_LOCK (connection);
5696 ei = g_hash_table_lookup (connection->map_id_to_ei,
5697 GUINT_TO_POINTER (registration_id));
5703 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5704 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5705 /* unregister object path if we have no more exported interfaces */
5706 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5707 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5713 CONNECTION_UNLOCK (connection);
5718 /* ---------------------------------------------------------------------------------------------------- */
5721 * g_dbus_connection_emit_signal:
5722 * @connection: a #GDBusConnection
5723 * @destination_bus_name: (allow-none): the unique bus name for the destination
5724 * for the signal or %NULL to emit to all listeners
5725 * @object_path: path of remote object
5726 * @interface_name: D-Bus interface to emit a signal on
5727 * @signal_name: the name of the signal to emit
5728 * @parameters: (allow-none): a #GVariant tuple with parameters for the signal
5729 * or %NULL if not passing parameters
5730 * @error: Return location for error or %NULL
5734 * If the parameters GVariant is floating, it is consumed.
5736 * This can only fail if @parameters is not compatible with the D-Bus protocol.
5738 * Returns: %TRUE unless @error is set
5743 g_dbus_connection_emit_signal (GDBusConnection *connection,
5744 const gchar *destination_bus_name,
5745 const gchar *object_path,
5746 const gchar *interface_name,
5747 const gchar *signal_name,
5748 GVariant *parameters,
5751 GDBusMessage *message;
5757 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5758 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5759 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5760 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5761 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5762 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5763 g_return_val_if_fail (check_initialized (connection), FALSE);
5765 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5767 _g_dbus_debug_print_lock ();
5768 g_print ("========================================================================\n"
5769 "GDBus-debug:Emission:\n"
5770 " >>>> SIGNAL EMISSION %s.%s()\n"
5772 " destination %s\n",
5773 interface_name, signal_name,
5775 destination_bus_name != NULL ? destination_bus_name : "(none)");
5776 _g_dbus_debug_print_unlock ();
5779 message = g_dbus_message_new_signal (object_path,
5783 if (destination_bus_name != NULL)
5784 g_dbus_message_set_header (message,
5785 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5786 g_variant_new_string (destination_bus_name));
5788 if (parameters != NULL)
5789 g_dbus_message_set_body (message, parameters);
5791 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5792 g_object_unref (message);
5798 add_call_flags (GDBusMessage *message,
5799 GDBusCallFlags flags)
5801 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5802 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
5806 decode_method_reply (GDBusMessage *reply,
5807 const gchar *method_name,
5808 const GVariantType *reply_type,
5809 GUnixFDList **out_fd_list,
5815 switch (g_dbus_message_get_message_type (reply))
5817 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5818 result = g_dbus_message_get_body (reply);
5821 result = g_variant_new ("()");
5822 g_variant_ref_sink (result);
5826 g_variant_ref (result);
5829 if (!g_variant_is_of_type (result, reply_type))
5831 gchar *type_string = g_variant_type_dup_string (reply_type);
5835 G_IO_ERROR_INVALID_ARGUMENT,
5836 _("Method '%s' returned type '%s', but expected '%s'"),
5837 method_name, g_variant_get_type_string (result), type_string);
5839 g_variant_unref (result);
5840 g_free (type_string);
5847 if (out_fd_list != NULL)
5849 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5850 if (*out_fd_list != NULL)
5851 g_object_ref (*out_fd_list);
5857 case G_DBUS_MESSAGE_TYPE_ERROR:
5858 g_dbus_message_to_gerror (reply, error);
5862 g_assert_not_reached ();
5872 GSimpleAsyncResult *simple;
5873 GVariantType *reply_type;
5874 gchar *method_name; /* for error message */
5878 GUnixFDList *fd_list;
5882 call_state_free (CallState *state)
5884 g_variant_type_free (state->reply_type);
5885 g_free (state->method_name);
5887 if (state->value != NULL)
5888 g_variant_unref (state->value);
5889 if (state->fd_list != NULL)
5890 g_object_unref (state->fd_list);
5891 g_slice_free (CallState, state);
5894 /* called in any thread, with the connection's lock not held */
5896 g_dbus_connection_call_done (GObject *source,
5897 GAsyncResult *result,
5900 GSimpleAsyncResult *simple;
5901 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5902 CallState *state = user_data;
5904 GDBusMessage *reply;
5907 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5911 if (G_UNLIKELY (_g_dbus_debug_call ()))
5913 _g_dbus_debug_print_lock ();
5914 g_print ("========================================================================\n"
5915 "GDBus-debug:Call:\n"
5916 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5922 g_print ("SUCCESS\n");
5926 g_print ("FAILED: %s\n",
5929 _g_dbus_debug_print_unlock ();
5933 state->value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5935 simple = state->simple; /* why? because state is freed before we unref simple.. */
5938 g_simple_async_result_take_error (state->simple, error);
5939 g_simple_async_result_complete (state->simple);
5940 call_state_free (state);
5944 g_simple_async_result_set_op_res_gpointer (state->simple, state, (GDestroyNotify) call_state_free);
5945 g_simple_async_result_complete (state->simple);
5947 g_clear_object (&reply);
5948 g_object_unref (simple);
5951 /* called in any thread, with the connection's lock not held */
5953 g_dbus_connection_call_internal (GDBusConnection *connection,
5954 const gchar *bus_name,
5955 const gchar *object_path,
5956 const gchar *interface_name,
5957 const gchar *method_name,
5958 GVariant *parameters,
5959 const GVariantType *reply_type,
5960 GDBusCallFlags flags,
5962 GUnixFDList *fd_list,
5963 GCancellable *cancellable,
5964 GAsyncReadyCallback callback,
5967 GDBusMessage *message;
5970 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5971 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5972 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5973 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5974 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5975 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5976 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5977 g_return_if_fail (check_initialized (connection));
5979 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5981 g_return_if_fail (fd_list == NULL);
5984 message = g_dbus_message_new_method_call (bus_name,
5988 add_call_flags (message, flags);
5989 if (parameters != NULL)
5990 g_dbus_message_set_body (message, parameters);
5993 if (fd_list != NULL)
5994 g_dbus_message_set_unix_fd_list (message, fd_list);
5997 /* If the user has no callback then we can just send the message with
5998 * the G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set and skip all
5999 * the logic for processing the reply. If the service sends the reply
6000 * anyway then it will just be ignored.
6002 if (callback != NULL)
6006 state = g_slice_new0 (CallState);
6007 state->simple = g_simple_async_result_new (G_OBJECT (connection),
6008 callback, user_data,
6009 g_dbus_connection_call_internal);
6010 g_simple_async_result_set_check_cancellable (state->simple, cancellable);
6011 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
6013 if (reply_type == NULL)
6014 reply_type = G_VARIANT_TYPE_ANY;
6016 state->reply_type = g_variant_type_copy (reply_type);
6018 g_dbus_connection_send_message_with_reply (connection,
6020 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
6024 g_dbus_connection_call_done,
6026 serial = state->serial;
6030 GDBusMessageFlags flags;
6032 flags = g_dbus_message_get_flags (message);
6033 flags |= G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
6034 g_dbus_message_set_flags (message, flags);
6036 g_dbus_connection_send_message (connection,
6038 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
6042 if (G_UNLIKELY (_g_dbus_debug_call ()))
6044 _g_dbus_debug_print_lock ();
6045 g_print ("========================================================================\n"
6046 "GDBus-debug:Call:\n"
6047 " >>>> ASYNC %s.%s()\n"
6049 " owned by name %s (serial %d)\n",
6053 bus_name != NULL ? bus_name : "(none)",
6055 _g_dbus_debug_print_unlock ();
6058 if (message != NULL)
6059 g_object_unref (message);
6062 /* called in any thread, with the connection's lock not held */
6064 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
6065 GUnixFDList **out_fd_list,
6069 GSimpleAsyncResult *simple;
6072 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
6073 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
6074 g_dbus_connection_call_internal), NULL);
6075 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6077 simple = G_SIMPLE_ASYNC_RESULT (res);
6079 if (g_simple_async_result_propagate_error (simple, error))
6082 state = g_simple_async_result_get_op_res_gpointer (simple);
6083 if (out_fd_list != NULL)
6084 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
6085 return g_variant_ref (state->value);
6088 /* called in any user thread, with the connection's lock not held */
6090 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
6091 const gchar *bus_name,
6092 const gchar *object_path,
6093 const gchar *interface_name,
6094 const gchar *method_name,
6095 GVariant *parameters,
6096 const GVariantType *reply_type,
6097 GDBusCallFlags flags,
6099 GUnixFDList *fd_list,
6100 GUnixFDList **out_fd_list,
6101 GCancellable *cancellable,
6104 GDBusMessage *message;
6105 GDBusMessage *reply;
6107 GError *local_error;
6108 GDBusSendMessageFlags send_flags;
6114 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
6115 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
6116 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
6117 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
6118 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
6119 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
6120 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
6122 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
6124 g_return_val_if_fail (fd_list == NULL, NULL);
6126 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6128 if (!(flags & CALL_FLAGS_INITIALIZING))
6129 g_return_val_if_fail (check_initialized (connection), FALSE);
6131 if (reply_type == NULL)
6132 reply_type = G_VARIANT_TYPE_ANY;
6134 message = g_dbus_message_new_method_call (bus_name,
6138 add_call_flags (message, flags);
6139 if (parameters != NULL)
6140 g_dbus_message_set_body (message, parameters);
6143 if (fd_list != NULL)
6144 g_dbus_message_set_unix_fd_list (message, fd_list);
6147 if (G_UNLIKELY (_g_dbus_debug_call ()))
6149 _g_dbus_debug_print_lock ();
6150 g_print ("========================================================================\n"
6151 "GDBus-debug:Call:\n"
6152 " >>>> SYNC %s.%s()\n"
6154 " owned by name %s\n",
6158 bus_name != NULL ? bus_name : "(none)");
6159 _g_dbus_debug_print_unlock ();
6164 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
6166 /* translate from one flavour of flags to another... */
6167 if (flags & CALL_FLAGS_INITIALIZING)
6168 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
6170 reply = g_dbus_connection_send_message_with_reply_sync (connection,
6174 NULL, /* volatile guint32 *out_serial */
6178 if (G_UNLIKELY (_g_dbus_debug_call ()))
6180 _g_dbus_debug_print_lock ();
6181 g_print ("========================================================================\n"
6182 "GDBus-debug:Call:\n"
6183 " <<<< SYNC COMPLETE %s.%s()\n"
6189 g_print ("SUCCESS\n");
6193 g_print ("FAILED: %s\n",
6194 local_error->message);
6196 _g_dbus_debug_print_unlock ();
6202 *error = local_error;
6204 g_error_free (local_error);
6208 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
6211 if (message != NULL)
6212 g_object_unref (message);
6214 g_object_unref (reply);
6219 /* ---------------------------------------------------------------------------------------------------- */
6222 * g_dbus_connection_call:
6223 * @connection: a #GDBusConnection
6224 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6225 * @connection is not a message bus connection
6226 * @object_path: path of remote object
6227 * @interface_name: D-Bus interface to invoke method on
6228 * @method_name: the name of the method to invoke
6229 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6230 * or %NULL if not passing parameters
6231 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6232 * @flags: flags from the #GDBusCallFlags enumeration
6233 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6234 * timeout or %G_MAXINT for no timeout
6235 * @cancellable: (allow-none): a #GCancellable or %NULL
6236 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request
6237 * is satisfied or %NULL if you don't care about the result of the
6239 * @user_data: the data to pass to @callback
6241 * Asynchronously invokes the @method_name method on the
6242 * @interface_name D-Bus interface on the remote object at
6243 * @object_path owned by @bus_name.
6245 * If @connection is closed then the operation will fail with
6246 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
6247 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
6248 * not compatible with the D-Bus protocol, the operation fails with
6249 * %G_IO_ERROR_INVALID_ARGUMENT.
6251 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
6252 * error will be raised if it does not match. Said another way, if you give a @reply_type
6253 * then any non-%NULL return value will be of this type.
6255 * If the @parameters #GVariant is floating, it is consumed. This allows
6256 * convenient 'inline' use of g_variant_new(), e.g.:
6257 * |[<!-- language="C" -->
6258 * g_dbus_connection_call (connection,
6259 * "org.freedesktop.StringThings",
6260 * "/org/freedesktop/StringThings",
6261 * "org.freedesktop.StringThings",
6263 * g_variant_new ("(ss)",
6267 * G_DBUS_CALL_FLAGS_NONE,
6270 * (GAsyncReadyCallback) two_strings_done,
6274 * This is an asynchronous method. When the operation is finished,
6275 * @callback will be invoked in the
6276 * [thread-default main context][g-main-context-push-thread-default]
6277 * of the thread you are calling this method from. You can then call
6278 * g_dbus_connection_call_finish() to get the result of the operation.
6279 * See g_dbus_connection_call_sync() for the synchronous version of this
6282 * If @callback is %NULL then the D-Bus method call message will be sent with
6283 * the %G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set.
6288 g_dbus_connection_call (GDBusConnection *connection,
6289 const gchar *bus_name,
6290 const gchar *object_path,
6291 const gchar *interface_name,
6292 const gchar *method_name,
6293 GVariant *parameters,
6294 const GVariantType *reply_type,
6295 GDBusCallFlags flags,
6297 GCancellable *cancellable,
6298 GAsyncReadyCallback callback,
6301 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);
6305 * g_dbus_connection_call_finish:
6306 * @connection: a #GDBusConnection
6307 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call()
6308 * @error: return location for error or %NULL
6310 * Finishes an operation started with g_dbus_connection_call().
6312 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6313 * return values. Free with g_variant_unref().
6318 g_dbus_connection_call_finish (GDBusConnection *connection,
6322 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
6326 * g_dbus_connection_call_sync:
6327 * @connection: a #GDBusConnection
6328 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6329 * @connection is not a message bus connection
6330 * @object_path: path of remote object
6331 * @interface_name: D-Bus interface to invoke method on
6332 * @method_name: the name of the method to invoke
6333 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6334 * or %NULL if not passing parameters
6335 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6336 * @flags: flags from the #GDBusCallFlags enumeration
6337 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6338 * timeout or %G_MAXINT for no timeout
6339 * @cancellable: (allow-none): a #GCancellable or %NULL
6340 * @error: return location for error or %NULL
6342 * Synchronously invokes the @method_name method on the
6343 * @interface_name D-Bus interface on the remote object at
6344 * @object_path owned by @bus_name.
6346 * If @connection is closed then the operation will fail with
6347 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
6348 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
6349 * contains a value not compatible with the D-Bus protocol, the operation
6350 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
6352 * If @reply_type is non-%NULL then the reply will be checked for having
6353 * this type and an error will be raised if it does not match. Said
6354 * another way, if you give a @reply_type then any non-%NULL return
6355 * value will be of this type.
6357 * If the @parameters #GVariant is floating, it is consumed.
6358 * This allows convenient 'inline' use of g_variant_new(), e.g.:
6359 * |[<!-- language="C" -->
6360 * g_dbus_connection_call_sync (connection,
6361 * "org.freedesktop.StringThings",
6362 * "/org/freedesktop/StringThings",
6363 * "org.freedesktop.StringThings",
6365 * g_variant_new ("(ss)",
6369 * G_DBUS_CALL_FLAGS_NONE,
6375 * The calling thread is blocked until a reply is received. See
6376 * g_dbus_connection_call() for the asynchronous version of
6379 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6380 * return values. Free with g_variant_unref().
6385 g_dbus_connection_call_sync (GDBusConnection *connection,
6386 const gchar *bus_name,
6387 const gchar *object_path,
6388 const gchar *interface_name,
6389 const gchar *method_name,
6390 GVariant *parameters,
6391 const GVariantType *reply_type,
6392 GDBusCallFlags flags,
6394 GCancellable *cancellable,
6397 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);
6400 /* ---------------------------------------------------------------------------------------------------- */
6405 * g_dbus_connection_call_with_unix_fd_list:
6406 * @connection: a #GDBusConnection
6407 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6408 * @connection is not a message bus connection
6409 * @object_path: path of remote object
6410 * @interface_name: D-Bus interface to invoke method on
6411 * @method_name: the name of the method to invoke
6412 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6413 * or %NULL if not passing parameters
6414 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6415 * @flags: flags from the #GDBusCallFlags enumeration
6416 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6417 * timeout or %G_MAXINT for no timeout
6418 * @fd_list: (allow-none): a #GUnixFDList or %NULL
6419 * @cancellable: (allow-none): a #GCancellable or %NULL
6420 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request is
6421 * satisfied or %NULL if you don't * care about the result of the
6423 * @user_data: The data to pass to @callback.
6425 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
6427 * This method is only available on UNIX.
6432 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
6433 const gchar *bus_name,
6434 const gchar *object_path,
6435 const gchar *interface_name,
6436 const gchar *method_name,
6437 GVariant *parameters,
6438 const GVariantType *reply_type,
6439 GDBusCallFlags flags,
6441 GUnixFDList *fd_list,
6442 GCancellable *cancellable,
6443 GAsyncReadyCallback callback,
6446 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);
6450 * g_dbus_connection_call_with_unix_fd_list_finish:
6451 * @connection: a #GDBusConnection
6452 * @out_fd_list: (out) (allow-none): return location for a #GUnixFDList or %NULL
6453 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
6454 * g_dbus_connection_call_with_unix_fd_list()
6455 * @error: return location for error or %NULL
6457 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
6459 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6460 * return values. Free with g_variant_unref().
6465 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
6466 GUnixFDList **out_fd_list,
6470 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
6474 * g_dbus_connection_call_with_unix_fd_list_sync:
6475 * @connection: a #GDBusConnection
6476 * @bus_name: (allow-none): a unique or well-known bus name or %NULL
6477 * if @connection is not a message bus connection
6478 * @object_path: path of remote object
6479 * @interface_name: D-Bus interface to invoke method on
6480 * @method_name: the name of the method to invoke
6481 * @parameters: (allow-none): a #GVariant tuple with parameters for
6482 * the method or %NULL if not passing parameters
6483 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6484 * @flags: flags from the #GDBusCallFlags enumeration
6485 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6486 * timeout or %G_MAXINT for no timeout
6487 * @fd_list: (allow-none): a #GUnixFDList or %NULL
6488 * @out_fd_list: (out) (allow-none): return location for a #GUnixFDList or %NULL
6489 * @cancellable: (allow-none): a #GCancellable or %NULL
6490 * @error: return location for error or %NULL
6492 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
6494 * This method is only available on UNIX.
6496 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6497 * return values. Free with g_variant_unref().
6502 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
6503 const gchar *bus_name,
6504 const gchar *object_path,
6505 const gchar *interface_name,
6506 const gchar *method_name,
6507 GVariant *parameters,
6508 const GVariantType *reply_type,
6509 GDBusCallFlags flags,
6511 GUnixFDList *fd_list,
6512 GUnixFDList **out_fd_list,
6513 GCancellable *cancellable,
6516 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);
6519 #endif /* G_OS_UNIX */
6521 /* ---------------------------------------------------------------------------------------------------- */
6523 struct ExportedSubtree
6527 GDBusConnection *connection;
6528 GDBusSubtreeVTable *vtable;
6529 GDBusSubtreeFlags flags;
6531 GMainContext *context;
6533 GDestroyNotify user_data_free_func;
6537 exported_subtree_free (ExportedSubtree *es)
6539 call_destroy_notify (es->context,
6540 es->user_data_free_func,
6543 g_main_context_unref (es->context);
6545 _g_dbus_subtree_vtable_free (es->vtable);
6546 g_free (es->object_path);
6550 /* called without lock held in the thread where the caller registered
6554 handle_subtree_introspect (GDBusConnection *connection,
6555 ExportedSubtree *es,
6556 GDBusMessage *message)
6560 GDBusMessage *reply;
6563 const gchar *sender;
6564 const gchar *requested_object_path;
6565 const gchar *requested_node;
6566 GDBusInterfaceInfo **interfaces;
6568 gchar **subnode_paths;
6569 gboolean has_properties_interface;
6570 gboolean has_introspectable_interface;
6574 requested_object_path = g_dbus_message_get_path (message);
6575 sender = g_dbus_message_get_sender (message);
6576 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6578 s = g_string_new (NULL);
6579 introspect_append_header (s);
6581 /* Strictly we don't need the children in dynamic mode, but we avoid the
6582 * conditionals to preserve code clarity
6584 children = es->vtable->enumerate (es->connection,
6591 requested_node = strrchr (requested_object_path, '/') + 1;
6593 /* Assert existence of object if we are not dynamic */
6594 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
6595 !_g_strv_has_string ((const gchar * const *) children, requested_node))
6600 requested_node = NULL;
6603 interfaces = es->vtable->introspect (es->connection,
6608 if (interfaces != NULL)
6610 has_properties_interface = FALSE;
6611 has_introspectable_interface = FALSE;
6613 for (n = 0; interfaces[n] != NULL; n++)
6615 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
6616 has_properties_interface = TRUE;
6617 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
6618 has_introspectable_interface = TRUE;
6620 if (!has_properties_interface)
6621 g_string_append (s, introspect_properties_interface);
6622 if (!has_introspectable_interface)
6623 g_string_append (s, introspect_introspectable_interface);
6625 for (n = 0; interfaces[n] != NULL; n++)
6627 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
6628 g_dbus_interface_info_unref (interfaces[n]);
6630 g_free (interfaces);
6633 /* then include <node> entries from the Subtree for the root */
6636 for (n = 0; children != NULL && children[n] != NULL; n++)
6637 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
6640 /* finally include nodes registered below us */
6641 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
6642 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
6643 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
6644 g_strfreev (subnode_paths);
6646 g_string_append (s, "</node>\n");
6648 reply = g_dbus_message_new_method_reply (message);
6649 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6650 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6651 g_object_unref (reply);
6656 g_string_free (s, TRUE);
6657 g_strfreev (children);
6661 /* called without lock held in the thread where the caller registered
6665 handle_subtree_method_invocation (GDBusConnection *connection,
6666 ExportedSubtree *es,
6667 GDBusMessage *message)
6670 const gchar *sender;
6671 const gchar *interface_name;
6672 const gchar *member;
6673 const gchar *signature;
6674 const gchar *requested_object_path;
6675 const gchar *requested_node;
6677 GDBusInterfaceInfo *interface_info;
6678 const GDBusInterfaceVTable *interface_vtable;
6679 gpointer interface_user_data;
6681 GDBusInterfaceInfo **interfaces;
6682 gboolean is_property_get;
6683 gboolean is_property_set;
6684 gboolean is_property_get_all;
6689 requested_object_path = g_dbus_message_get_path (message);
6690 sender = g_dbus_message_get_sender (message);
6691 interface_name = g_dbus_message_get_interface (message);
6692 member = g_dbus_message_get_member (message);
6693 signature = g_dbus_message_get_signature (message);
6694 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6696 is_property_get = FALSE;
6697 is_property_set = FALSE;
6698 is_property_get_all = FALSE;
6699 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6701 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6702 is_property_get = TRUE;
6703 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6704 is_property_set = TRUE;
6705 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6706 is_property_get_all = TRUE;
6711 requested_node = strrchr (requested_object_path, '/') + 1;
6713 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6715 /* We don't want to dispatch to unenumerated
6716 * nodes, so ensure that the child exists.
6721 children = es->vtable->enumerate (es->connection,
6726 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6727 g_strfreev (children);
6735 requested_node = NULL;
6738 /* get introspection data for the node */
6739 interfaces = es->vtable->introspect (es->connection,
6741 requested_object_path,
6745 if (interfaces == NULL)
6748 interface_info = NULL;
6749 for (n = 0; interfaces[n] != NULL; n++)
6751 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6752 interface_info = interfaces[n];
6755 /* dispatch the call if the user wants to handle it */
6756 if (interface_info != NULL)
6758 /* figure out where to dispatch the method call */
6759 interface_user_data = NULL;
6760 interface_vtable = es->vtable->dispatch (es->connection,
6765 &interface_user_data,
6767 if (interface_vtable == NULL)
6770 CONNECTION_LOCK (connection);
6771 handled = validate_and_maybe_schedule_method_call (es->connection,
6778 interface_user_data);
6779 CONNECTION_UNLOCK (connection);
6781 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6782 else if (is_property_get || is_property_set || is_property_get_all)
6784 if (is_property_get)
6785 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6786 else if (is_property_set)
6787 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6788 else if (is_property_get_all)
6789 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6791 g_assert_not_reached ();
6793 /* see if the object supports this interface at all */
6794 for (n = 0; interfaces[n] != NULL; n++)
6796 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6797 interface_info = interfaces[n];
6800 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6801 * claims it won't support the interface
6803 if (interface_info == NULL)
6805 GDBusMessage *reply;
6806 reply = g_dbus_message_new_method_error (message,
6807 "org.freedesktop.DBus.Error.InvalidArgs",
6808 _("No such interface '%s'"),
6810 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6811 g_object_unref (reply);
6816 /* figure out where to dispatch the property get/set/getall calls */
6817 interface_user_data = NULL;
6818 interface_vtable = es->vtable->dispatch (es->connection,
6823 &interface_user_data,
6825 if (interface_vtable == NULL)
6827 g_warning ("The subtree introspection function indicates that '%s' "
6828 "is a valid interface name, but calling the dispatch "
6829 "function on that interface gave us NULL", interface_name);
6833 if (is_property_get || is_property_set)
6835 CONNECTION_LOCK (connection);
6836 handled = validate_and_maybe_schedule_property_getset (es->connection,
6844 interface_user_data);
6845 CONNECTION_UNLOCK (connection);
6847 else if (is_property_get_all)
6849 CONNECTION_LOCK (connection);
6850 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6857 interface_user_data);
6858 CONNECTION_UNLOCK (connection);
6863 if (interfaces != NULL)
6865 for (n = 0; interfaces[n] != NULL; n++)
6866 g_dbus_interface_info_unref (interfaces[n]);
6867 g_free (interfaces);
6875 GDBusMessage *message;
6876 ExportedSubtree *es;
6877 } SubtreeDeferredData;
6880 subtree_deferred_data_free (SubtreeDeferredData *data)
6882 g_object_unref (data->message);
6886 /* called without lock held in the thread where the caller registered the subtree */
6888 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6890 SubtreeDeferredData *data = _data;
6895 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6896 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6897 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6898 handled = handle_subtree_introspect (data->es->connection,
6902 handled = handle_subtree_method_invocation (data->es->connection,
6908 CONNECTION_LOCK (data->es->connection);
6909 handled = handle_generic_unlocked (data->es->connection, data->message);
6910 CONNECTION_UNLOCK (data->es->connection);
6913 /* if we couldn't handle the request, just bail with the UnknownMethod error */
6916 GDBusMessage *reply;
6917 reply = g_dbus_message_new_method_error (data->message,
6918 "org.freedesktop.DBus.Error.UnknownMethod",
6919 _("Method '%s' on interface '%s' with signature '%s' does not exist"),
6920 g_dbus_message_get_member (data->message),
6921 g_dbus_message_get_interface (data->message),
6922 g_dbus_message_get_signature (data->message));
6923 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6924 g_object_unref (reply);
6930 /* called in GDBusWorker thread with connection's lock held */
6932 subtree_message_func (GDBusConnection *connection,
6933 ExportedSubtree *es,
6934 GDBusMessage *message)
6936 GSource *idle_source;
6937 SubtreeDeferredData *data;
6939 data = g_new0 (SubtreeDeferredData, 1);
6940 data->message = g_object_ref (message);
6943 /* defer this call to an idle handler in the right thread */
6944 idle_source = g_idle_source_new ();
6945 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
6946 g_source_set_callback (idle_source,
6947 process_subtree_vtable_message_in_idle_cb,
6949 (GDestroyNotify) subtree_deferred_data_free);
6950 g_source_set_name (idle_source, "[gio] process_subtree_vtable_message_in_idle_cb");
6951 g_source_attach (idle_source, es->context);
6952 g_source_unref (idle_source);
6954 /* since we own the entire subtree, handlers for objects not in the subtree have been
6955 * tried already by libdbus-1 - so we just need to ensure that we're always going
6956 * to reply to the message
6962 * g_dbus_connection_register_subtree:
6963 * @connection: a #GDBusConnection
6964 * @object_path: the object path to register the subtree at
6965 * @vtable: a #GDBusSubtreeVTable to enumerate, introspect and
6966 * dispatch nodes in the subtree
6967 * @flags: flags used to fine tune the behavior of the subtree
6968 * @user_data: data to pass to functions in @vtable
6969 * @user_data_free_func: function to call when the subtree is unregistered
6970 * @error: return location for error or %NULL
6972 * Registers a whole subtree of dynamic objects.
6974 * The @enumerate and @introspection functions in @vtable are used to
6975 * convey, to remote callers, what nodes exist in the subtree rooted
6978 * When handling remote calls into any node in the subtree, first the
6979 * @enumerate function is used to check if the node exists. If the node exists
6980 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6981 * the @introspection function is used to check if the node supports the
6982 * requested method. If so, the @dispatch function is used to determine
6983 * where to dispatch the call. The collected #GDBusInterfaceVTable and
6984 * #gpointer will be used to call into the interface vtable for processing
6987 * All calls into user-provided code will be invoked in the
6988 * [thread-default main context][g-main-context-push-thread-default]
6989 * of the thread you are calling this method from.
6991 * If an existing subtree is already registered at @object_path or
6992 * then @error is set to #G_IO_ERROR_EXISTS.
6994 * Note that it is valid to register regular objects (using
6995 * g_dbus_connection_register_object()) in a subtree registered with
6996 * g_dbus_connection_register_subtree() - if so, the subtree handler
6997 * is tried as the last resort. One way to think about a subtree
6998 * handler is to consider it a fallback handler for object paths not
6999 * registered via g_dbus_connection_register_object() or other bindings.
7001 * Note that @vtable will be copied so you cannot change it after
7004 * See this [server][gdbus-subtree-server] for an example of how to use
7007 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
7008 * that can be used with g_dbus_connection_unregister_subtree() .
7013 g_dbus_connection_register_subtree (GDBusConnection *connection,
7014 const gchar *object_path,
7015 const GDBusSubtreeVTable *vtable,
7016 GDBusSubtreeFlags flags,
7018 GDestroyNotify user_data_free_func,
7022 ExportedSubtree *es;
7024 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
7025 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
7026 g_return_val_if_fail (vtable != NULL, 0);
7027 g_return_val_if_fail (error == NULL || *error == NULL, 0);
7028 g_return_val_if_fail (check_initialized (connection), 0);
7032 CONNECTION_LOCK (connection);
7034 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
7040 _("A subtree is already exported for %s"),
7045 es = g_new0 (ExportedSubtree, 1);
7046 es->object_path = g_strdup (object_path);
7047 es->connection = connection;
7049 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
7051 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
7052 es->user_data = user_data;
7053 es->user_data_free_func = user_data_free_func;
7054 es->context = g_main_context_ref_thread_default ();
7056 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
7057 g_hash_table_insert (connection->map_id_to_es,
7058 GUINT_TO_POINTER (es->id),
7064 CONNECTION_UNLOCK (connection);
7069 /* ---------------------------------------------------------------------------------------------------- */
7072 * g_dbus_connection_unregister_subtree:
7073 * @connection: a #GDBusConnection
7074 * @registration_id: a subtree registration id obtained from
7075 * g_dbus_connection_register_subtree()
7077 * Unregisters a subtree.
7079 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise
7084 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
7085 guint registration_id)
7087 ExportedSubtree *es;
7090 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
7091 g_return_val_if_fail (check_initialized (connection), FALSE);
7095 CONNECTION_LOCK (connection);
7097 es = g_hash_table_lookup (connection->map_id_to_es,
7098 GUINT_TO_POINTER (registration_id));
7102 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
7103 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
7108 CONNECTION_UNLOCK (connection);
7113 /* ---------------------------------------------------------------------------------------------------- */
7115 /* may be called in any thread, with connection's lock held */
7117 handle_generic_ping_unlocked (GDBusConnection *connection,
7118 const gchar *object_path,
7119 GDBusMessage *message)
7121 GDBusMessage *reply;
7122 reply = g_dbus_message_new_method_reply (message);
7123 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7124 g_object_unref (reply);
7127 /* may be called in any thread, with connection's lock held */
7129 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
7130 const gchar *object_path,
7131 GDBusMessage *message)
7133 GDBusMessage *reply;
7136 if (connection->machine_id == NULL)
7141 connection->machine_id = _g_dbus_get_machine_id (&error);
7142 if (connection->machine_id == NULL)
7144 reply = g_dbus_message_new_method_error_literal (message,
7145 "org.freedesktop.DBus.Error.Failed",
7147 g_error_free (error);
7153 reply = g_dbus_message_new_method_reply (message);
7154 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
7156 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7157 g_object_unref (reply);
7160 /* may be called in any thread, with connection's lock held */
7162 handle_generic_introspect_unlocked (GDBusConnection *connection,
7163 const gchar *object_path,
7164 GDBusMessage *message)
7169 GDBusMessage *reply;
7171 /* first the header */
7172 s = g_string_new (NULL);
7173 introspect_append_header (s);
7175 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
7176 for (n = 0; registered != NULL && registered[n] != NULL; n++)
7177 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
7178 g_strfreev (registered);
7179 g_string_append (s, "</node>\n");
7181 reply = g_dbus_message_new_method_reply (message);
7182 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
7183 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7184 g_object_unref (reply);
7185 g_string_free (s, TRUE);
7188 /* may be called in any thread, with connection's lock held */
7190 handle_generic_unlocked (GDBusConnection *connection,
7191 GDBusMessage *message)
7194 const gchar *interface_name;
7195 const gchar *member;
7196 const gchar *signature;
7199 CONNECTION_ENSURE_LOCK (connection);
7203 interface_name = g_dbus_message_get_interface (message);
7204 member = g_dbus_message_get_member (message);
7205 signature = g_dbus_message_get_signature (message);
7206 path = g_dbus_message_get_path (message);
7208 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
7209 g_strcmp0 (member, "Introspect") == 0 &&
7210 g_strcmp0 (signature, "") == 0)
7212 handle_generic_introspect_unlocked (connection, path, message);
7215 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7216 g_strcmp0 (member, "Ping") == 0 &&
7217 g_strcmp0 (signature, "") == 0)
7219 handle_generic_ping_unlocked (connection, path, message);
7222 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7223 g_strcmp0 (member, "GetMachineId") == 0 &&
7224 g_strcmp0 (signature, "") == 0)
7226 handle_generic_get_machine_id_unlocked (connection, path, message);
7233 /* ---------------------------------------------------------------------------------------------------- */
7235 /* called in GDBusWorker thread with connection's lock held */
7237 distribute_method_call (GDBusConnection *connection,
7238 GDBusMessage *message)
7240 GDBusMessage *reply;
7242 ExportedSubtree *es;
7243 const gchar *object_path;
7244 const gchar *interface_name;
7245 const gchar *member;
7247 gchar *subtree_path;
7250 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
7252 interface_name = g_dbus_message_get_interface (message);
7253 member = g_dbus_message_get_member (message);
7254 path = g_dbus_message_get_path (message);
7255 subtree_path = g_strdup (path);
7256 needle = strrchr (subtree_path, '/');
7257 if (needle != NULL && needle != subtree_path)
7263 g_free (subtree_path);
7264 subtree_path = NULL;
7268 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
7270 _g_dbus_debug_print_lock ();
7271 g_print ("========================================================================\n"
7272 "GDBus-debug:Incoming:\n"
7273 " <<<< METHOD INVOCATION %s.%s()\n"
7275 " invoked by name %s\n"
7277 interface_name, member,
7279 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
7280 g_dbus_message_get_serial (message));
7281 _g_dbus_debug_print_unlock ();
7284 object_path = g_dbus_message_get_path (message);
7285 g_assert (object_path != NULL);
7287 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
7290 if (obj_message_func (connection, eo, message))
7294 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
7297 if (subtree_message_func (connection, es, message))
7301 if (subtree_path != NULL)
7303 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
7306 if (subtree_message_func (connection, es, message))
7311 if (handle_generic_unlocked (connection, message))
7314 /* if we end up here, the message has not been not handled - so return an error saying this */
7315 reply = g_dbus_message_new_method_error (message,
7316 "org.freedesktop.DBus.Error.UnknownMethod",
7317 _("No such interface '%s' on object at path %s"),
7320 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7321 g_object_unref (reply);
7324 g_free (subtree_path);
7327 /* ---------------------------------------------------------------------------------------------------- */
7329 /* Called in any user thread, with the message_bus_lock held. */
7331 message_bus_get_singleton (GBusType bus_type,
7335 const gchar *starter_bus;
7341 case G_BUS_TYPE_SESSION:
7342 ret = &the_session_bus;
7345 case G_BUS_TYPE_SYSTEM:
7346 ret = &the_system_bus;
7349 case G_BUS_TYPE_USER:
7350 ret = &the_user_bus;
7353 case G_BUS_TYPE_MACHINE:
7354 ret = &the_machine_bus;
7357 case G_BUS_TYPE_STARTER:
7358 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
7359 if (g_strcmp0 (starter_bus, "session") == 0)
7361 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
7364 else if (g_strcmp0 (starter_bus, "system") == 0)
7366 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
7371 if (starter_bus != NULL)
7375 G_IO_ERROR_INVALID_ARGUMENT,
7376 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
7377 " - unknown value '%s'"),
7382 g_set_error_literal (error,
7384 G_IO_ERROR_INVALID_ARGUMENT,
7385 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
7386 "variable is not set"));
7392 g_assert_not_reached ();
7400 /* Called in any user thread, without holding locks. */
7401 static GDBusConnection *
7402 get_uninitialized_connection (GBusType bus_type,
7403 GCancellable *cancellable,
7406 GWeakRef *singleton;
7407 GDBusConnection *ret;
7411 G_LOCK (message_bus_lock);
7412 singleton = message_bus_get_singleton (bus_type, error);
7413 if (singleton == NULL)
7416 ret = g_weak_ref_get (singleton);
7421 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
7422 if (address == NULL)
7424 ret = g_object_new (G_TYPE_DBUS_CONNECTION,
7426 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
7427 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
7428 "exit-on-close", TRUE,
7431 g_weak_ref_set (singleton, ret);
7435 g_assert (ret != NULL);
7438 G_UNLOCK (message_bus_lock);
7442 /* May be called from any thread. Must not hold message_bus_lock. */
7444 _g_bus_get_singleton_if_exists (GBusType bus_type)
7446 GWeakRef *singleton;
7447 GDBusConnection *ret = NULL;
7449 G_LOCK (message_bus_lock);
7450 singleton = message_bus_get_singleton (bus_type, NULL);
7451 if (singleton == NULL)
7454 ret = g_weak_ref_get (singleton);
7457 G_UNLOCK (message_bus_lock);
7463 * @bus_type: a #GBusType
7464 * @cancellable: (allow-none): a #GCancellable or %NULL
7465 * @error: return location for error or %NULL
7467 * Synchronously connects to the message bus specified by @bus_type.
7468 * Note that the returned object may shared with other callers,
7469 * e.g. if two separate parts of a process calls this function with
7470 * the same @bus_type, they will share the same object.
7472 * This is a synchronous failable function. See g_bus_get() and
7473 * g_bus_get_finish() for the asynchronous version.
7475 * The returned object is a singleton, that is, shared with other
7476 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7477 * event that you need a private message bus connection, use
7478 * g_dbus_address_get_for_bus_sync() and
7479 * g_dbus_connection_new_for_address().
7481 * Note that the returned #GDBusConnection object will (usually) have
7482 * the #GDBusConnection:exit-on-close property set to %TRUE.
7484 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7485 * Free with g_object_unref().
7490 g_bus_get_sync (GBusType bus_type,
7491 GCancellable *cancellable,
7494 GDBusConnection *connection;
7496 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7498 connection = get_uninitialized_connection (bus_type, cancellable, error);
7499 if (connection == NULL)
7502 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
7504 g_object_unref (connection);
7513 bus_get_async_initable_cb (GObject *source_object,
7517 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
7521 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
7525 g_assert (error != NULL);
7526 g_simple_async_result_take_error (simple, error);
7527 g_object_unref (source_object);
7531 g_simple_async_result_set_op_res_gpointer (simple,
7535 g_simple_async_result_complete_in_idle (simple);
7536 g_object_unref (simple);
7541 * @bus_type: a #GBusType
7542 * @cancellable: (allow-none): a #GCancellable or %NULL
7543 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
7544 * @user_data: the data to pass to @callback
7546 * Asynchronously connects to the message bus specified by @bus_type.
7548 * When the operation is finished, @callback will be invoked. You can
7549 * then call g_bus_get_finish() to get the result of the operation.
7551 * This is a asynchronous failable function. See g_bus_get_sync() for
7552 * the synchronous version.
7557 g_bus_get (GBusType bus_type,
7558 GCancellable *cancellable,
7559 GAsyncReadyCallback callback,
7562 GDBusConnection *connection;
7563 GSimpleAsyncResult *simple;
7566 simple = g_simple_async_result_new (NULL,
7570 g_simple_async_result_set_check_cancellable (simple, cancellable);
7573 connection = get_uninitialized_connection (bus_type, cancellable, &error);
7574 if (connection == NULL)
7576 g_assert (error != NULL);
7577 g_simple_async_result_take_error (simple, error);
7578 g_simple_async_result_complete_in_idle (simple);
7579 g_object_unref (simple);
7583 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
7586 bus_get_async_initable_cb,
7593 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
7595 * @error: return location for error or %NULL
7597 * Finishes an operation started with g_bus_get().
7599 * The returned object is a singleton, that is, shared with other
7600 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7601 * event that you need a private message bus connection, use
7602 * g_dbus_address_get_for_bus_sync() and
7603 * g_dbus_connection_new_for_address().
7605 * Note that the returned #GDBusConnection object will (usually) have
7606 * the #GDBusConnection:exit-on-close property set to %TRUE.
7608 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7609 * Free with g_object_unref().
7614 g_bus_get_finish (GAsyncResult *res,
7617 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
7619 GDBusConnection *ret;
7621 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7623 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
7627 if (g_simple_async_result_propagate_error (simple, error))
7630 object = g_simple_async_result_get_op_res_gpointer (simple);
7631 g_assert (object != NULL);
7632 ret = g_object_ref (G_DBUS_CONNECTION (object));
7638 /* ---------------------------------------------------------------------------------------------------- */