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;
216 /* Extra pseudo-member of GDBusSendMessageFlags.
217 * Set by initable_init() to indicate that despite not being initialized yet,
218 * enough of the only-valid-after-init members are set that we can send a
219 * message, and we're being called from its thread, so no memory barrier is
220 * required before accessing them.
222 #define SEND_MESSAGE_FLAGS_INITIALIZING (1<<31)
224 /* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
225 #define CALL_FLAGS_INITIALIZING (1<<31)
227 /* ---------------------------------------------------------------------------------------------------- */
231 GDestroyNotify callback;
233 GMainContext *context;
234 } CallDestroyNotifyData;
237 call_destroy_notify_data_in_idle (gpointer user_data)
239 CallDestroyNotifyData *data = user_data;
240 data->callback (data->user_data);
245 call_destroy_notify_data_free (CallDestroyNotifyData *data)
247 if (data->context != NULL)
248 g_main_context_unref (data->context);
253 * call_destroy_notify: <internal>
254 * @context: (allow-none): A #GMainContext or %NULL.
255 * @callback: (allow-none): A #GDestroyNotify or %NULL.
256 * @user_data: Data to pass to @callback.
258 * Schedules @callback to run in @context.
261 call_destroy_notify (GMainContext *context,
262 GDestroyNotify callback,
265 GSource *idle_source;
266 CallDestroyNotifyData *data;
268 if (callback == NULL)
271 data = g_new0 (CallDestroyNotifyData, 1);
272 data->callback = callback;
273 data->user_data = user_data;
274 data->context = context;
275 if (data->context != NULL)
276 g_main_context_ref (data->context);
278 idle_source = g_idle_source_new ();
279 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
280 g_source_set_callback (idle_source,
281 call_destroy_notify_data_in_idle,
283 (GDestroyNotify) call_destroy_notify_data_free);
284 g_source_set_name (idle_source, "[gio] call_destroy_notify_data_in_idle");
285 g_source_attach (idle_source, data->context);
286 g_source_unref (idle_source);
292 /* ---------------------------------------------------------------------------------------------------- */
295 _g_strv_has_string (const gchar* const *haystack,
300 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
302 if (g_strcmp0 (haystack[n], needle) == 0)
308 /* ---------------------------------------------------------------------------------------------------- */
311 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
313 // TODO: for some reason this doesn't work on Windows
314 #define CONNECTION_ENSURE_LOCK(obj) do { \
315 if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock))) \
317 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
318 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
323 #define CONNECTION_LOCK(obj) do { \
324 g_mutex_lock (&(obj)->lock); \
327 #define CONNECTION_UNLOCK(obj) do { \
328 g_mutex_unlock (&(obj)->lock); \
331 /* Flags in connection->atomic_flags */
333 FLAG_INITIALIZED = 1 << 0,
334 FLAG_EXIT_ON_CLOSE = 1 << 1,
341 * The #GDBusConnection structure contains only private data and
342 * should only be accessed using the provided API.
346 struct _GDBusConnection
349 GObject parent_instance;
351 /* ------------------------------------------------------------------------ */
352 /* -- General object state ------------------------------------------------ */
353 /* ------------------------------------------------------------------------ */
355 /* General-purpose lock for most fields */
358 /* A lock used in the init() method of the GInitable interface - see comments
359 * in initable_init() for why a separate lock is needed.
361 * If you need both @lock and @init_lock, you must take @init_lock first.
365 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
366 * someone calls org.freedesktop.DBus.Peer.GetMachineId(). Protected by @lock.
370 /* The underlying stream used for communication
371 * Read-only after initable_init(), so it may be read if you either
372 * hold @init_lock or check for initialization first.
376 /* The object used for authentication (if any).
377 * Read-only after initable_init(), so it may be read if you either
378 * hold @init_lock or check for initialization first.
382 /* Last serial used. Protected by @lock. */
385 /* The object used to send/receive messages.
386 * Read-only after initable_init(), so it may be read if you either
387 * hold @init_lock or check for initialization first.
391 /* If connected to a message bus, this contains the unique name assigned to
392 * us by the bus (e.g. ":1.42").
393 * Read-only after initable_init(), so it may be read if you either
394 * hold @init_lock or check for initialization first.
396 gchar *bus_unique_name;
398 /* The GUID returned by the other side if we authenticed as a client or
399 * the GUID to use if authenticating as a server.
400 * Read-only after initable_init(), so it may be read if you either
401 * hold @init_lock or check for initialization first.
405 /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
406 * Inspect @initialization_error to see whether it succeeded or failed.
408 * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
410 * FLAG_CLOSED is the closed property. It may be read at any time, but
411 * may only be written while holding @lock.
413 volatile gint atomic_flags;
415 /* If the connection could not be established during initable_init(),
416 * this GError will be set.
417 * Read-only after initable_init(), so it may be read if you either
418 * hold @init_lock or check for initialization first.
420 GError *initialization_error;
422 /* The result of g_main_context_ref_thread_default() when the object
423 * was created (the GObject _init() function) - this is used for delivery
424 * of the :closed GObject signal.
426 * Only set in the GObject init function, so no locks are needed.
428 GMainContext *main_context_at_construction;
430 /* Read-only construct properties, no locks needed */
432 GDBusConnectionFlags flags;
434 /* Map used for managing method replies, protected by @lock */
435 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
437 /* Maps used for managing signal subscription, protected by @lock */
438 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
439 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
440 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
442 /* Maps used for managing exported objects and subtrees,
445 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
446 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
447 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
448 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
450 /* Map used for storing last used serials for each thread, protected by @lock */
451 GHashTable *map_thread_to_last_serial;
453 /* Structure used for message filters, protected by @lock */
456 /* Capabilities negotiated during authentication
457 * Read-only after initable_init(), so it may be read without holding a
458 * lock, if you check for initialization first.
460 GDBusCapabilityFlags capabilities;
462 /* Protected by @init_lock */
463 GDBusAuthObserver *authentication_observer;
465 /* Read-only after initable_init(), so it may be read if you either
466 * hold @init_lock or check for initialization first.
468 GCredentials *credentials;
470 /* set to TRUE when finalizing */
474 typedef struct ExportedObject ExportedObject;
475 static void exported_object_free (ExportedObject *eo);
477 typedef struct ExportedSubtree ExportedSubtree;
478 static void exported_subtree_free (ExportedSubtree *es);
496 PROP_CAPABILITY_FLAGS,
497 PROP_AUTHENTICATION_OBSERVER,
500 static void distribute_signals (GDBusConnection *connection,
501 GDBusMessage *message);
503 static void distribute_method_call (GDBusConnection *connection,
504 GDBusMessage *message);
506 static gboolean handle_generic_unlocked (GDBusConnection *connection,
507 GDBusMessage *message);
510 static void purge_all_signal_subscriptions (GDBusConnection *connection);
511 static void purge_all_filters (GDBusConnection *connection);
513 static void schedule_method_call (GDBusConnection *connection,
514 GDBusMessage *message,
515 guint registration_id,
516 guint subtree_registration_id,
517 const GDBusInterfaceInfo *interface_info,
518 const GDBusMethodInfo *method_info,
519 const GDBusPropertyInfo *property_info,
520 GVariant *parameters,
521 const GDBusInterfaceVTable *vtable,
522 GMainContext *main_context,
525 #define _G_ENSURE_LOCK(name) do { \
526 if (G_UNLIKELY (G_TRYLOCK(name))) \
528 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
529 "_G_ENSURE_LOCK: Lock '" #name "' is not locked"); \
533 static guint signals[LAST_SIGNAL] = { 0 };
535 static void initable_iface_init (GInitableIface *initable_iface);
536 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
538 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
539 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
540 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
544 * Check that all members of @connection that can only be accessed after
545 * the connection is initialized can safely be accessed. If not,
546 * log a critical warning. This function is a memory barrier.
548 * Returns: %TRUE if initialized
551 check_initialized (GDBusConnection *connection)
553 /* The access to @atomic_flags isn't conditional, so that this function
554 * provides a memory barrier for thread-safety even if checks are disabled.
555 * (If you don't want this stricter guarantee, you can call
556 * g_return_if_fail (check_initialized (c)).)
558 * This isn't strictly necessary now that we've decided use of an
559 * uninitialized GDBusConnection is undefined behaviour, but it seems
560 * better to be as deterministic as is feasible.
562 * (Anything that could suffer a crash from seeing undefined values
563 * must have a race condition - thread A initializes the connection while
564 * thread B calls a method without initialization, hoping that thread A will
565 * win the race - so its behaviour is undefined anyway.)
567 gint flags = g_atomic_int_get (&connection->atomic_flags);
569 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
571 /* We can safely access this, due to the memory barrier above */
572 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
578 MAY_BE_UNINITIALIZED = (1<<1)
579 } CheckUnclosedFlags;
582 * Check the same thing as check_initialized(), and also that the
583 * connection is not closed. If the connection is uninitialized,
584 * raise a critical warning (it's programmer error); if it's closed,
585 * raise a recoverable GError (it's a runtime error).
587 * This function is a memory barrier.
589 * Returns: %TRUE if initialized and not closed
592 check_unclosed (GDBusConnection *connection,
593 CheckUnclosedFlags check,
596 /* check_initialized() is effectively inlined, so we don't waste time
597 * doing two memory barriers
599 gint flags = g_atomic_int_get (&connection->atomic_flags);
601 if (!(check & MAY_BE_UNINITIALIZED))
603 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
604 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
607 if (flags & FLAG_CLOSED)
609 g_set_error_literal (error,
612 _("The connection is closed"));
619 static GHashTable *alive_connections = NULL;
622 g_dbus_connection_dispose (GObject *object)
624 GDBusConnection *connection = G_DBUS_CONNECTION (object);
626 G_LOCK (message_bus_lock);
627 CONNECTION_LOCK (connection);
628 if (connection->worker != NULL)
630 _g_dbus_worker_stop (connection->worker);
631 connection->worker = NULL;
632 if (alive_connections != NULL)
633 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
637 if (alive_connections != NULL)
638 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
640 CONNECTION_UNLOCK (connection);
641 G_UNLOCK (message_bus_lock);
643 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
644 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
648 g_dbus_connection_finalize (GObject *object)
650 GDBusConnection *connection = G_DBUS_CONNECTION (object);
652 connection->finalizing = TRUE;
654 purge_all_signal_subscriptions (connection);
656 purge_all_filters (connection);
657 g_ptr_array_unref (connection->filters);
659 if (connection->authentication_observer != NULL)
660 g_object_unref (connection->authentication_observer);
662 if (connection->auth != NULL)
663 g_object_unref (connection->auth);
665 if (connection->credentials)
666 g_object_unref (connection->credentials);
668 if (connection->stream != NULL)
670 g_object_unref (connection->stream);
671 connection->stream = NULL;
674 g_free (connection->address);
676 g_free (connection->guid);
677 g_free (connection->bus_unique_name);
679 if (connection->initialization_error != NULL)
680 g_error_free (connection->initialization_error);
682 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
684 g_hash_table_unref (connection->map_rule_to_signal_data);
685 g_hash_table_unref (connection->map_id_to_signal_data);
686 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
688 g_hash_table_unref (connection->map_id_to_ei);
689 g_hash_table_unref (connection->map_object_path_to_eo);
690 g_hash_table_unref (connection->map_id_to_es);
691 g_hash_table_unref (connection->map_object_path_to_es);
693 g_hash_table_unref (connection->map_thread_to_last_serial);
695 g_main_context_unref (connection->main_context_at_construction);
697 g_free (connection->machine_id);
699 g_mutex_clear (&connection->init_lock);
700 g_mutex_clear (&connection->lock);
702 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
705 /* called in any user thread, with the connection's lock not held */
707 g_dbus_connection_get_property (GObject *object,
712 GDBusConnection *connection = G_DBUS_CONNECTION (object);
717 g_value_set_object (value, g_dbus_connection_get_stream (connection));
721 g_value_set_string (value, g_dbus_connection_get_guid (connection));
724 case PROP_UNIQUE_NAME:
725 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
729 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
732 case PROP_EXIT_ON_CLOSE:
733 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
736 case PROP_CAPABILITY_FLAGS:
737 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
741 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
746 /* called in any user thread, with the connection's lock not held */
748 g_dbus_connection_set_property (GObject *object,
753 GDBusConnection *connection = G_DBUS_CONNECTION (object);
758 connection->stream = g_value_dup_object (value);
762 connection->guid = g_value_dup_string (value);
766 connection->address = g_value_dup_string (value);
770 connection->flags = g_value_get_flags (value);
773 case PROP_EXIT_ON_CLOSE:
774 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
777 case PROP_AUTHENTICATION_OBSERVER:
778 connection->authentication_observer = g_value_dup_object (value);
782 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
787 /* Base-class implementation of GDBusConnection::closed.
789 * Called in a user thread, by the main context that was thread-default when
790 * the object was constructed.
793 g_dbus_connection_real_closed (GDBusConnection *connection,
794 gboolean remote_peer_vanished,
797 gint flags = g_atomic_int_get (&connection->atomic_flags);
799 /* Because atomic int access is a memory barrier, we can safely read
800 * initialization_error without a lock, as long as we do it afterwards.
802 if (remote_peer_vanished &&
803 (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
804 (flags & FLAG_INITIALIZED) != 0 &&
805 connection->initialization_error == NULL)
809 g_printerr ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
812 g_quark_to_string (error->domain), error->code);
816 g_printerr ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
823 g_dbus_connection_class_init (GDBusConnectionClass *klass)
825 GObjectClass *gobject_class;
827 gobject_class = G_OBJECT_CLASS (klass);
829 gobject_class->finalize = g_dbus_connection_finalize;
830 gobject_class->dispose = g_dbus_connection_dispose;
831 gobject_class->set_property = g_dbus_connection_set_property;
832 gobject_class->get_property = g_dbus_connection_get_property;
834 klass->closed = g_dbus_connection_real_closed;
837 * GDBusConnection:stream:
839 * The underlying #GIOStream used for I/O.
841 * If this is passed on construction and is a #GSocketConnection,
842 * then the corresponding #GSocket will be put into non-blocking mode.
844 * While the #GDBusConnection is active, it will interact with this
845 * stream from a worker thread, so it is not safe to interact with
846 * the stream directly.
850 g_object_class_install_property (gobject_class,
852 g_param_spec_object ("stream",
854 P_("The underlying streams used for I/O"),
858 G_PARAM_CONSTRUCT_ONLY |
859 G_PARAM_STATIC_NAME |
860 G_PARAM_STATIC_BLURB |
861 G_PARAM_STATIC_NICK));
864 * GDBusConnection:address:
866 * A D-Bus address specifying potential endpoints that can be used
867 * when establishing the connection.
871 g_object_class_install_property (gobject_class,
873 g_param_spec_string ("address",
875 P_("D-Bus address specifying potential socket endpoints"),
878 G_PARAM_CONSTRUCT_ONLY |
879 G_PARAM_STATIC_NAME |
880 G_PARAM_STATIC_BLURB |
881 G_PARAM_STATIC_NICK));
884 * GDBusConnection:flags:
886 * Flags from the #GDBusConnectionFlags enumeration.
890 g_object_class_install_property (gobject_class,
892 g_param_spec_flags ("flags",
895 G_TYPE_DBUS_CONNECTION_FLAGS,
896 G_DBUS_CONNECTION_FLAGS_NONE,
898 G_PARAM_CONSTRUCT_ONLY |
899 G_PARAM_STATIC_NAME |
900 G_PARAM_STATIC_BLURB |
901 G_PARAM_STATIC_NICK));
904 * GDBusConnection:guid:
906 * The GUID of the peer performing the role of server when
909 * If you are constructing a #GDBusConnection and pass
910 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
911 * #GDBusConnection:flags property then you MUST also set this
912 * property to a valid guid.
914 * If you are constructing a #GDBusConnection and pass
915 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
916 * #GDBusConnection:flags property you will be able to read the GUID
917 * of the other peer here after the connection has been successfully
922 g_object_class_install_property (gobject_class,
924 g_param_spec_string ("guid",
926 P_("GUID of the server peer"),
930 G_PARAM_CONSTRUCT_ONLY |
931 G_PARAM_STATIC_NAME |
932 G_PARAM_STATIC_BLURB |
933 G_PARAM_STATIC_NICK));
936 * GDBusConnection:unique-name:
938 * The unique name as assigned by the message bus or %NULL if the
939 * connection is not open or not a message bus connection.
943 g_object_class_install_property (gobject_class,
945 g_param_spec_string ("unique-name",
947 P_("Unique name of bus connection"),
950 G_PARAM_STATIC_NAME |
951 G_PARAM_STATIC_BLURB |
952 G_PARAM_STATIC_NICK));
955 * GDBusConnection:closed:
957 * A boolean specifying whether the connection has been closed.
961 g_object_class_install_property (gobject_class,
963 g_param_spec_boolean ("closed",
965 P_("Whether the connection is closed"),
968 G_PARAM_STATIC_NAME |
969 G_PARAM_STATIC_BLURB |
970 G_PARAM_STATIC_NICK));
973 * GDBusConnection:exit-on-close:
975 * A boolean specifying whether the process will be terminated (by
976 * calling `raise(SIGTERM)`) if the connection is closed by the
979 * Note that #GDBusConnection objects returned by g_bus_get_finish()
980 * and g_bus_get_sync() will (usually) have this property set to %TRUE.
984 g_object_class_install_property (gobject_class,
986 g_param_spec_boolean ("exit-on-close",
988 P_("Whether the process is terminated when the connection is closed"),
992 G_PARAM_STATIC_NAME |
993 G_PARAM_STATIC_BLURB |
994 G_PARAM_STATIC_NICK));
997 * GDBusConnection:capabilities:
999 * Flags from the #GDBusCapabilityFlags enumeration
1000 * representing connection features negotiated with the other peer.
1004 g_object_class_install_property (gobject_class,
1005 PROP_CAPABILITY_FLAGS,
1006 g_param_spec_flags ("capabilities",
1009 G_TYPE_DBUS_CAPABILITY_FLAGS,
1010 G_DBUS_CAPABILITY_FLAGS_NONE,
1012 G_PARAM_STATIC_NAME |
1013 G_PARAM_STATIC_BLURB |
1014 G_PARAM_STATIC_NICK));
1017 * GDBusConnection:authentication-observer:
1019 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
1023 g_object_class_install_property (gobject_class,
1024 PROP_AUTHENTICATION_OBSERVER,
1025 g_param_spec_object ("authentication-observer",
1026 P_("Authentication Observer"),
1027 P_("Object used to assist in the authentication process"),
1028 G_TYPE_DBUS_AUTH_OBSERVER,
1030 G_PARAM_CONSTRUCT_ONLY |
1031 G_PARAM_STATIC_NAME |
1032 G_PARAM_STATIC_BLURB |
1033 G_PARAM_STATIC_NICK));
1036 * GDBusConnection::closed:
1037 * @connection: the #GDBusConnection emitting the signal
1038 * @remote_peer_vanished: %TRUE if @connection is closed because the
1039 * remote peer closed its end of the connection
1040 * @error: (allow-none): a #GError with more details about the event or %NULL
1042 * Emitted when the connection is closed.
1044 * The cause of this event can be
1046 * - If g_dbus_connection_close() is called. In this case
1047 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
1049 * - If the remote peer closes the connection. In this case
1050 * @remote_peer_vanished is set to %TRUE and @error is set.
1052 * - If the remote peer sends invalid or malformed data. In this
1053 * case @remote_peer_vanished is set to %FALSE and @error is set.
1055 * Upon receiving this signal, you should give up your reference to
1056 * @connection. You are guaranteed that this signal is emitted only
1061 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
1062 G_TYPE_DBUS_CONNECTION,
1064 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1075 g_dbus_connection_init (GDBusConnection *connection)
1077 g_mutex_init (&connection->lock);
1078 g_mutex_init (&connection->init_lock);
1080 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
1082 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1084 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1086 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1089 (GDestroyNotify) g_ptr_array_unref);
1091 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1094 (GDestroyNotify) exported_object_free);
1096 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1099 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1102 (GDestroyNotify) exported_subtree_free);
1104 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1107 connection->map_thread_to_last_serial = g_hash_table_new (g_direct_hash,
1110 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1112 connection->filters = g_ptr_array_new ();
1116 * g_dbus_connection_get_stream:
1117 * @connection: a #GDBusConnection
1119 * Gets the underlying stream used for IO.
1121 * While the #GDBusConnection is active, it will interact with this
1122 * stream from a worker thread, so it is not safe to interact with
1123 * the stream directly.
1125 * Returns: (transfer none): the stream used for IO
1130 g_dbus_connection_get_stream (GDBusConnection *connection)
1132 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1134 /* do not use g_return_val_if_fail(), we want the memory barrier */
1135 if (!check_initialized (connection))
1138 return connection->stream;
1142 * g_dbus_connection_start_message_processing:
1143 * @connection: a #GDBusConnection
1145 * If @connection was created with
1146 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1147 * starts processing messages. Does nothing on if @connection wasn't
1148 * created with this flag or if the method has already been called.
1153 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1155 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1157 /* do not use g_return_val_if_fail(), we want the memory barrier */
1158 if (!check_initialized (connection))
1161 g_assert (connection->worker != NULL);
1162 _g_dbus_worker_unfreeze (connection->worker);
1166 * g_dbus_connection_is_closed:
1167 * @connection: a #GDBusConnection
1169 * Gets whether @connection is closed.
1171 * Returns: %TRUE if the connection is closed, %FALSE otherwise
1176 g_dbus_connection_is_closed (GDBusConnection *connection)
1180 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1182 flags = g_atomic_int_get (&connection->atomic_flags);
1184 return (flags & FLAG_CLOSED) ? TRUE : FALSE;
1188 * g_dbus_connection_get_capabilities:
1189 * @connection: a #GDBusConnection
1191 * Gets the capabilities negotiated with the remote peer
1193 * Returns: zero or more flags from the #GDBusCapabilityFlags enumeration
1197 GDBusCapabilityFlags
1198 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1200 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1202 /* do not use g_return_val_if_fail(), we want the memory barrier */
1203 if (!check_initialized (connection))
1204 return G_DBUS_CAPABILITY_FLAGS_NONE;
1206 return connection->capabilities;
1209 /* ---------------------------------------------------------------------------------------------------- */
1211 /* Called in a temporary thread without holding locks. */
1213 flush_in_thread_func (GSimpleAsyncResult *res,
1215 GCancellable *cancellable)
1220 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1223 g_simple_async_result_take_error (res, error);
1227 * g_dbus_connection_flush:
1228 * @connection: a #GDBusConnection
1229 * @cancellable: (allow-none): a #GCancellable or %NULL
1230 * @callback: (allow-none): a #GAsyncReadyCallback to call when the
1231 * request is satisfied or %NULL if you don't care about the result
1232 * @user_data: The data to pass to @callback
1234 * Asynchronously flushes @connection, that is, writes all queued
1235 * outgoing message to the transport and then flushes the transport
1236 * (using g_output_stream_flush_async()). This is useful in programs
1237 * that wants to emit a D-Bus signal and then exit immediately. Without
1238 * flushing the connection, there is no guaranteed that the message has
1239 * been sent to the networking buffers in the OS kernel.
1241 * This is an asynchronous method. When the operation is finished,
1242 * @callback will be invoked in the
1243 * [thread-default main context][g-main-context-push-thread-default]
1244 * of the thread you are calling this method from. You can
1245 * then call g_dbus_connection_flush_finish() to get the result of the
1246 * operation. See g_dbus_connection_flush_sync() for the synchronous
1252 g_dbus_connection_flush (GDBusConnection *connection,
1253 GCancellable *cancellable,
1254 GAsyncReadyCallback callback,
1257 GSimpleAsyncResult *simple;
1259 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1261 simple = g_simple_async_result_new (G_OBJECT (connection),
1264 g_dbus_connection_flush);
1265 g_simple_async_result_set_check_cancellable (simple, cancellable);
1266 g_simple_async_result_run_in_thread (simple,
1267 flush_in_thread_func,
1270 g_object_unref (simple);
1274 * g_dbus_connection_flush_finish:
1275 * @connection: a #GDBusConnection
1276 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1277 * to g_dbus_connection_flush()
1278 * @error: return location for error or %NULL
1280 * Finishes an operation started with g_dbus_connection_flush().
1282 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1287 g_dbus_connection_flush_finish (GDBusConnection *connection,
1291 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1296 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1297 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1298 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1300 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1302 if (g_simple_async_result_propagate_error (simple, error))
1312 * g_dbus_connection_flush_sync:
1313 * @connection: a #GDBusConnection
1314 * @cancellable: (allow-none): a #GCancellable or %NULL
1315 * @error: return location for error or %NULL
1317 * Synchronously flushes @connection. The calling thread is blocked
1318 * until this is done. See g_dbus_connection_flush() for the
1319 * asynchronous version of this method and more details about what it
1322 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1327 g_dbus_connection_flush_sync (GDBusConnection *connection,
1328 GCancellable *cancellable,
1333 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1334 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1338 /* This is only a best-effort attempt to see whether the connection is
1339 * closed, so it doesn't need the lock. If the connection closes just
1340 * after this check, but before scheduling the flush operation, the
1341 * result will be more or less the same as if the connection closed while
1342 * the flush operation was pending - it'll fail with either CLOSED or
1345 if (!check_unclosed (connection, 0, error))
1348 g_assert (connection->worker != NULL);
1350 ret = _g_dbus_worker_flush_sync (connection->worker,
1358 /* ---------------------------------------------------------------------------------------------------- */
1362 GDBusConnection *connection;
1364 gboolean remote_peer_vanished;
1368 emit_closed_data_free (EmitClosedData *data)
1370 g_object_unref (data->connection);
1371 if (data->error != NULL)
1372 g_error_free (data->error);
1376 /* Called in a user thread that has acquired the main context that was
1377 * thread-default when the object was constructed
1380 emit_closed_in_idle (gpointer user_data)
1382 EmitClosedData *data = user_data;
1385 g_object_notify (G_OBJECT (data->connection), "closed");
1386 g_signal_emit (data->connection,
1387 signals[CLOSED_SIGNAL],
1389 data->remote_peer_vanished,
1395 /* Can be called from any thread, must hold lock.
1396 * FLAG_CLOSED must already have been set.
1399 schedule_closed_unlocked (GDBusConnection *connection,
1400 gboolean remote_peer_vanished,
1403 GSource *idle_source;
1404 EmitClosedData *data;
1406 CONNECTION_ENSURE_LOCK (connection);
1408 data = g_new0 (EmitClosedData, 1);
1409 data->connection = g_object_ref (connection);
1410 data->remote_peer_vanished = remote_peer_vanished;
1411 data->error = error != NULL ? g_error_copy (error) : NULL;
1413 idle_source = g_idle_source_new ();
1414 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1415 g_source_set_callback (idle_source,
1416 emit_closed_in_idle,
1418 (GDestroyNotify) emit_closed_data_free);
1419 g_source_set_name (idle_source, "[gio] emit_closed_in_idle");
1420 g_source_attach (idle_source, connection->main_context_at_construction);
1421 g_source_unref (idle_source);
1424 /* ---------------------------------------------------------------------------------------------------- */
1427 * g_dbus_connection_close:
1428 * @connection: a #GDBusConnection
1429 * @cancellable: (allow-none): a #GCancellable or %NULL
1430 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request is
1431 * satisfied or %NULL if you don't care about the result
1432 * @user_data: The data to pass to @callback
1434 * Closes @connection. Note that this never causes the process to
1435 * exit (this might only happen if the other end of a shared message
1436 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1438 * Once the connection is closed, operations such as sending a message
1439 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1440 * will not automatically flush the connection so queued messages may
1441 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1443 * If @connection is already closed, this method fails with
1444 * %G_IO_ERROR_CLOSED.
1446 * When @connection has been closed, the #GDBusConnection::closed
1447 * signal is emitted in the
1448 * [thread-default main context][g-main-context-push-thread-default]
1449 * of the thread that @connection was constructed in.
1451 * This is an asynchronous method. When the operation is finished,
1452 * @callback will be invoked in the
1453 * [thread-default main context][g-main-context-push-thread-default]
1454 * of the thread you are calling this method from. You can
1455 * then call g_dbus_connection_close_finish() to get the result of the
1456 * operation. See g_dbus_connection_close_sync() for the synchronous
1462 g_dbus_connection_close (GDBusConnection *connection,
1463 GCancellable *cancellable,
1464 GAsyncReadyCallback callback,
1467 GSimpleAsyncResult *simple;
1469 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1471 /* do not use g_return_val_if_fail(), we want the memory barrier */
1472 if (!check_initialized (connection))
1475 g_assert (connection->worker != NULL);
1477 simple = g_simple_async_result_new (G_OBJECT (connection),
1480 g_dbus_connection_close);
1481 g_simple_async_result_set_check_cancellable (simple, cancellable);
1482 _g_dbus_worker_close (connection->worker, cancellable, simple);
1483 g_object_unref (simple);
1487 * g_dbus_connection_close_finish:
1488 * @connection: a #GDBusConnection
1489 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1490 * to g_dbus_connection_close()
1491 * @error: return location for error or %NULL
1493 * Finishes an operation started with g_dbus_connection_close().
1495 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1500 g_dbus_connection_close_finish (GDBusConnection *connection,
1504 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1509 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1510 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1511 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1513 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1515 if (g_simple_async_result_propagate_error (simple, error))
1526 GAsyncResult *result;
1529 /* Can be called by any thread, without the connection lock */
1531 sync_close_cb (GObject *source_object,
1535 SyncCloseData *data = user_data;
1537 data->result = g_object_ref (res);
1538 g_main_loop_quit (data->loop);
1542 * g_dbus_connection_close_sync:
1543 * @connection: a #GDBusConnection
1544 * @cancellable: (allow-none): a #GCancellable or %NULL
1545 * @error: return location for error or %NULL
1547 * Synchronously closees @connection. The calling thread is blocked
1548 * until this is done. See g_dbus_connection_close() for the
1549 * asynchronous version of this method and more details about what it
1552 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1557 g_dbus_connection_close_sync (GDBusConnection *connection,
1558 GCancellable *cancellable,
1563 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1564 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1568 if (check_unclosed (connection, 0, error))
1570 GMainContext *context;
1573 context = g_main_context_new ();
1574 g_main_context_push_thread_default (context);
1575 data.loop = g_main_loop_new (context, TRUE);
1578 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1579 g_main_loop_run (data.loop);
1580 ret = g_dbus_connection_close_finish (connection, data.result, error);
1582 g_object_unref (data.result);
1583 g_main_loop_unref (data.loop);
1584 g_main_context_pop_thread_default (context);
1585 g_main_context_unref (context);
1591 /* ---------------------------------------------------------------------------------------------------- */
1594 * g_dbus_get_bus_id:
1595 * @connection: a #GDBusConnection
1596 * @timeout_msec: the timeout in milliseconds, -1 to use the default timeout
1597 * @error: return location for error or %NULL
1599 * Synchronously returns the unique ID of the bus.
1601 * If @connection is closed then the operation will fail with
1602 * %G_IO_ERROR_CLOSED.
1604 * The calling thread is blocked until a reply is received.
1606 * Returns: the unique ID of the bus or %NULL if @error is set.
1607 * Free with g_free().
1612 g_dbus_get_bus_id (GDBusConnection *connection,
1619 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1620 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1621 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1626 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1627 "org.freedesktop.DBus", "GetId",
1628 NULL, G_VARIANT_TYPE ("(s)"),
1629 G_DBUS_CALL_FLAGS_NONE, timeout_msec, NULL, error);
1632 g_variant_get (result, "(s)", &bus_id);
1633 g_variant_unref (result);
1642 LIST_ACTIVATABLE_NAMES,
1644 } GDBusListNameType;
1647 _g_dbus_get_list_internal (GDBusConnection *connection,
1649 GDBusListNameType list_name_type,
1662 if (list_name_type == LIST_QUEUED_OWNERS)
1664 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1665 "org.freedesktop.DBus", "ListQueuedOwners",
1666 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(as)"),
1667 G_DBUS_CALL_FLAGS_NONE, timeout_msec, NULL, error);
1673 if (list_name_type == LIST_NAMES)
1674 method_name = "ListNames";
1676 method_name = "ListActivatableNames";
1678 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1679 "org.freedesktop.DBus", method_name,
1680 NULL, G_VARIANT_TYPE ("(as)"),
1681 G_DBUS_CALL_FLAGS_NONE, timeout_msec, NULL, error);
1686 g_variant_get (result, "(as)", &iter);
1687 n = g_variant_iter_n_children (iter);
1688 strv = g_new (gchar *, n + 1);
1691 while (g_variant_iter_loop (iter, "s", &str))
1693 strv[i] = g_strdup (str);
1698 g_variant_iter_free (iter);
1699 g_variant_unref (result);
1706 * g_dbus_get_list_names:
1707 * @connection: a #GDBusConnection
1708 * @timeout_msec: the timeout in milliseconds, -1 to use the default timeout
1709 * @error: return location for error or %NULL
1711 * Synchronously returns a list of all currently-owned names on the bus.
1713 * If @connection is closed then the operation will fail with
1714 * %G_IO_ERROR_CLOSED.
1716 * The calling thread is blocked until a reply is received.
1718 * Returns: a list of all currently-owned names on the bus.
1719 * Free with g_strfreev().
1724 g_dbus_get_list_names (GDBusConnection *connection,
1730 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1731 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1732 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1734 strv = _g_dbus_get_list_internal (connection, NULL, LIST_NAMES, timeout_msec, error);
1740 * g_dbus_get_list_activatable_names:
1741 * @connection: a #GDBusConnection
1742 * @timeout_msec: the timeout in milliseconds, -1 to use the default timeout
1743 * @error: return location for error or %NULL
1745 * Synchronously returns a list of all names that can be activated on the bus.
1747 * If @connection is closed then the operation will fail with
1748 * %G_IO_ERROR_CLOSED.
1750 * The calling thread is blocked until a reply is received.
1752 * Returns: a list of all names that can be activated on the bus.
1753 * Free with g_strfreev().
1758 g_dbus_get_list_activatable_names (GDBusConnection *connection,
1764 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1765 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1766 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1768 strv = _g_dbus_get_list_internal (connection, NULL, LIST_ACTIVATABLE_NAMES, timeout_msec, error);
1774 * g_dbus_get_list_queued_names:
1775 * @connection: a #GDBusConnection
1776 * @name: a unique or well-known bus name
1777 * @timeout_msec: the timeout in milliseconds, -1 to use the default timeout
1778 * @error: return location for error or %NULL
1780 * Synchronously returns the unique bus names of connections currently queued
1783 * If @connection is closed then the operation will fail with
1784 * %G_IO_ERROR_CLOSED. If @name contains a value not compatible with
1785 * the D-Bus syntax and naming conventions for bus names, the operation
1788 * The calling thread is blocked until a reply is received.
1790 * Returns: the unique bus names of connections currently queued for the @name
1791 * or %NULL if @error is set. Free with g_strfreev().
1796 g_dbus_get_list_queued_owners (GDBusConnection *connection,
1803 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1804 g_return_val_if_fail (name == NULL || g_dbus_is_name (name), NULL);
1805 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1806 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1808 strv = _g_dbus_get_list_internal (connection, name, LIST_QUEUED_OWNERS, timeout_msec, error);
1814 * g_dbus_get_name_owner:
1815 * @connection: a #GDBusConnection
1816 * @name: well-known bus name to get the owner of
1817 * @timeout_msec: the timeout in milliseconds, -1 to use the default timeout
1818 * @error: return location for error or %NULL
1820 * Synchronously returns the unique connection name of the primary owner of
1821 * the name given. If the requested name doesn't have an owner, an @error is
1824 * If @connection is closed then the operation will fail with
1825 * %G_IO_ERROR_CLOSED. If @name contains a value not compatible with
1826 * the D-Bus syntax and naming conventions for bus names, the operation
1829 * The calling thread is blocked until a reply is received.
1831 * Returns: the unique connection name of the primary owner of the
1832 * name given. If the requested name doesn't have an owner, function
1833 * returns %NULL and @error is set. Free with g_free().
1838 g_dbus_get_name_owner (GDBusConnection *connection,
1846 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1847 g_return_val_if_fail (name == NULL || g_dbus_is_name (name), NULL);
1848 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1849 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1854 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1855 "org.freedesktop.DBus", "GetNameOwner",
1856 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(s)"),
1857 G_DBUS_CALL_FLAGS_NONE, timeout_msec, NULL, error);
1860 g_variant_get (result, "(s)", &name_owner);
1861 g_variant_unref (result);
1870 * g_dbus_name_has_owner:
1871 * @connection: a #GDBusConnection
1872 * @name: a unique or well-known bus name
1873 * @timeout_msec: the timeout in milliseconds, -1 to use the default timeout
1874 * @error: return location for error or %NULL
1876 * Synchronously checks if the specified name exists (currently has an owner).
1878 * If @connection is closed then the operation will fail with
1879 * %G_IO_ERROR_CLOSED. If @name contains a value not compatible with
1880 * the D-Bus syntax and naming conventions for bus names, the operation
1883 * The calling thread is blocked until a reply is received.
1885 * Returns: %TRUE if specified name exists (currently has an owner)
1886 * If the requested name doesn't have an owner or @error is set,
1887 * function returns %FALSE.
1892 g_dbus_name_has_owner (GDBusConnection *connection,
1900 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1901 g_return_val_if_fail (name == NULL || g_dbus_is_name (name), NULL);
1902 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1903 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1907 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1908 "org.freedesktop.DBus", "NameHasOwner",
1909 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(b)"),
1910 G_DBUS_CALL_FLAGS_NONE, timeout_msec, NULL, error);
1913 g_variant_get (result, "(b)", &ret);
1914 g_variant_unref (result);
1923 * g_dbus_get_connection_pid:
1924 * @connection: a #GDBusConnection
1925 * @name: a unique or well-known bus name of the connection to query
1926 * @timeout_msec: the timeout in milliseconds, -1 to use the default timeout
1927 * @error: return location for error or %NULL
1929 * Synchronously returns the Unix process ID of the process connected to the
1930 * bus. If unable to determine it, an @error is returned.
1932 * If @connection is closed then the operation will fail with
1933 * %G_IO_ERROR_CLOSED. If @name contains a value not compatible with
1934 * the D-Bus syntax and naming conventions for bus names, the operation
1935 * returns (guint32) -1.
1937 * The calling thread is blocked until a reply is received.
1939 * Returns: the Unix process ID of the process connected to the bus or
1940 * (guint32) -1 if @error is set.
1945 g_dbus_get_connection_pid (GDBusConnection *connection,
1953 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), -1);
1954 g_return_val_if_fail (name == NULL || g_dbus_is_name (name), -1);
1955 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, -1);
1956 g_return_val_if_fail (error == NULL || *error == NULL, -1);
1961 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1962 "org.freedesktop.DBus", "GetConnectionUnixProcessID",
1963 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(u)"),
1964 G_DBUS_CALL_FLAGS_NONE, timeout_msec, NULL, error);
1967 g_variant_get (result, "(u)", &pid);
1968 g_variant_unref (result);
1975 * g_dbus_get_connection_uid:
1976 * @connection: a #GDBusConnection
1977 * @name: a unique or well-known bus name of the connection to query
1978 * @timeout_msec: the timeout in milliseconds, -1 to use the default timeout
1979 * @error: return location for error or %NULL
1981 * Synchronously returns the Unix user ID of the process connected to the
1982 * bus. If unable to determine it, an @error is returned.
1984 * If @connection is closed then the operation will fail with
1985 * %G_IO_ERROR_CLOSED. If @name contains a value not compatible with
1986 * the D-Bus syntax and naming conventions for bus names, the operation
1987 * returns (guint32) -1.
1989 * The calling thread is blocked until a reply is received.
1991 * Returns: the Unix user ID of the process connected to the bus or
1992 * (guint32) -1 if @error is set.
1997 g_dbus_get_connection_uid (GDBusConnection *connection,
2005 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), -1);
2006 g_return_val_if_fail (name == NULL || g_dbus_is_name (name), -1);
2007 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, -1);
2008 g_return_val_if_fail (error == NULL || *error == NULL, -1);
2013 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
2014 "org.freedesktop.DBus", "GetConnectionUnixUser",
2015 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(u)"),
2016 G_DBUS_CALL_FLAGS_NONE, timeout_msec, NULL, error);
2019 g_variant_get (result, "(u)", &uid);
2020 g_variant_unref (result);
2026 /* ---------------------------------------------------------------------------------------------------- */
2029 * g_dbus_connection_get_last_serial:
2030 * @connection: a #GDBusConnection
2032 * Retrieves the last serial number assigned to a #GDBusMessage on
2033 * the current thread. This includes messages sent via both low-level
2034 * API such as g_dbus_connection_send_message() as well as
2035 * high-level API such as g_dbus_connection_emit_signal(),
2036 * g_dbus_connection_call() or g_dbus_proxy_call().
2038 * Returns: the last used serial or zero when no message has been sent
2039 * within the current thread
2044 g_dbus_connection_get_last_serial (GDBusConnection *connection)
2048 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2050 CONNECTION_LOCK (connection);
2051 ret = GPOINTER_TO_UINT (g_hash_table_lookup (connection->map_thread_to_last_serial,
2053 CONNECTION_UNLOCK (connection);
2058 /* ---------------------------------------------------------------------------------------------------- */
2060 /* Can be called by any thread, with the connection lock held */
2062 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
2063 GDBusMessage *message,
2064 GDBusSendMessageFlags flags,
2065 volatile guint32 *out_serial,
2070 guint32 serial_to_use;
2073 CONNECTION_ENSURE_LOCK (connection);
2075 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2076 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
2078 /* TODO: check all necessary headers are present */
2083 if (out_serial != NULL)
2086 /* If we're in initable_init(), don't check for being initialized, to avoid
2087 * chicken-and-egg problems. initable_init() is responsible for setting up
2088 * our prerequisites (mainly connection->worker), and only calling us
2089 * from its own thread (so no memory barrier is needed).
2091 if (!check_unclosed (connection,
2092 (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
2096 blob = g_dbus_message_to_blob (message,
2098 connection->capabilities,
2103 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
2104 serial_to_use = g_dbus_message_get_serial (message);
2106 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
2111 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
2114 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
2117 g_assert_not_reached ();
2122 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
2123 blob_size, serial_to_use, connection);
2124 g_printerr ("----\n");
2125 hexdump (blob, blob_size);
2126 g_printerr ("----\n");
2129 /* TODO: use connection->auth to encode the blob */
2131 if (out_serial != NULL)
2132 *out_serial = serial_to_use;
2134 /* store used serial for the current thread */
2135 /* TODO: watch the thread disposal and remove associated record
2137 * - see https://bugzilla.gnome.org/show_bug.cgi?id=676825#c7
2139 g_hash_table_replace (connection->map_thread_to_last_serial,
2141 GUINT_TO_POINTER (serial_to_use));
2143 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
2144 g_dbus_message_set_serial (message, serial_to_use);
2146 g_dbus_message_lock (message);
2147 _g_dbus_worker_send_message (connection->worker,
2151 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
2162 * g_dbus_connection_send_message:
2163 * @connection: a #GDBusConnection
2164 * @message: a #GDBusMessage
2165 * @flags: flags affecting how the message is sent
2166 * @out_serial: (out) (allow-none): return location for serial number assigned
2167 * to @message when sending it or %NULL
2168 * @error: Return location for error or %NULL
2170 * Asynchronously sends @message to the peer represented by @connection.
2172 * Unless @flags contain the
2173 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2174 * will be assigned by @connection and set on @message via
2175 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2176 * serial number used will be written to this location prior to
2177 * submitting the message to the underlying transport.
2179 * If @connection is closed then the operation will fail with
2180 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
2181 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2183 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2184 * for an example of how to use this low-level API to send and receive
2185 * UNIX file descriptors.
2187 * Note that @message must be unlocked, unless @flags contain the
2188 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2190 * Returns: %TRUE if the message was well-formed and queued for
2191 * transmission, %FALSE if @error is set
2196 g_dbus_connection_send_message (GDBusConnection *connection,
2197 GDBusMessage *message,
2198 GDBusSendMessageFlags flags,
2199 volatile guint32 *out_serial,
2204 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2205 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
2206 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
2207 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2209 CONNECTION_LOCK (connection);
2210 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
2211 CONNECTION_UNLOCK (connection);
2215 /* ---------------------------------------------------------------------------------------------------- */
2219 volatile gint ref_count;
2220 GDBusConnection *connection;
2222 GSimpleAsyncResult *simple;
2224 GMainContext *main_context;
2226 GCancellable *cancellable;
2228 gulong cancellable_handler_id;
2230 GSource *timeout_source;
2235 /* Can be called from any thread with or without lock held */
2236 static SendMessageData *
2237 send_message_data_ref (SendMessageData *data)
2239 g_atomic_int_inc (&data->ref_count);
2243 /* Can be called from any thread with or without lock held */
2245 send_message_data_unref (SendMessageData *data)
2247 if (g_atomic_int_dec_and_test (&data->ref_count))
2249 g_assert (data->timeout_source == NULL);
2250 g_assert (data->simple == NULL);
2251 g_assert (data->cancellable_handler_id == 0);
2252 g_object_unref (data->connection);
2253 if (data->cancellable != NULL)
2254 g_object_unref (data->cancellable);
2255 g_main_context_unref (data->main_context);
2260 /* ---------------------------------------------------------------------------------------------------- */
2262 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
2264 send_message_with_reply_deliver (SendMessageData *data, gboolean remove)
2266 CONNECTION_ENSURE_LOCK (data->connection);
2268 g_assert (!data->delivered);
2270 data->delivered = TRUE;
2272 g_simple_async_result_complete_in_idle (data->simple);
2273 g_object_unref (data->simple);
2274 data->simple = NULL;
2276 if (data->timeout_source != NULL)
2278 g_source_destroy (data->timeout_source);
2279 data->timeout_source = NULL;
2281 if (data->cancellable_handler_id > 0)
2283 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
2284 data->cancellable_handler_id = 0;
2289 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
2290 GUINT_TO_POINTER (data->serial)));
2293 send_message_data_unref (data);
2296 /* ---------------------------------------------------------------------------------------------------- */
2298 /* Can be called from any thread with lock held */
2300 send_message_data_deliver_reply_unlocked (SendMessageData *data,
2301 GDBusMessage *reply)
2303 if (data->delivered)
2306 g_simple_async_result_set_op_res_gpointer (data->simple,
2307 g_object_ref (reply),
2310 send_message_with_reply_deliver (data, TRUE);
2316 /* ---------------------------------------------------------------------------------------------------- */
2318 /* Called from a user thread, lock is not held */
2320 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
2322 SendMessageData *data = user_data;
2324 CONNECTION_LOCK (data->connection);
2325 if (data->delivered)
2328 g_simple_async_result_set_error (data->simple,
2330 G_IO_ERROR_CANCELLED,
2331 _("Operation was cancelled"));
2333 send_message_with_reply_deliver (data, TRUE);
2336 CONNECTION_UNLOCK (data->connection);
2340 /* Can be called from any thread with or without lock held */
2342 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
2345 SendMessageData *data = user_data;
2346 GSource *idle_source;
2348 /* postpone cancellation to idle handler since we may be called directly
2349 * via g_cancellable_connect() (e.g. holding lock)
2351 idle_source = g_idle_source_new ();
2352 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
2353 g_source_set_callback (idle_source,
2354 send_message_with_reply_cancelled_idle_cb,
2355 send_message_data_ref (data),
2356 (GDestroyNotify) send_message_data_unref);
2357 g_source_set_name (idle_source, "[gio] send_message_with_reply_cancelled_idle_cb");
2358 g_source_attach (idle_source, data->main_context);
2359 g_source_unref (idle_source);
2362 /* ---------------------------------------------------------------------------------------------------- */
2364 /* Called from a user thread, lock is not held */
2366 send_message_with_reply_timeout_cb (gpointer user_data)
2368 SendMessageData *data = user_data;
2370 CONNECTION_LOCK (data->connection);
2371 if (data->delivered)
2374 g_simple_async_result_set_error (data->simple,
2376 G_IO_ERROR_TIMED_OUT,
2377 _("Timeout was reached"));
2379 send_message_with_reply_deliver (data, TRUE);
2382 CONNECTION_UNLOCK (data->connection);
2387 /* ---------------------------------------------------------------------------------------------------- */
2389 /* Called from a user thread, connection's lock is held */
2391 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
2392 GDBusMessage *message,
2393 GDBusSendMessageFlags flags,
2395 volatile guint32 *out_serial,
2396 GCancellable *cancellable,
2397 GAsyncReadyCallback callback,
2400 GSimpleAsyncResult *simple;
2401 SendMessageData *data;
2403 volatile guint32 serial;
2407 if (out_serial == NULL)
2408 out_serial = &serial;
2410 if (timeout_msec == -1)
2411 timeout_msec = 25 * 1000;
2413 simple = g_simple_async_result_new (G_OBJECT (connection),
2416 g_dbus_connection_send_message_with_reply);
2417 g_simple_async_result_set_check_cancellable (simple, cancellable);
2419 if (g_cancellable_is_cancelled (cancellable))
2421 g_simple_async_result_set_error (simple,
2423 G_IO_ERROR_CANCELLED,
2424 _("Operation was cancelled"));
2425 g_simple_async_result_complete_in_idle (simple);
2426 g_object_unref (simple);
2431 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
2433 g_simple_async_result_take_error (simple, error);
2434 g_simple_async_result_complete_in_idle (simple);
2435 g_object_unref (simple);
2439 data = g_new0 (SendMessageData, 1);
2440 data->ref_count = 1;
2441 data->connection = g_object_ref (connection);
2442 data->simple = simple;
2443 data->serial = *out_serial;
2444 data->main_context = g_main_context_ref_thread_default ();
2446 if (cancellable != NULL)
2448 data->cancellable = g_object_ref (cancellable);
2449 data->cancellable_handler_id = g_cancellable_connect (cancellable,
2450 G_CALLBACK (send_message_with_reply_cancelled_cb),
2451 send_message_data_ref (data),
2452 (GDestroyNotify) send_message_data_unref);
2455 if (timeout_msec != G_MAXINT)
2457 data->timeout_source = g_timeout_source_new (timeout_msec);
2458 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
2459 g_source_set_callback (data->timeout_source,
2460 send_message_with_reply_timeout_cb,
2461 send_message_data_ref (data),
2462 (GDestroyNotify) send_message_data_unref);
2463 g_source_attach (data->timeout_source, data->main_context);
2464 g_source_unref (data->timeout_source);
2467 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
2468 GUINT_TO_POINTER (*out_serial),
2476 * g_dbus_connection_send_message_with_reply:
2477 * @connection: a #GDBusConnection
2478 * @message: a #GDBusMessage
2479 * @flags: flags affecting how the message is sent
2480 * @timeout_msec: the timeout in milliseconds, -1 to use the default
2481 * timeout or %G_MAXINT for no timeout
2482 * @out_serial: (out) (allow-none): return location for serial number assigned
2483 * to @message when sending it or %NULL
2484 * @cancellable: (allow-none): a #GCancellable or %NULL
2485 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request
2486 * is satisfied or %NULL if you don't care about the result
2487 * @user_data: The data to pass to @callback
2489 * Asynchronously sends @message to the peer represented by @connection.
2491 * Unless @flags contain the
2492 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2493 * will be assigned by @connection and set on @message via
2494 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2495 * serial number used will be written to this location prior to
2496 * submitting the message to the underlying transport.
2498 * If @connection is closed then the operation will fail with
2499 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2500 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2501 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2503 * This is an asynchronous method. When the operation is finished, @callback
2504 * will be invoked in the
2505 * [thread-default main context][g-main-context-push-thread-default]
2506 * of the thread you are calling this method from. You can then call
2507 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
2508 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
2510 * Note that @message must be unlocked, unless @flags contain the
2511 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2513 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2514 * for an example of how to use this low-level API to send and receive
2515 * UNIX file descriptors.
2520 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
2521 GDBusMessage *message,
2522 GDBusSendMessageFlags flags,
2524 volatile guint32 *out_serial,
2525 GCancellable *cancellable,
2526 GAsyncReadyCallback callback,
2529 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2530 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2531 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2532 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2534 CONNECTION_LOCK (connection);
2535 g_dbus_connection_send_message_with_reply_unlocked (connection,
2543 CONNECTION_UNLOCK (connection);
2547 * g_dbus_connection_send_message_with_reply_finish:
2548 * @connection: a #GDBusConnection
2549 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
2550 * g_dbus_connection_send_message_with_reply()
2551 * @error: teturn location for error or %NULL
2553 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2555 * Note that @error is only set if a local in-process error
2556 * occurred. That is to say that the returned #GDBusMessage object may
2557 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2558 * g_dbus_message_to_gerror() to transcode this to a #GError.
2560 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2561 * for an example of how to use this low-level API to send and receive
2562 * UNIX file descriptors.
2564 * Returns: (transfer full): a locked #GDBusMessage or %NULL if @error is set
2569 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2573 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2574 GDBusMessage *reply;
2576 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2577 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2581 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
2583 if (g_simple_async_result_propagate_error (simple, error))
2586 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
2592 /* ---------------------------------------------------------------------------------------------------- */
2597 GMainContext *context;
2599 } SendMessageSyncData;
2601 /* Called from a user thread, lock is not held */
2603 send_message_with_reply_sync_cb (GDBusConnection *connection,
2607 SendMessageSyncData *data = user_data;
2608 data->res = g_object_ref (res);
2609 g_main_loop_quit (data->loop);
2613 * g_dbus_connection_send_message_with_reply_sync:
2614 * @connection: a #GDBusConnection
2615 * @message: a #GDBusMessage
2616 * @flags: flags affecting how the message is sent.
2617 * @timeout_msec: the timeout in milliseconds, -1 to use the default
2618 * timeout or %G_MAXINT for no timeout
2619 * @out_serial: (out) (allow-none): return location for serial number
2620 * assigned to @message when sending it or %NULL
2621 * @cancellable: (allow-none): a #GCancellable or %NULL
2622 * @error: return location for error or %NULL
2624 * Synchronously sends @message to the peer represented by @connection
2625 * and blocks the calling thread until a reply is received or the
2626 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2627 * for the asynchronous version of this method.
2629 * Unless @flags contain the
2630 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2631 * will be assigned by @connection and set on @message via
2632 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2633 * serial number used will be written to this location prior to
2634 * submitting the message to the underlying transport.
2636 * If @connection is closed then the operation will fail with
2637 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2638 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2639 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2641 * Note that @error is only set if a local in-process error
2642 * occurred. That is to say that the returned #GDBusMessage object may
2643 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2644 * g_dbus_message_to_gerror() to transcode this to a #GError.
2646 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2647 * for an example of how to use this low-level API to send and receive
2648 * UNIX file descriptors.
2650 * Note that @message must be unlocked, unless @flags contain the
2651 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2653 * Returns: (transfer full): a locked #GDBusMessage that is the reply
2654 * to @message or %NULL if @error is set
2659 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2660 GDBusMessage *message,
2661 GDBusSendMessageFlags flags,
2663 volatile guint32 *out_serial,
2664 GCancellable *cancellable,
2667 SendMessageSyncData *data;
2668 GDBusMessage *reply;
2670 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2671 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2672 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2673 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2674 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2676 data = g_new0 (SendMessageSyncData, 1);
2677 data->context = g_main_context_new ();
2678 data->loop = g_main_loop_new (data->context, FALSE);
2680 g_main_context_push_thread_default (data->context);
2682 g_dbus_connection_send_message_with_reply (connection,
2688 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2690 g_main_loop_run (data->loop);
2691 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2695 g_main_context_pop_thread_default (data->context);
2697 g_main_context_unref (data->context);
2698 g_main_loop_unref (data->loop);
2699 g_object_unref (data->res);
2705 /* ---------------------------------------------------------------------------------------------------- */
2709 GDBusMessageFilterFunction func;
2716 GDBusMessageFilterFunction filter_function;
2718 GDestroyNotify user_data_free_func;
2721 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2723 on_worker_message_received (GDBusWorker *worker,
2724 GDBusMessage *message,
2727 GDBusConnection *connection;
2728 FilterCallback *filters;
2733 G_LOCK (message_bus_lock);
2734 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2737 G_UNLOCK (message_bus_lock);
2740 connection = G_DBUS_CONNECTION (user_data);
2741 g_object_ref (connection);
2742 G_UNLOCK (message_bus_lock);
2744 //g_debug ("in on_worker_message_received");
2746 g_object_ref (message);
2747 g_dbus_message_lock (message);
2749 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2751 /* First collect the set of callback functions */
2752 CONNECTION_LOCK (connection);
2753 num_filters = connection->filters->len;
2754 filters = g_new0 (FilterCallback, num_filters);
2755 for (n = 0; n < num_filters; n++)
2757 FilterData *data = connection->filters->pdata[n];
2758 filters[n].func = data->filter_function;
2759 filters[n].user_data = data->user_data;
2761 CONNECTION_UNLOCK (connection);
2763 /* then call the filters in order (without holding the lock) */
2764 for (n = 0; n < num_filters; n++)
2766 message = filters[n].func (connection,
2769 filters[n].user_data);
2770 if (message == NULL)
2772 g_dbus_message_lock (message);
2775 /* Standard dispatch unless the filter ate the message - no need to
2776 * do anything if the message was altered
2778 if (message != NULL)
2780 GDBusMessageType message_type;
2782 message_type = g_dbus_message_get_message_type (message);
2783 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2785 guint32 reply_serial;
2786 SendMessageData *send_message_data;
2788 reply_serial = g_dbus_message_get_reply_serial (message);
2789 CONNECTION_LOCK (connection);
2790 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2791 GUINT_TO_POINTER (reply_serial));
2792 if (send_message_data != NULL)
2794 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2795 send_message_data_deliver_reply_unlocked (send_message_data, message);
2799 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2801 CONNECTION_UNLOCK (connection);
2803 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2805 CONNECTION_LOCK (connection);
2806 distribute_signals (connection, message);
2807 CONNECTION_UNLOCK (connection);
2809 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2811 CONNECTION_LOCK (connection);
2812 distribute_method_call (connection, message);
2813 CONNECTION_UNLOCK (connection);
2817 if (message != NULL)
2818 g_object_unref (message);
2819 g_object_unref (connection);
2823 /* Called in GDBusWorker's thread, lock is not held */
2824 static GDBusMessage *
2825 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2826 GDBusMessage *message,
2829 GDBusConnection *connection;
2830 FilterCallback *filters;
2835 G_LOCK (message_bus_lock);
2836 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2839 G_UNLOCK (message_bus_lock);
2842 connection = G_DBUS_CONNECTION (user_data);
2843 g_object_ref (connection);
2844 G_UNLOCK (message_bus_lock);
2846 //g_debug ("in on_worker_message_about_to_be_sent");
2848 /* First collect the set of callback functions */
2849 CONNECTION_LOCK (connection);
2850 num_filters = connection->filters->len;
2851 filters = g_new0 (FilterCallback, num_filters);
2852 for (n = 0; n < num_filters; n++)
2854 FilterData *data = connection->filters->pdata[n];
2855 filters[n].func = data->filter_function;
2856 filters[n].user_data = data->user_data;
2858 CONNECTION_UNLOCK (connection);
2860 /* then call the filters in order (without holding the lock) */
2861 for (n = 0; n < num_filters; n++)
2863 g_dbus_message_lock (message);
2864 message = filters[n].func (connection,
2867 filters[n].user_data);
2868 if (message == NULL)
2872 g_object_unref (connection);
2878 /* called with connection lock held, in GDBusWorker thread */
2880 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2882 SendMessageData *data = value;
2884 if (data->delivered)
2887 g_simple_async_result_set_error (data->simple,
2890 _("The connection is closed"));
2892 /* Ask send_message_with_reply_deliver not to remove the element from the
2893 * hash table - we're in the middle of a foreach; that would be unsafe.
2894 * Instead, return TRUE from this function so that it gets removed safely.
2896 send_message_with_reply_deliver (data, FALSE);
2900 /* Called in GDBusWorker's thread - we must not block - without lock held */
2902 on_worker_closed (GDBusWorker *worker,
2903 gboolean remote_peer_vanished,
2907 GDBusConnection *connection;
2909 guint old_atomic_flags;
2911 G_LOCK (message_bus_lock);
2912 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2915 G_UNLOCK (message_bus_lock);
2918 connection = G_DBUS_CONNECTION (user_data);
2919 g_object_ref (connection);
2920 G_UNLOCK (message_bus_lock);
2922 //g_debug ("in on_worker_closed: %s", error->message);
2924 CONNECTION_LOCK (connection);
2925 /* Even though this is atomic, we do it inside the lock to avoid breaking
2926 * assumptions in remove_match_rule(). We'd need the lock in a moment
2927 * anyway, so, no loss.
2929 old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
2931 if (!(old_atomic_flags & FLAG_CLOSED))
2933 g_hash_table_foreach_remove (connection->map_method_serial_to_send_message_data, cancel_method_on_close, NULL);
2934 schedule_closed_unlocked (connection, remote_peer_vanished, error);
2936 CONNECTION_UNLOCK (connection);
2938 g_object_unref (connection);
2941 /* ---------------------------------------------------------------------------------------------------- */
2943 /* Determines the biggest set of capabilities we can support on this
2946 * Called with the init_lock held.
2948 static GDBusCapabilityFlags
2949 get_offered_capabilities_max (GDBusConnection *connection)
2951 GDBusCapabilityFlags ret;
2952 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2954 if (G_IS_UNIX_CONNECTION (connection->stream))
2955 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2960 /* Called in a user thread, lock is not held */
2962 initable_init (GInitable *initable,
2963 GCancellable *cancellable,
2966 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2969 /* This method needs to be idempotent to work with the singleton
2970 * pattern. See the docs for g_initable_init(). We implement this by
2973 * Unfortunately we can't use the main lock since the on_worker_*()
2974 * callbacks above needs the lock during initialization (for message
2975 * bus connections we do a synchronous Hello() call on the bus).
2977 g_mutex_lock (&connection->init_lock);
2981 /* Make this a no-op if we're already initialized (successfully or
2984 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
2986 ret = (connection->initialization_error == NULL);
2990 /* Because of init_lock, we can't get here twice in different threads */
2991 g_assert (connection->initialization_error == NULL);
2993 /* The user can pass multiple (but mutally exclusive) construct
2996 * - stream (of type GIOStream)
2997 * - address (of type gchar*)
2999 * At the end of the day we end up with a non-NULL GIOStream
3000 * object in connection->stream.
3002 if (connection->address != NULL)
3004 g_assert (connection->stream == NULL);
3006 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
3007 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
3009 g_set_error_literal (&connection->initialization_error,
3011 G_IO_ERROR_INVALID_ARGUMENT,
3012 _("Unsupported flags encountered when constructing a client-side connection"));
3016 connection->stream = g_dbus_address_get_stream_sync (connection->address,
3017 NULL, /* TODO: out_guid */
3019 &connection->initialization_error);
3020 if (connection->stream == NULL)
3023 else if (connection->stream != NULL)
3029 g_assert_not_reached ();
3032 /* Authenticate the connection */
3033 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
3035 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
3036 g_assert (connection->guid != NULL);
3037 connection->auth = _g_dbus_auth_new (connection->stream);
3038 if (!_g_dbus_auth_run_server (connection->auth,
3039 connection->authentication_observer,
3041 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
3042 get_offered_capabilities_max (connection),
3043 &connection->capabilities,
3044 &connection->credentials,
3046 &connection->initialization_error))
3049 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
3051 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
3052 g_assert (connection->guid == NULL);
3053 connection->auth = _g_dbus_auth_new (connection->stream);
3054 connection->guid = _g_dbus_auth_run_client (connection->auth,
3055 connection->authentication_observer,
3056 get_offered_capabilities_max (connection),
3057 &connection->capabilities,
3059 &connection->initialization_error);
3060 if (connection->guid == NULL)
3064 if (connection->authentication_observer != NULL)
3066 g_object_unref (connection->authentication_observer);
3067 connection->authentication_observer = NULL;
3070 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
3072 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
3075 /* We want all IO operations to be non-blocking since they happen in
3076 * the worker thread which is shared by _all_ connections.
3078 if (G_IS_SOCKET_CONNECTION (connection->stream))
3080 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
3084 G_LOCK (message_bus_lock);
3085 if (alive_connections == NULL)
3086 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
3087 g_hash_table_insert (alive_connections, connection, connection);
3088 G_UNLOCK (message_bus_lock);
3090 connection->worker = _g_dbus_worker_new (connection->stream,
3091 connection->capabilities,
3092 ((connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) != 0),
3093 on_worker_message_received,
3094 on_worker_message_about_to_be_sent,
3098 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
3099 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3101 GVariant *hello_result;
3103 /* we could lift this restriction by adding code in gdbusprivate.c */
3104 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
3106 g_set_error_literal (&connection->initialization_error,
3109 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
3113 hello_result = g_dbus_connection_call_sync (connection,
3114 "org.freedesktop.DBus", /* name */
3115 "/org/freedesktop/DBus", /* path */
3116 "org.freedesktop.DBus", /* interface */
3118 NULL, /* parameters */
3119 G_VARIANT_TYPE ("(s)"),
3120 CALL_FLAGS_INITIALIZING,
3122 NULL, /* TODO: cancellable */
3123 &connection->initialization_error);
3124 if (hello_result == NULL)
3127 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
3128 g_variant_unref (hello_result);
3129 //g_debug ("unique name is '%s'", connection->bus_unique_name);
3136 g_assert (connection->initialization_error != NULL);
3137 g_propagate_error (error, g_error_copy (connection->initialization_error));
3140 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
3141 g_mutex_unlock (&connection->init_lock);
3147 initable_iface_init (GInitableIface *initable_iface)
3149 initable_iface->init = initable_init;
3152 /* ---------------------------------------------------------------------------------------------------- */
3155 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
3160 /* ---------------------------------------------------------------------------------------------------- */
3163 * g_dbus_connection_new:
3164 * @stream: a #GIOStream
3165 * @guid: (allow-none): the GUID to use if a authenticating as a server or %NULL
3166 * @flags: flags describing how to make the connection
3167 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3168 * @cancellable: (allow-none): a #GCancellable or %NULL
3169 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
3170 * @user_data: the data to pass to @callback
3172 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
3173 * with the end represented by @stream.
3175 * If @stream is a #GSocketConnection, then the corresponding #GSocket
3176 * will be put into non-blocking mode.
3178 * The D-Bus connection will interact with @stream from a worker thread.
3179 * As a result, the caller should not interact with @stream after this
3180 * method has been called, except by calling g_object_unref() on it.
3182 * If @observer is not %NULL it may be used to control the
3183 * authentication process.
3185 * When the operation is finished, @callback will be invoked. You can
3186 * then call g_dbus_connection_new_finish() to get the result of the
3189 * This is a asynchronous failable constructor. See
3190 * g_dbus_connection_new_sync() for the synchronous
3196 g_dbus_connection_new (GIOStream *stream,
3198 GDBusConnectionFlags flags,
3199 GDBusAuthObserver *observer,
3200 GCancellable *cancellable,
3201 GAsyncReadyCallback callback,
3204 g_return_if_fail (G_IS_IO_STREAM (stream));
3205 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
3213 "authentication-observer", observer,
3218 * g_dbus_connection_new_finish:
3219 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback
3220 * passed to g_dbus_connection_new().
3221 * @error: return location for error or %NULL
3223 * Finishes an operation started with g_dbus_connection_new().
3225 * Returns: a #GDBusConnection or %NULL if @error is set. Free
3226 * with g_object_unref().
3231 g_dbus_connection_new_finish (GAsyncResult *res,
3235 GObject *source_object;
3237 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
3238 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3240 source_object = g_async_result_get_source_object (res);
3241 g_assert (source_object != NULL);
3242 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
3245 g_object_unref (source_object);
3247 return G_DBUS_CONNECTION (object);
3253 * g_dbus_connection_new_sync:
3254 * @stream: a #GIOStream
3255 * @guid: (allow-none): the GUID to use if a authenticating as a server or %NULL
3256 * @flags: flags describing how to make the connection
3257 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3258 * @cancellable: (allow-none): a #GCancellable or %NULL
3259 * @error: return location for error or %NULL
3261 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
3262 * with the end represented by @stream.
3264 * If @stream is a #GSocketConnection, then the corresponding #GSocket
3265 * will be put into non-blocking mode.
3267 * The D-Bus connection will interact with @stream from a worker thread.
3268 * As a result, the caller should not interact with @stream after this
3269 * method has been called, except by calling g_object_unref() on it.
3271 * If @observer is not %NULL it may be used to control the
3272 * authentication process.
3274 * This is a synchronous failable constructor. See
3275 * g_dbus_connection_new() for the asynchronous version.
3277 * Returns: a #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
3282 g_dbus_connection_new_sync (GIOStream *stream,
3284 GDBusConnectionFlags flags,
3285 GDBusAuthObserver *observer,
3286 GCancellable *cancellable,
3289 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
3290 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3291 return g_initable_new (G_TYPE_DBUS_CONNECTION,
3297 "authentication-observer", observer,
3301 /* ---------------------------------------------------------------------------------------------------- */
3304 * g_dbus_connection_new_for_address:
3305 * @address: a D-Bus address
3306 * @flags: flags describing how to make the connection
3307 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3308 * @cancellable: (allow-none): a #GCancellable or %NULL
3309 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
3310 * @user_data: the data to pass to @callback
3312 * Asynchronously connects and sets up a D-Bus client connection for
3313 * exchanging D-Bus messages with an endpoint specified by @address
3314 * which must be in the D-Bus address format.
3316 * This constructor can only be used to initiate client-side
3317 * connections - use g_dbus_connection_new() if you need to act as the
3318 * server. In particular, @flags cannot contain the
3319 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
3320 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
3322 * When the operation is finished, @callback will be invoked. You can
3323 * then call g_dbus_connection_new_finish() to get the result of the
3326 * If @observer is not %NULL it may be used to control the
3327 * authentication process.
3329 * This is a asynchronous failable constructor. See
3330 * g_dbus_connection_new_for_address_sync() for the synchronous
3336 g_dbus_connection_new_for_address (const gchar *address,
3337 GDBusConnectionFlags flags,
3338 GDBusAuthObserver *observer,
3339 GCancellable *cancellable,
3340 GAsyncReadyCallback callback,
3343 g_return_if_fail (address != NULL);
3344 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
3351 "authentication-observer", observer,
3356 * g_dbus_connection_new_for_address_finish:
3357 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
3358 * to g_dbus_connection_new()
3359 * @error: return location for error or %NULL
3361 * Finishes an operation started with g_dbus_connection_new_for_address().
3363 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
3369 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
3373 GObject *source_object;
3375 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
3376 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3378 source_object = g_async_result_get_source_object (res);
3379 g_assert (source_object != NULL);
3380 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
3383 g_object_unref (source_object);
3385 return G_DBUS_CONNECTION (object);
3391 * g_dbus_connection_new_for_address_sync:
3392 * @address: a D-Bus address
3393 * @flags: flags describing how to make the connection
3394 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3395 * @cancellable: (allow-none): a #GCancellable or %NULL
3396 * @error: return location for error or %NULL
3398 * Synchronously connects and sets up a D-Bus client connection for
3399 * exchanging D-Bus messages with an endpoint specified by @address
3400 * which must be in the D-Bus address format.
3402 * This constructor can only be used to initiate client-side
3403 * connections - use g_dbus_connection_new_sync() if you need to act
3404 * as the server. In particular, @flags cannot contain the
3405 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
3406 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
3408 * This is a synchronous failable constructor. See
3409 * g_dbus_connection_new_for_address() for the asynchronous version.
3411 * If @observer is not %NULL it may be used to control the
3412 * authentication process.
3414 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
3420 g_dbus_connection_new_for_address_sync (const gchar *address,
3421 GDBusConnectionFlags flags,
3422 GDBusAuthObserver *observer,
3423 GCancellable *cancellable,
3426 g_return_val_if_fail (address != NULL, NULL);
3427 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3428 return g_initable_new (G_TYPE_DBUS_CONNECTION,
3433 "authentication-observer", observer,
3437 /* ---------------------------------------------------------------------------------------------------- */
3440 * g_dbus_connection_set_exit_on_close:
3441 * @connection: a #GDBusConnection
3442 * @exit_on_close: whether the process should be terminated
3443 * when @connection is closed by the remote peer
3445 * Sets whether the process should be terminated when @connection is
3446 * closed by the remote peer. See #GDBusConnection:exit-on-close for
3449 * Note that this function should be used with care. Most modern UNIX
3450 * desktops tie the notion of a user session the session bus, and expect
3451 * all of a users applications to quit when their bus connection goes away.
3452 * If you are setting @exit_on_close to %FALSE for the shared session
3453 * bus connection, you should make sure that your application exits
3454 * when the user session ends.
3459 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
3460 gboolean exit_on_close)
3462 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3465 g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
3467 g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
3472 * g_dbus_connection_get_exit_on_close:
3473 * @connection: a #GDBusConnection
3475 * Gets whether the process is terminated when @connection is
3476 * closed by the remote peer. See
3477 * #GDBusConnection:exit-on-close for more details.
3479 * Returns: whether the process is terminated when @connection is
3480 * closed by the remote peer
3485 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
3487 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3489 if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
3496 * g_dbus_connection_get_guid:
3497 * @connection: a #GDBusConnection
3499 * The GUID of the peer performing the role of server when
3500 * authenticating. See #GDBusConnection:guid for more details.
3502 * Returns: The GUID. Do not free this string, it is owned by
3508 g_dbus_connection_get_guid (GDBusConnection *connection)
3510 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3511 return connection->guid;
3515 * g_dbus_connection_get_unique_name:
3516 * @connection: a #GDBusConnection
3518 * Gets the unique name of @connection as assigned by the message
3519 * bus. This can also be used to figure out if @connection is a
3520 * message bus connection.
3522 * Returns: the unique name or %NULL if @connection is not a message
3523 * bus connection. Do not free this string, it is owned by
3529 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3531 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3533 /* do not use g_return_val_if_fail(), we want the memory barrier */
3534 if (!check_initialized (connection))
3537 return connection->bus_unique_name;
3541 * g_dbus_connection_get_peer_credentials:
3542 * @connection: a #GDBusConnection
3544 * Gets the credentials of the authenticated peer. This will always
3545 * return %NULL unless @connection acted as a server
3546 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3547 * when set up and the client passed credentials as part of the
3548 * authentication process.
3550 * In a message bus setup, the message bus is always the server and
3551 * each application is a client. So this method will always return
3552 * %NULL for message bus clients.
3554 * Returns: (transfer none): a #GCredentials or %NULL if not available.
3555 * Do not free this object, it is owned by @connection.
3560 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3562 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3564 /* do not use g_return_val_if_fail(), we want the memory barrier */
3565 if (!check_initialized (connection))
3568 return connection->credentials;
3571 /* ---------------------------------------------------------------------------------------------------- */
3573 static guint _global_filter_id = 1;
3576 * g_dbus_connection_add_filter:
3577 * @connection: a #GDBusConnection
3578 * @filter_function: a filter function
3579 * @user_data: user data to pass to @filter_function
3580 * @user_data_free_func: function to free @user_data with when filter
3581 * is removed or %NULL
3583 * Adds a message filter. Filters are handlers that are run on all
3584 * incoming and outgoing messages, prior to standard dispatch. Filters
3585 * are run in the order that they were added. The same handler can be
3586 * added as a filter more than once, in which case it will be run more
3587 * than once. Filters added during a filter callback won't be run on
3588 * the message being processed. Filter functions are allowed to modify
3589 * and even drop messages.
3591 * Note that filters are run in a dedicated message handling thread so
3592 * they can't block and, generally, can't do anything but signal a
3593 * worker thread. Also note that filters are rarely needed - use API
3594 * such as g_dbus_connection_send_message_with_reply(),
3595 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3597 * If a filter consumes an incoming message the message is not
3598 * dispatched anywhere else - not even the standard dispatch machinery
3599 * (that API such as g_dbus_connection_signal_subscribe() and
3600 * g_dbus_connection_send_message_with_reply() relies on) will see the
3601 * message. Similary, if a filter consumes an outgoing message, the
3602 * message will not be sent to the other peer.
3604 * Returns: a filter identifier that can be used with
3605 * g_dbus_connection_remove_filter()
3610 g_dbus_connection_add_filter (GDBusConnection *connection,
3611 GDBusMessageFilterFunction filter_function,
3613 GDestroyNotify user_data_free_func)
3617 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3618 g_return_val_if_fail (filter_function != NULL, 0);
3619 g_return_val_if_fail (check_initialized (connection), 0);
3621 CONNECTION_LOCK (connection);
3622 data = g_new0 (FilterData, 1);
3623 data->id = _global_filter_id++; /* TODO: overflow etc. */
3624 data->filter_function = filter_function;
3625 data->user_data = user_data;
3626 data->user_data_free_func = user_data_free_func;
3627 g_ptr_array_add (connection->filters, data);
3628 CONNECTION_UNLOCK (connection);
3633 /* only called from finalize(), removes all filters */
3635 purge_all_filters (GDBusConnection *connection)
3638 for (n = 0; n < connection->filters->len; n++)
3640 FilterData *data = connection->filters->pdata[n];
3641 if (data->user_data_free_func != NULL)
3642 data->user_data_free_func (data->user_data);
3648 * g_dbus_connection_remove_filter:
3649 * @connection: a #GDBusConnection
3650 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3657 g_dbus_connection_remove_filter (GDBusConnection *connection,
3661 FilterData *to_destroy;
3663 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3664 g_return_if_fail (check_initialized (connection));
3666 CONNECTION_LOCK (connection);
3668 for (n = 0; n < connection->filters->len; n++)
3670 FilterData *data = connection->filters->pdata[n];
3671 if (data->id == filter_id)
3673 g_ptr_array_remove_index (connection->filters, n);
3678 CONNECTION_UNLOCK (connection);
3680 /* do free without holding lock */
3681 if (to_destroy != NULL)
3683 if (to_destroy->user_data_free_func != NULL)
3684 to_destroy->user_data_free_func (to_destroy->user_data);
3685 g_free (to_destroy);
3689 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3693 /* ---------------------------------------------------------------------------------------------------- */
3699 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3700 gchar *interface_name;
3704 GDBusSignalFlags flags;
3705 GArray *subscribers;
3710 GDBusSignalCallback callback;
3712 GDestroyNotify user_data_free_func;
3714 GMainContext *context;
3718 signal_data_free (SignalData *signal_data)
3720 g_free (signal_data->rule);
3721 g_free (signal_data->sender);
3722 g_free (signal_data->sender_unique_name);
3723 g_free (signal_data->interface_name);
3724 g_free (signal_data->member);
3725 g_free (signal_data->object_path);
3726 g_free (signal_data->arg0);
3727 g_array_free (signal_data->subscribers, TRUE);
3728 g_free (signal_data);
3732 args_to_rule (const gchar *sender,
3733 const gchar *interface_name,
3734 const gchar *member,
3735 const gchar *object_path,
3737 GDBusSignalFlags flags)
3741 rule = g_string_new ("type='signal'");
3742 if (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE)
3743 g_string_prepend_c (rule, '-');
3745 g_string_append_printf (rule, ",sender='%s'", sender);
3746 if (interface_name != NULL)
3747 g_string_append_printf (rule, ",interface='%s'", interface_name);
3749 g_string_append_printf (rule, ",member='%s'", member);
3750 if (object_path != NULL)
3751 g_string_append_printf (rule, ",path='%s'", object_path);
3755 if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3756 g_string_append_printf (rule, ",arg0path='%s'", arg0);
3757 else if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3758 g_string_append_printf (rule, ",arg0namespace='%s'", arg0);
3760 g_string_append_printf (rule, ",arg0='%s'", arg0);
3763 return g_string_free (rule, FALSE);
3766 static guint _global_subscriber_id = 1;
3767 static guint _global_registration_id = 1;
3768 static guint _global_subtree_registration_id = 1;
3770 /* ---------------------------------------------------------------------------------------------------- */
3772 /* Called in a user thread, lock is held */
3774 add_match_rule (GDBusConnection *connection,
3775 const gchar *match_rule)
3778 GDBusMessage *message;
3780 if (match_rule[0] == '-')
3783 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3784 "/org/freedesktop/DBus", /* path */
3785 "org.freedesktop.DBus", /* interface */
3787 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3789 if (!g_dbus_connection_send_message_unlocked (connection,
3791 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3795 g_critical ("Error while sending AddMatch() message: %s", error->message);
3796 g_error_free (error);
3798 g_object_unref (message);
3801 /* ---------------------------------------------------------------------------------------------------- */
3803 /* Called in a user thread, lock is held */
3805 remove_match_rule (GDBusConnection *connection,
3806 const gchar *match_rule)
3809 GDBusMessage *message;
3811 if (match_rule[0] == '-')
3814 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3815 "/org/freedesktop/DBus", /* path */
3816 "org.freedesktop.DBus", /* interface */
3818 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3821 if (!g_dbus_connection_send_message_unlocked (connection,
3823 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3827 /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
3828 * critical; but we're holding the lock, and our caller checked whether
3829 * we were already closed, so we can't get that error.
3831 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3832 g_error_free (error);
3834 g_object_unref (message);
3837 /* ---------------------------------------------------------------------------------------------------- */
3840 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3842 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3843 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3844 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3845 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3846 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3849 /* ---------------------------------------------------------------------------------------------------- */
3852 * g_dbus_connection_signal_subscribe:
3853 * @connection: a #GDBusConnection
3854 * @sender: (allow-none): sender name to match on (unique or well-known name)
3855 * or %NULL to listen from all senders
3856 * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3857 * match on all interfaces
3858 * @member: (allow-none): D-Bus signal name to match on or %NULL to match on
3860 * @object_path: (allow-none): object path to match on or %NULL to match on
3862 * @arg0: (allow-none): contents of first string argument to match on or %NULL
3863 * to match on all kinds of arguments
3864 * @flags: flags describing how to subscribe to the signal (currently unused)
3865 * @callback: callback to invoke when there is a signal matching the requested data
3866 * @user_data: user data to pass to @callback
3867 * @user_data_free_func: (allow-none): function to free @user_data with when
3868 * subscription is removed or %NULL
3870 * Subscribes to signals on @connection and invokes @callback with a whenever
3871 * the signal is received. Note that @callback will be invoked in the
3872 * [thread-default main context][g-main-context-push-thread-default]
3873 * of the thread you are calling this method from.
3875 * If @connection is not a message bus connection, @sender must be
3878 * If @sender is a well-known name note that @callback is invoked with
3879 * the unique name for the owner of @sender, not the well-known name
3880 * as one would expect. This is because the message bus rewrites the
3881 * name. As such, to avoid certain race conditions, users should be
3882 * tracking the name owner of the well-known name and use that when
3883 * processing the received signal.
3885 * If one of %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE or
3886 * %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH are given, @arg0 is
3887 * interpreted as part of a namespace or path. The first argument
3888 * of a signal is matched against that part as specified by D-Bus.
3890 * Returns: a subscription identifier that can be used with g_dbus_connection_signal_unsubscribe()
3895 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3896 const gchar *sender,
3897 const gchar *interface_name,
3898 const gchar *member,
3899 const gchar *object_path,
3901 GDBusSignalFlags flags,
3902 GDBusSignalCallback callback,
3904 GDestroyNotify user_data_free_func)
3907 SignalData *signal_data;
3908 SignalSubscriber subscriber;
3909 GPtrArray *signal_data_array;
3910 const gchar *sender_unique_name;
3912 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3913 * an OOM condition. We might want to change that but that would involve making
3914 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3915 * handle that. And there's really no sensible way of handling this short of retrying
3916 * to add the match rule... and then there's the little thing that, hey, maybe there's
3917 * a reason the bus in an OOM condition.
3919 * Doable, but not really sure it's worth it...
3922 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3923 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3924 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3925 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3926 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3927 g_return_val_if_fail (callback != NULL, 0);
3928 g_return_val_if_fail (check_initialized (connection), 0);
3929 g_return_val_if_fail (!((flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH) && (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)), 0);
3930 g_return_val_if_fail (!(arg0 == NULL && (flags & (G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH | G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE))), 0);
3932 CONNECTION_LOCK (connection);
3934 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3935 * with a '-' character to prefix the rule (which will otherwise be
3938 * This allows us to hash the rule and do our lifecycle tracking in
3939 * the usual way, but the '-' prevents the match rule from ever
3940 * actually being send to the bus (either for add or remove).
3942 rule = args_to_rule (sender, interface_name, member, object_path, arg0, flags);
3944 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3945 sender_unique_name = sender;
3947 sender_unique_name = "";
3949 subscriber.callback = callback;
3950 subscriber.user_data = user_data;
3951 subscriber.user_data_free_func = user_data_free_func;
3952 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3953 subscriber.context = g_main_context_ref_thread_default ();
3955 /* see if we've already have this rule */
3956 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3957 if (signal_data != NULL)
3959 g_array_append_val (signal_data->subscribers, subscriber);
3964 signal_data = g_new0 (SignalData, 1);
3965 signal_data->rule = rule;
3966 signal_data->sender = g_strdup (sender);
3967 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3968 signal_data->interface_name = g_strdup (interface_name);
3969 signal_data->member = g_strdup (member);
3970 signal_data->object_path = g_strdup (object_path);
3971 signal_data->arg0 = g_strdup (arg0);
3972 signal_data->flags = flags;
3973 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3974 g_array_append_val (signal_data->subscribers, subscriber);
3976 g_hash_table_insert (connection->map_rule_to_signal_data,
3980 /* Add the match rule to the bus...
3982 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3983 * always send such messages to us.
3985 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3987 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3988 add_match_rule (connection, signal_data->rule);
3991 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3992 signal_data->sender_unique_name);
3993 if (signal_data_array == NULL)
3995 signal_data_array = g_ptr_array_new ();
3996 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3997 g_strdup (signal_data->sender_unique_name),
4000 g_ptr_array_add (signal_data_array, signal_data);
4003 g_hash_table_insert (connection->map_id_to_signal_data,
4004 GUINT_TO_POINTER (subscriber.id),
4007 CONNECTION_UNLOCK (connection);
4009 return subscriber.id;
4012 /* ---------------------------------------------------------------------------------------------------- */
4014 /* called in any thread */
4015 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
4017 unsubscribe_id_internal (GDBusConnection *connection,
4018 guint subscription_id,
4019 GArray *out_removed_subscribers)
4021 SignalData *signal_data;
4022 GPtrArray *signal_data_array;
4025 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
4026 GUINT_TO_POINTER (subscription_id));
4027 if (signal_data == NULL)
4029 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
4033 for (n = 0; n < signal_data->subscribers->len; n++)
4035 SignalSubscriber *subscriber;
4037 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
4038 if (subscriber->id != subscription_id)
4041 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
4042 GUINT_TO_POINTER (subscription_id)));
4043 g_array_append_val (out_removed_subscribers, *subscriber);
4044 g_array_remove_index (signal_data->subscribers, n);
4046 if (signal_data->subscribers->len == 0)
4048 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
4050 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
4051 signal_data->sender_unique_name);
4052 g_warn_if_fail (signal_data_array != NULL);
4053 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
4055 if (signal_data_array->len == 0)
4057 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
4058 signal_data->sender_unique_name));
4061 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
4062 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
4063 !is_signal_data_for_name_lost_or_acquired (signal_data) &&
4064 !g_dbus_connection_is_closed (connection) &&
4065 !connection->finalizing)
4067 /* The check for g_dbus_connection_is_closed() means that
4068 * sending the RemoveMatch message can't fail with
4069 * G_IO_ERROR_CLOSED, because we're holding the lock,
4070 * so on_worker_closed() can't happen between the check we just
4071 * did, and releasing the lock later.
4073 remove_match_rule (connection, signal_data->rule);
4076 signal_data_free (signal_data);
4082 g_assert_not_reached ();
4089 * g_dbus_connection_signal_unsubscribe:
4090 * @connection: a #GDBusConnection
4091 * @subscription_id: a subscription id obtained from
4092 * g_dbus_connection_signal_subscribe()
4094 * Unsubscribes from signals.
4099 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
4100 guint subscription_id)
4102 GArray *subscribers;
4105 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4106 g_return_if_fail (check_initialized (connection));
4108 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
4110 CONNECTION_LOCK (connection);
4111 unsubscribe_id_internal (connection,
4114 CONNECTION_UNLOCK (connection);
4117 g_assert (subscribers->len == 0 || subscribers->len == 1);
4119 /* call GDestroyNotify without lock held */
4120 for (n = 0; n < subscribers->len; n++)
4122 SignalSubscriber *subscriber;
4123 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
4124 call_destroy_notify (subscriber->context,
4125 subscriber->user_data_free_func,
4126 subscriber->user_data);
4127 g_main_context_unref (subscriber->context);
4130 g_array_free (subscribers, TRUE);
4133 /* ---------------------------------------------------------------------------------------------------- */
4137 guint subscription_id;
4138 GDBusSignalCallback callback;
4140 GDBusMessage *message;
4141 GDBusConnection *connection;
4142 const gchar *sender;
4144 const gchar *interface;
4145 const gchar *member;
4148 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
4152 emit_signal_instance_in_idle_cb (gpointer data)
4154 SignalInstance *signal_instance = data;
4155 GVariant *parameters;
4156 gboolean has_subscription;
4158 parameters = g_dbus_message_get_body (signal_instance->message);
4159 if (parameters == NULL)
4161 parameters = g_variant_new ("()");
4162 g_variant_ref_sink (parameters);
4166 g_variant_ref_sink (parameters);
4170 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
4171 signal_instance->subscription_id,
4172 signal_instance->sender,
4173 signal_instance->path,
4174 signal_instance->interface,
4175 signal_instance->member,
4176 g_variant_print (parameters, TRUE));
4179 /* Careful here, don't do the callback if we no longer has the subscription */
4180 CONNECTION_LOCK (signal_instance->connection);
4181 has_subscription = FALSE;
4182 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
4183 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
4184 has_subscription = TRUE;
4185 CONNECTION_UNLOCK (signal_instance->connection);
4187 if (has_subscription)
4188 signal_instance->callback (signal_instance->connection,
4189 signal_instance->sender,
4190 signal_instance->path,
4191 signal_instance->interface,
4192 signal_instance->member,
4194 signal_instance->user_data);
4196 g_variant_unref (parameters);
4202 signal_instance_free (SignalInstance *signal_instance)
4204 g_object_unref (signal_instance->message);
4205 g_object_unref (signal_instance->connection);
4206 g_free (signal_instance);
4210 namespace_rule_matches (const gchar *namespace,
4216 len_namespace = strlen (namespace);
4217 len_name = strlen (name);
4219 if (len_name < len_namespace)
4222 if (memcmp (namespace, name, len_namespace) != 0)
4225 return len_namespace == len_name || name[len_namespace] == '.';
4229 path_rule_matches (const gchar *path_a,
4230 const gchar *path_b)
4234 len_a = strlen (path_a);
4235 len_b = strlen (path_b);
4237 if (len_a < len_b && path_a[len_a - 1] != '/')
4240 if (len_b < len_a && path_b[len_b - 1] != '/')
4243 return memcmp (path_a, path_b, MIN (len_a, len_b)) == 0;
4246 /* called in GDBusWorker thread WITH lock held */
4248 schedule_callbacks (GDBusConnection *connection,
4249 GPtrArray *signal_data_array,
4250 GDBusMessage *message,
4251 const gchar *sender)
4254 const gchar *interface;
4255 const gchar *member;
4264 interface = g_dbus_message_get_interface (message);
4265 member = g_dbus_message_get_member (message);
4266 path = g_dbus_message_get_path (message);
4267 arg0 = g_dbus_message_get_arg0 (message);
4270 g_print ("In schedule_callbacks:\n"
4272 " interface = '%s'\n"
4283 /* TODO: if this is slow, then we can change signal_data_array into
4284 * map_object_path_to_signal_data_array or something.
4286 for (n = 0; n < signal_data_array->len; n++)
4288 SignalData *signal_data = signal_data_array->pdata[n];
4290 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
4293 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
4296 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
4299 if (signal_data->arg0 != NULL)
4304 if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
4306 if (!namespace_rule_matches (signal_data->arg0, arg0))
4309 else if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
4311 if (!path_rule_matches (signal_data->arg0, arg0))
4314 else if (!g_str_equal (signal_data->arg0, arg0))
4318 for (m = 0; m < signal_data->subscribers->len; m++)
4320 SignalSubscriber *subscriber;
4321 GSource *idle_source;
4322 SignalInstance *signal_instance;
4324 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
4326 signal_instance = g_new0 (SignalInstance, 1);
4327 signal_instance->subscription_id = subscriber->id;
4328 signal_instance->callback = subscriber->callback;
4329 signal_instance->user_data = subscriber->user_data;
4330 signal_instance->message = g_object_ref (message);
4331 signal_instance->connection = g_object_ref (connection);
4332 signal_instance->sender = sender;
4333 signal_instance->path = path;
4334 signal_instance->interface = interface;
4335 signal_instance->member = member;
4337 idle_source = g_idle_source_new ();
4338 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4339 g_source_set_callback (idle_source,
4340 emit_signal_instance_in_idle_cb,
4342 (GDestroyNotify) signal_instance_free);
4343 g_source_set_name (idle_source, "[gio] emit_signal_instance_in_idle_cb");
4344 g_source_attach (idle_source, subscriber->context);
4345 g_source_unref (idle_source);
4350 /* called in GDBusWorker thread with lock held */
4352 distribute_signals (GDBusConnection *connection,
4353 GDBusMessage *message)
4355 GPtrArray *signal_data_array;
4356 const gchar *sender;
4358 sender = g_dbus_message_get_sender (message);
4360 if (G_UNLIKELY (_g_dbus_debug_signal ()))
4362 _g_dbus_debug_print_lock ();
4363 g_print ("========================================================================\n"
4364 "GDBus-debug:Signal:\n"
4365 " <<<< RECEIVED SIGNAL %s.%s\n"
4367 " sent by name %s\n",
4368 g_dbus_message_get_interface (message),
4369 g_dbus_message_get_member (message),
4370 g_dbus_message_get_path (message),
4371 sender != NULL ? sender : "(none)");
4372 _g_dbus_debug_print_unlock ();
4375 /* collect subscribers that match on sender */
4378 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
4379 if (signal_data_array != NULL)
4380 schedule_callbacks (connection, signal_data_array, message, sender);
4383 /* collect subscribers not matching on sender */
4384 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
4385 if (signal_data_array != NULL)
4386 schedule_callbacks (connection, signal_data_array, message, sender);
4389 /* ---------------------------------------------------------------------------------------------------- */
4391 /* only called from finalize(), removes all subscriptions */
4393 purge_all_signal_subscriptions (GDBusConnection *connection)
4395 GHashTableIter iter;
4398 GArray *subscribers;
4401 ids = g_array_new (FALSE, FALSE, sizeof (guint));
4402 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
4403 while (g_hash_table_iter_next (&iter, &key, NULL))
4405 guint subscription_id = GPOINTER_TO_UINT (key);
4406 g_array_append_val (ids, subscription_id);
4409 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
4410 for (n = 0; n < ids->len; n++)
4412 guint subscription_id = g_array_index (ids, guint, n);
4413 unsubscribe_id_internal (connection,
4417 g_array_free (ids, TRUE);
4419 /* call GDestroyNotify without lock held */
4420 for (n = 0; n < subscribers->len; n++)
4422 SignalSubscriber *subscriber;
4423 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
4424 call_destroy_notify (subscriber->context,
4425 subscriber->user_data_free_func,
4426 subscriber->user_data);
4427 g_main_context_unref (subscriber->context);
4430 g_array_free (subscribers, TRUE);
4433 /* ---------------------------------------------------------------------------------------------------- */
4435 static GDBusInterfaceVTable *
4436 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
4438 /* Don't waste memory by copying padding - remember to update this
4439 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
4441 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4445 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
4450 /* ---------------------------------------------------------------------------------------------------- */
4452 static GDBusSubtreeVTable *
4453 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
4455 /* Don't waste memory by copying padding - remember to update this
4456 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
4458 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4462 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
4467 /* ---------------------------------------------------------------------------------------------------- */
4469 struct ExportedObject
4472 GDBusConnection *connection;
4474 /* maps gchar* -> ExportedInterface* */
4475 GHashTable *map_if_name_to_ei;
4478 /* only called with lock held */
4480 exported_object_free (ExportedObject *eo)
4482 g_free (eo->object_path);
4483 g_hash_table_unref (eo->map_if_name_to_ei);
4492 gchar *interface_name;
4493 GDBusInterfaceVTable *vtable;
4494 GDBusInterfaceInfo *interface_info;
4496 GMainContext *context;
4498 GDestroyNotify user_data_free_func;
4499 } ExportedInterface;
4501 /* called with lock held */
4503 exported_interface_free (ExportedInterface *ei)
4505 g_dbus_interface_info_cache_release (ei->interface_info);
4506 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
4508 call_destroy_notify (ei->context,
4509 ei->user_data_free_func,
4512 g_main_context_unref (ei->context);
4514 g_free (ei->interface_name);
4515 _g_dbus_interface_vtable_free (ei->vtable);
4519 /* ---------------------------------------------------------------------------------------------------- */
4521 /* Convenience function to check if @registration_id (if not zero) or
4522 * @subtree_registration_id (if not zero) has been unregistered. If
4523 * so, returns %TRUE.
4525 * May be called by any thread. Caller must *not* hold lock.
4528 has_object_been_unregistered (GDBusConnection *connection,
4529 guint registration_id,
4530 guint subtree_registration_id)
4534 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4538 CONNECTION_LOCK (connection);
4539 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
4540 GUINT_TO_POINTER (registration_id)) == NULL)
4544 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
4545 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
4549 CONNECTION_UNLOCK (connection);
4554 /* ---------------------------------------------------------------------------------------------------- */
4558 GDBusConnection *connection;
4559 GDBusMessage *message;
4561 const gchar *property_name;
4562 const GDBusInterfaceVTable *vtable;
4563 GDBusInterfaceInfo *interface_info;
4564 const GDBusPropertyInfo *property_info;
4565 guint registration_id;
4566 guint subtree_registration_id;
4570 property_data_free (PropertyData *data)
4572 g_object_unref (data->connection);
4573 g_object_unref (data->message);
4577 /* called in thread where object was registered - no locks held */
4579 invoke_get_property_in_idle_cb (gpointer _data)
4581 PropertyData *data = _data;
4584 GDBusMessage *reply;
4586 if (has_object_been_unregistered (data->connection,
4587 data->registration_id,
4588 data->subtree_registration_id))
4590 reply = g_dbus_message_new_method_error (data->message,
4591 "org.freedesktop.DBus.Error.UnknownMethod",
4592 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4593 g_dbus_message_get_path (data->message));
4594 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4595 g_object_unref (reply);
4600 value = data->vtable->get_property (data->connection,
4601 g_dbus_message_get_sender (data->message),
4602 g_dbus_message_get_path (data->message),
4603 data->interface_info->name,
4604 data->property_name,
4611 g_assert_no_error (error);
4613 g_variant_take_ref (value);
4614 reply = g_dbus_message_new_method_reply (data->message);
4615 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4616 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4617 g_variant_unref (value);
4618 g_object_unref (reply);
4622 gchar *dbus_error_name;
4623 g_assert (error != NULL);
4624 dbus_error_name = g_dbus_error_encode_gerror (error);
4625 reply = g_dbus_message_new_method_error_literal (data->message,
4628 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4629 g_free (dbus_error_name);
4630 g_error_free (error);
4631 g_object_unref (reply);
4638 /* called in thread where object was registered - no locks held */
4640 invoke_set_property_in_idle_cb (gpointer _data)
4642 PropertyData *data = _data;
4644 GDBusMessage *reply;
4650 g_variant_get (g_dbus_message_get_body (data->message),
4656 if (!data->vtable->set_property (data->connection,
4657 g_dbus_message_get_sender (data->message),
4658 g_dbus_message_get_path (data->message),
4659 data->interface_info->name,
4660 data->property_name,
4665 gchar *dbus_error_name;
4666 g_assert (error != NULL);
4667 dbus_error_name = g_dbus_error_encode_gerror (error);
4668 reply = g_dbus_message_new_method_error_literal (data->message,
4671 g_free (dbus_error_name);
4672 g_error_free (error);
4676 reply = g_dbus_message_new_method_reply (data->message);
4679 g_assert (reply != NULL);
4680 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4681 g_object_unref (reply);
4682 g_variant_unref (value);
4687 /* called in any thread with connection's lock held */
4689 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4690 GDBusMessage *message,
4691 guint registration_id,
4692 guint subtree_registration_id,
4694 GDBusInterfaceInfo *interface_info,
4695 const GDBusInterfaceVTable *vtable,
4696 GMainContext *main_context,
4700 const char *interface_name;
4701 const char *property_name;
4702 const GDBusPropertyInfo *property_info;
4703 GSource *idle_source;
4704 PropertyData *property_data;
4705 GDBusMessage *reply;
4710 g_variant_get (g_dbus_message_get_body (message),
4715 g_variant_get (g_dbus_message_get_body (message),
4724 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4726 property_info = NULL;
4728 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4729 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4730 if (property_info == NULL)
4732 reply = g_dbus_message_new_method_error (message,
4733 "org.freedesktop.DBus.Error.InvalidArgs",
4734 _("No such property '%s'"),
4736 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4737 g_object_unref (reply);
4742 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4744 reply = g_dbus_message_new_method_error (message,
4745 "org.freedesktop.DBus.Error.InvalidArgs",
4746 _("Property '%s' is not readable"),
4748 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4749 g_object_unref (reply);
4753 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4755 reply = g_dbus_message_new_method_error (message,
4756 "org.freedesktop.DBus.Error.InvalidArgs",
4757 _("Property '%s' is not writable"),
4759 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4760 g_object_unref (reply);
4769 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4770 * of the given value is wrong
4772 g_variant_get_child (g_dbus_message_get_body (message), 2, "v", &value);
4773 if (g_strcmp0 (g_variant_get_type_string (value), property_info->signature) != 0)
4775 reply = g_dbus_message_new_method_error (message,
4776 "org.freedesktop.DBus.Error.InvalidArgs",
4777 _("Error setting property '%s': Expected type '%s' but got '%s'"),
4778 property_name, property_info->signature,
4779 g_variant_get_type_string (value));
4780 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4781 g_variant_unref (value);
4782 g_object_unref (reply);
4787 g_variant_unref (value);
4790 /* If the vtable pointer for get_property() resp. set_property() is
4791 * NULL then dispatch the call via the method_call() handler.
4795 if (vtable->get_property == NULL)
4797 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4798 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4799 vtable, main_context, user_data);
4806 if (vtable->set_property == NULL)
4808 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4809 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4810 vtable, main_context, user_data);
4816 /* ok, got the property info - call user code in an idle handler */
4817 property_data = g_new0 (PropertyData, 1);
4818 property_data->connection = g_object_ref (connection);
4819 property_data->message = g_object_ref (message);
4820 property_data->user_data = user_data;
4821 property_data->property_name = property_name;
4822 property_data->vtable = vtable;
4823 property_data->interface_info = interface_info;
4824 property_data->property_info = property_info;
4825 property_data->registration_id = registration_id;
4826 property_data->subtree_registration_id = subtree_registration_id;
4828 idle_source = g_idle_source_new ();
4829 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4830 g_source_set_callback (idle_source,
4831 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4833 (GDestroyNotify) property_data_free);
4835 g_source_set_name (idle_source, "[gio] invoke_get_property_in_idle_cb");
4837 g_source_set_name (idle_source, "[gio] invoke_set_property_in_idle_cb");
4838 g_source_attach (idle_source, main_context);
4839 g_source_unref (idle_source);
4847 /* called in GDBusWorker thread with connection's lock held */
4849 handle_getset_property (GDBusConnection *connection,
4851 GDBusMessage *message,
4854 ExportedInterface *ei;
4856 const char *interface_name;
4857 const char *property_name;
4862 g_variant_get (g_dbus_message_get_body (message),
4867 g_variant_get (g_dbus_message_get_body (message),
4873 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4874 * no such interface registered
4876 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4879 GDBusMessage *reply;
4880 reply = g_dbus_message_new_method_error (message,
4881 "org.freedesktop.DBus.Error.InvalidArgs",
4882 _("No such interface '%s'"),
4884 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4885 g_object_unref (reply);
4890 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4903 /* ---------------------------------------------------------------------------------------------------- */
4907 GDBusConnection *connection;
4908 GDBusMessage *message;
4910 const GDBusInterfaceVTable *vtable;
4911 GDBusInterfaceInfo *interface_info;
4912 guint registration_id;
4913 guint subtree_registration_id;
4914 } PropertyGetAllData;
4917 property_get_all_data_free (PropertyData *data)
4919 g_object_unref (data->connection);
4920 g_object_unref (data->message);
4924 /* called in thread where object was registered - no locks held */
4926 invoke_get_all_properties_in_idle_cb (gpointer _data)
4928 PropertyGetAllData *data = _data;
4929 GVariantBuilder builder;
4930 GDBusMessage *reply;
4933 if (has_object_been_unregistered (data->connection,
4934 data->registration_id,
4935 data->subtree_registration_id))
4937 reply = g_dbus_message_new_method_error (data->message,
4938 "org.freedesktop.DBus.Error.UnknownMethod",
4939 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4940 g_dbus_message_get_path (data->message));
4941 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4942 g_object_unref (reply);
4946 /* TODO: Right now we never fail this call - we just omit values if
4947 * a get_property() call is failing.
4949 * We could fail the whole call if just a single get_property() call
4950 * returns an error. We need clarification in the D-Bus spec about this.
4952 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4953 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4954 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4956 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4959 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4962 value = data->vtable->get_property (data->connection,
4963 g_dbus_message_get_sender (data->message),
4964 g_dbus_message_get_path (data->message),
4965 data->interface_info->name,
4966 property_info->name,
4973 g_variant_take_ref (value);
4974 g_variant_builder_add (&builder,
4976 property_info->name,
4978 g_variant_unref (value);
4980 g_variant_builder_close (&builder);
4982 reply = g_dbus_message_new_method_reply (data->message);
4983 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4984 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4985 g_object_unref (reply);
4992 interface_has_readable_properties (GDBusInterfaceInfo *interface_info)
4996 if (!interface_info->properties)
4999 for (i = 0; interface_info->properties[i]; i++)
5000 if (interface_info->properties[i]->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE)
5006 /* called in any thread with connection's lock held */
5008 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
5009 GDBusMessage *message,
5010 guint registration_id,
5011 guint subtree_registration_id,
5012 GDBusInterfaceInfo *interface_info,
5013 const GDBusInterfaceVTable *vtable,
5014 GMainContext *main_context,
5018 GSource *idle_source;
5019 PropertyGetAllData *property_get_all_data;
5026 /* If the vtable pointer for get_property() is NULL but we have a
5027 * non-zero number of readable properties, then dispatch the call via
5028 * the method_call() handler.
5030 if (vtable->get_property == NULL && interface_has_readable_properties (interface_info))
5032 schedule_method_call (connection, message, registration_id, subtree_registration_id,
5033 interface_info, NULL, NULL, g_dbus_message_get_body (message),
5034 vtable, main_context, user_data);
5039 /* ok, got the property info - call user in an idle handler */
5040 property_get_all_data = g_new0 (PropertyGetAllData, 1);
5041 property_get_all_data->connection = g_object_ref (connection);
5042 property_get_all_data->message = g_object_ref (message);
5043 property_get_all_data->user_data = user_data;
5044 property_get_all_data->vtable = vtable;
5045 property_get_all_data->interface_info = interface_info;
5046 property_get_all_data->registration_id = registration_id;
5047 property_get_all_data->subtree_registration_id = subtree_registration_id;
5049 idle_source = g_idle_source_new ();
5050 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
5051 g_source_set_callback (idle_source,
5052 invoke_get_all_properties_in_idle_cb,
5053 property_get_all_data,
5054 (GDestroyNotify) property_get_all_data_free);
5055 g_source_set_name (idle_source, "[gio] invoke_get_all_properties_in_idle_cb");
5056 g_source_attach (idle_source, main_context);
5057 g_source_unref (idle_source);
5065 /* called in GDBusWorker thread with connection's lock held */
5067 handle_get_all_properties (GDBusConnection *connection,
5069 GDBusMessage *message)
5071 ExportedInterface *ei;
5073 const char *interface_name;
5077 g_variant_get (g_dbus_message_get_body (message),
5081 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
5082 * no such interface registered
5084 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5087 GDBusMessage *reply;
5088 reply = g_dbus_message_new_method_error (message,
5089 "org.freedesktop.DBus.Error.InvalidArgs",
5090 _("No such interface"),
5092 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5093 g_object_unref (reply);
5098 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
5110 /* ---------------------------------------------------------------------------------------------------- */
5112 static const gchar introspect_header[] =
5113 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
5114 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
5115 "<!-- GDBus " PACKAGE_VERSION " -->\n"
5118 static const gchar introspect_tail[] =
5121 static const gchar introspect_properties_interface[] =
5122 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
5123 " <method name=\"Get\">\n"
5124 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5125 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
5126 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
5128 " <method name=\"GetAll\">\n"
5129 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5130 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
5132 " <method name=\"Set\">\n"
5133 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5134 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
5135 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
5137 " <signal name=\"PropertiesChanged\">\n"
5138 " <arg type=\"s\" name=\"interface_name\"/>\n"
5139 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
5140 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
5144 static const gchar introspect_introspectable_interface[] =
5145 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
5146 " <method name=\"Introspect\">\n"
5147 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
5150 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
5151 " <method name=\"Ping\"/>\n"
5152 " <method name=\"GetMachineId\">\n"
5153 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
5158 introspect_append_header (GString *s)
5160 g_string_append (s, introspect_header);
5164 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
5166 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
5172 begin = object_path + path_len;
5173 end = strchr (begin, '/');
5175 s = g_strndup (begin, end - begin);
5177 s = g_strdup (begin);
5179 if (g_hash_table_lookup (set, s) == NULL)
5180 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
5186 /* TODO: we want a nicer public interface for this */
5187 /* called in any thread with connection's lock held */
5189 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
5194 GHashTableIter hash_iter;
5195 const gchar *object_path;
5201 CONNECTION_ENSURE_LOCK (connection);
5203 path_len = strlen (path);
5207 set = g_hash_table_new (g_str_hash, g_str_equal);
5209 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
5210 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
5211 maybe_add_path (path, path_len, object_path, set);
5213 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
5214 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
5215 maybe_add_path (path, path_len, object_path, set);
5217 p = g_ptr_array_new ();
5218 keys = g_hash_table_get_keys (set);
5219 for (l = keys; l != NULL; l = l->next)
5220 g_ptr_array_add (p, l->data);
5221 g_hash_table_unref (set);
5224 g_ptr_array_add (p, NULL);
5225 ret = (gchar **) g_ptr_array_free (p, FALSE);
5229 /* called in any thread with connection's lock not held */
5231 g_dbus_connection_list_registered (GDBusConnection *connection,
5235 CONNECTION_LOCK (connection);
5236 ret = g_dbus_connection_list_registered_unlocked (connection, path);
5237 CONNECTION_UNLOCK (connection);
5241 /* called in GDBusWorker thread with connection's lock held */
5243 handle_introspect (GDBusConnection *connection,
5245 GDBusMessage *message)
5249 GDBusMessage *reply;
5250 GHashTableIter hash_iter;
5251 ExportedInterface *ei;
5254 /* first the header with the standard interfaces */
5255 s = g_string_sized_new (sizeof (introspect_header) +
5256 sizeof (introspect_properties_interface) +
5257 sizeof (introspect_introspectable_interface) +
5258 sizeof (introspect_tail));
5259 introspect_append_header (s);
5260 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
5261 "org.freedesktop.DBus.Properties"))
5262 g_string_append (s, introspect_properties_interface);
5264 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
5265 "org.freedesktop.DBus.Introspectable"))
5266 g_string_append (s, introspect_introspectable_interface);
5268 /* then include the registered interfaces */
5269 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
5270 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
5271 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
5273 /* finally include nodes registered below us */
5274 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
5275 for (n = 0; registered != NULL && registered[n] != NULL; n++)
5276 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
5277 g_strfreev (registered);
5278 g_string_append (s, introspect_tail);
5280 reply = g_dbus_message_new_method_reply (message);
5281 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5282 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5283 g_object_unref (reply);
5284 g_string_free (s, TRUE);
5289 /* called in thread where object was registered - no locks held */
5291 call_in_idle_cb (gpointer user_data)
5293 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
5294 GDBusInterfaceVTable *vtable;
5295 guint registration_id;
5296 guint subtree_registration_id;
5298 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
5299 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
5301 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
5303 subtree_registration_id))
5305 GDBusMessage *reply;
5306 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
5307 "org.freedesktop.DBus.Error.UnknownMethod",
5308 _("No such interface '%s' on object at path %s"),
5309 g_dbus_method_invocation_get_interface_name (invocation),
5310 g_dbus_method_invocation_get_object_path (invocation));
5311 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5312 g_object_unref (reply);
5316 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
5317 g_assert (vtable != NULL && vtable->method_call != NULL);
5319 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
5320 g_dbus_method_invocation_get_sender (invocation),
5321 g_dbus_method_invocation_get_object_path (invocation),
5322 g_dbus_method_invocation_get_interface_name (invocation),
5323 g_dbus_method_invocation_get_method_name (invocation),
5324 g_dbus_method_invocation_get_parameters (invocation),
5325 g_object_ref (invocation),
5326 g_dbus_method_invocation_get_user_data (invocation));
5332 /* called in GDBusWorker thread with connection's lock held */
5334 schedule_method_call (GDBusConnection *connection,
5335 GDBusMessage *message,
5336 guint registration_id,
5337 guint subtree_registration_id,
5338 const GDBusInterfaceInfo *interface_info,
5339 const GDBusMethodInfo *method_info,
5340 const GDBusPropertyInfo *property_info,
5341 GVariant *parameters,
5342 const GDBusInterfaceVTable *vtable,
5343 GMainContext *main_context,
5346 GDBusMethodInvocation *invocation;
5347 GSource *idle_source;
5349 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
5350 g_dbus_message_get_path (message),
5351 g_dbus_message_get_interface (message),
5352 g_dbus_message_get_member (message),
5360 /* TODO: would be nicer with a real MethodData like we already
5361 * have PropertyData and PropertyGetAllData... */
5362 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
5363 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
5364 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
5366 idle_source = g_idle_source_new ();
5367 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
5368 g_source_set_callback (idle_source,
5372 g_source_set_name (idle_source, "[gio] call_in_idle_cb");
5373 g_source_attach (idle_source, main_context);
5374 g_source_unref (idle_source);
5377 /* called in GDBusWorker thread with connection's lock held */
5379 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
5380 GDBusMessage *message,
5381 guint registration_id,
5382 guint subtree_registration_id,
5383 GDBusInterfaceInfo *interface_info,
5384 const GDBusInterfaceVTable *vtable,
5385 GMainContext *main_context,
5388 GDBusMethodInfo *method_info;
5389 GDBusMessage *reply;
5390 GVariant *parameters;
5392 GVariantType *in_type;
5396 /* TODO: the cost of this is O(n) - it might be worth caching the result */
5397 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
5399 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
5400 * error to the caller
5402 if (method_info == NULL)
5404 reply = g_dbus_message_new_method_error (message,
5405 "org.freedesktop.DBus.Error.UnknownMethod",
5406 _("No such method '%s'"),
5407 g_dbus_message_get_member (message));
5408 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5409 g_object_unref (reply);
5414 parameters = g_dbus_message_get_body (message);
5415 if (parameters == NULL)
5417 parameters = g_variant_new ("()");
5418 g_variant_ref_sink (parameters);
5422 g_variant_ref (parameters);
5425 /* Check that the incoming args are of the right type - if they are not, return
5426 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
5428 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
5429 if (!g_variant_is_of_type (parameters, in_type))
5433 type_string = g_variant_type_dup_string (in_type);
5435 reply = g_dbus_message_new_method_error (message,
5436 "org.freedesktop.DBus.Error.InvalidArgs",
5437 _("Type of message, '%s', does not match expected type '%s'"),
5438 g_variant_get_type_string (parameters),
5440 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5441 g_variant_type_free (in_type);
5442 g_variant_unref (parameters);
5443 g_object_unref (reply);
5444 g_free (type_string);
5448 g_variant_type_free (in_type);
5450 /* schedule the call in idle */
5451 schedule_method_call (connection, message, registration_id, subtree_registration_id,
5452 interface_info, method_info, NULL, parameters,
5453 vtable, main_context, user_data);
5454 g_variant_unref (parameters);
5461 /* ---------------------------------------------------------------------------------------------------- */
5463 /* called in GDBusWorker thread with connection's lock held */
5465 obj_message_func (GDBusConnection *connection,
5467 GDBusMessage *message)
5469 const gchar *interface_name;
5470 const gchar *member;
5471 const gchar *signature;
5476 interface_name = g_dbus_message_get_interface (message);
5477 member = g_dbus_message_get_member (message);
5478 signature = g_dbus_message_get_signature (message);
5480 /* see if we have an interface for handling this call */
5481 if (interface_name != NULL)
5483 ExportedInterface *ei;
5484 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5487 /* we do - invoke the handler in idle in the right thread */
5489 /* handle no vtable or handler being present */
5490 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
5493 handled = validate_and_maybe_schedule_method_call (connection,
5505 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5506 g_strcmp0 (member, "Introspect") == 0 &&
5507 g_strcmp0 (signature, "") == 0)
5509 handled = handle_introspect (connection, eo, message);
5512 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5513 g_strcmp0 (member, "Get") == 0 &&
5514 g_strcmp0 (signature, "ss") == 0)
5516 handled = handle_getset_property (connection, eo, message, TRUE);
5519 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5520 g_strcmp0 (member, "Set") == 0 &&
5521 g_strcmp0 (signature, "ssv") == 0)
5523 handled = handle_getset_property (connection, eo, message, FALSE);
5526 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5527 g_strcmp0 (member, "GetAll") == 0 &&
5528 g_strcmp0 (signature, "s") == 0)
5530 handled = handle_get_all_properties (connection, eo, message);
5539 * g_dbus_connection_register_object:
5540 * @connection: a #GDBusConnection
5541 * @object_path: the object path to register at
5542 * @interface_info: introspection data for the interface
5543 * @vtable: (allow-none): a #GDBusInterfaceVTable to call into or %NULL
5544 * @user_data: (allow-none): data to pass to functions in @vtable
5545 * @user_data_free_func: function to call when the object path is unregistered
5546 * @error: return location for error or %NULL
5548 * Registers callbacks for exported objects at @object_path with the
5549 * D-Bus interface that is described in @interface_info.
5551 * Calls to functions in @vtable (and @user_data_free_func) will happen
5553 * [thread-default main context][g-main-context-push-thread-default]
5554 * of the thread you are calling this method from.
5556 * Note that all #GVariant values passed to functions in @vtable will match
5557 * the signature given in @interface_info - if a remote caller passes
5558 * incorrect values, the `org.freedesktop.DBus.Error.InvalidArgs`
5559 * is returned to the remote caller.
5561 * Additionally, if the remote caller attempts to invoke methods or
5562 * access properties not mentioned in @interface_info the
5563 * `org.freedesktop.DBus.Error.UnknownMethod` resp.
5564 * `org.freedesktop.DBus.Error.InvalidArgs` errors
5565 * are returned to the caller.
5567 * It is considered a programming error if the
5568 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
5569 * #GVariant of incorrect type.
5571 * If an existing callback is already registered at @object_path and
5572 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
5574 * GDBus automatically implements the standard D-Bus interfaces
5575 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
5576 * and org.freedesktop.Peer, so you don't have to implement those for the
5577 * objects you export. You can implement org.freedesktop.DBus.Properties
5578 * yourself, e.g. to handle getting and setting of properties asynchronously.
5580 * Note that the reference count on @interface_info will be
5581 * incremented by 1 (unless allocated statically, e.g. if the
5582 * reference count is -1, see g_dbus_interface_info_ref()) for as long
5583 * as the object is exported. Also note that @vtable will be copied.
5585 * See this [server][gdbus-server] for an example of how to use this method.
5587 * Returns: 0 if @error is set, otherwise a registration id (never 0)
5588 * that can be used with g_dbus_connection_unregister_object()
5593 g_dbus_connection_register_object (GDBusConnection *connection,
5594 const gchar *object_path,
5595 GDBusInterfaceInfo *interface_info,
5596 const GDBusInterfaceVTable *vtable,
5598 GDestroyNotify user_data_free_func,
5602 ExportedInterface *ei;
5605 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5606 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5607 g_return_val_if_fail (interface_info != NULL, 0);
5608 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
5609 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5610 g_return_val_if_fail (check_initialized (connection), 0);
5614 CONNECTION_LOCK (connection);
5616 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5619 eo = g_new0 (ExportedObject, 1);
5620 eo->object_path = g_strdup (object_path);
5621 eo->connection = connection;
5622 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
5625 (GDestroyNotify) exported_interface_free);
5626 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
5629 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
5635 _("An object is already exported for the interface %s at %s"),
5636 interface_info->name,
5641 ei = g_new0 (ExportedInterface, 1);
5642 ei->id = _global_registration_id++; /* TODO: overflow etc. */
5644 ei->user_data = user_data;
5645 ei->user_data_free_func = user_data_free_func;
5646 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
5647 ei->interface_info = g_dbus_interface_info_ref (interface_info);
5648 g_dbus_interface_info_cache_build (ei->interface_info);
5649 ei->interface_name = g_strdup (interface_info->name);
5650 ei->context = g_main_context_ref_thread_default ();
5652 g_hash_table_insert (eo->map_if_name_to_ei,
5653 (gpointer) ei->interface_name,
5655 g_hash_table_insert (connection->map_id_to_ei,
5656 GUINT_TO_POINTER (ei->id),
5662 CONNECTION_UNLOCK (connection);
5668 * g_dbus_connection_unregister_object:
5669 * @connection: a #GDBusConnection
5670 * @registration_id: a registration id obtained from
5671 * g_dbus_connection_register_object()
5673 * Unregisters an object.
5675 * Returns: %TRUE if the object was unregistered, %FALSE otherwise
5680 g_dbus_connection_unregister_object (GDBusConnection *connection,
5681 guint registration_id)
5683 ExportedInterface *ei;
5687 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5688 g_return_val_if_fail (check_initialized (connection), FALSE);
5692 CONNECTION_LOCK (connection);
5694 ei = g_hash_table_lookup (connection->map_id_to_ei,
5695 GUINT_TO_POINTER (registration_id));
5701 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5702 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5703 /* unregister object path if we have no more exported interfaces */
5704 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5705 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5711 CONNECTION_UNLOCK (connection);
5716 /* ---------------------------------------------------------------------------------------------------- */
5719 * g_dbus_connection_emit_signal:
5720 * @connection: a #GDBusConnection
5721 * @destination_bus_name: (allow-none): the unique bus name for the destination
5722 * for the signal or %NULL to emit to all listeners
5723 * @object_path: path of remote object
5724 * @interface_name: D-Bus interface to emit a signal on
5725 * @signal_name: the name of the signal to emit
5726 * @parameters: (allow-none): a #GVariant tuple with parameters for the signal
5727 * or %NULL if not passing parameters
5728 * @error: Return location for error or %NULL
5732 * If the parameters GVariant is floating, it is consumed.
5734 * This can only fail if @parameters is not compatible with the D-Bus protocol.
5736 * Returns: %TRUE unless @error is set
5741 g_dbus_connection_emit_signal (GDBusConnection *connection,
5742 const gchar *destination_bus_name,
5743 const gchar *object_path,
5744 const gchar *interface_name,
5745 const gchar *signal_name,
5746 GVariant *parameters,
5749 GDBusMessage *message;
5755 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5756 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5757 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5758 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5759 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5760 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5761 g_return_val_if_fail (check_initialized (connection), FALSE);
5763 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5765 _g_dbus_debug_print_lock ();
5766 g_print ("========================================================================\n"
5767 "GDBus-debug:Emission:\n"
5768 " >>>> SIGNAL EMISSION %s.%s()\n"
5770 " destination %s\n",
5771 interface_name, signal_name,
5773 destination_bus_name != NULL ? destination_bus_name : "(none)");
5774 _g_dbus_debug_print_unlock ();
5777 message = g_dbus_message_new_signal (object_path,
5781 if (destination_bus_name != NULL)
5782 g_dbus_message_set_header (message,
5783 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5784 g_variant_new_string (destination_bus_name));
5786 if (parameters != NULL)
5787 g_dbus_message_set_body (message, parameters);
5789 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5790 g_object_unref (message);
5796 add_call_flags (GDBusMessage *message,
5797 GDBusCallFlags flags)
5799 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5800 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
5804 decode_method_reply (GDBusMessage *reply,
5805 const gchar *method_name,
5806 const GVariantType *reply_type,
5807 GUnixFDList **out_fd_list,
5813 switch (g_dbus_message_get_message_type (reply))
5815 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5816 result = g_dbus_message_get_body (reply);
5819 result = g_variant_new ("()");
5820 g_variant_ref_sink (result);
5824 g_variant_ref (result);
5827 if (!g_variant_is_of_type (result, reply_type))
5829 gchar *type_string = g_variant_type_dup_string (reply_type);
5833 G_IO_ERROR_INVALID_ARGUMENT,
5834 _("Method '%s' returned type '%s', but expected '%s'"),
5835 method_name, g_variant_get_type_string (result), type_string);
5837 g_variant_unref (result);
5838 g_free (type_string);
5845 if (out_fd_list != NULL)
5847 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5848 if (*out_fd_list != NULL)
5849 g_object_ref (*out_fd_list);
5855 case G_DBUS_MESSAGE_TYPE_ERROR:
5856 g_dbus_message_to_gerror (reply, error);
5860 g_assert_not_reached ();
5870 GSimpleAsyncResult *simple;
5871 GVariantType *reply_type;
5872 gchar *method_name; /* for error message */
5876 GUnixFDList *fd_list;
5880 call_state_free (CallState *state)
5882 g_variant_type_free (state->reply_type);
5883 g_free (state->method_name);
5885 if (state->value != NULL)
5886 g_variant_unref (state->value);
5887 if (state->fd_list != NULL)
5888 g_object_unref (state->fd_list);
5889 g_slice_free (CallState, state);
5892 /* called in any thread, with the connection's lock not held */
5894 g_dbus_connection_call_done (GObject *source,
5895 GAsyncResult *result,
5898 GSimpleAsyncResult *simple;
5899 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5900 CallState *state = user_data;
5902 GDBusMessage *reply;
5905 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5909 if (G_UNLIKELY (_g_dbus_debug_call ()))
5911 _g_dbus_debug_print_lock ();
5912 g_print ("========================================================================\n"
5913 "GDBus-debug:Call:\n"
5914 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5920 g_print ("SUCCESS\n");
5924 g_print ("FAILED: %s\n",
5927 _g_dbus_debug_print_unlock ();
5931 state->value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5933 simple = state->simple; /* why? because state is freed before we unref simple.. */
5936 g_simple_async_result_take_error (state->simple, error);
5937 g_simple_async_result_complete (state->simple);
5938 call_state_free (state);
5942 g_simple_async_result_set_op_res_gpointer (state->simple, state, (GDestroyNotify) call_state_free);
5943 g_simple_async_result_complete (state->simple);
5945 g_clear_object (&reply);
5946 g_object_unref (simple);
5949 /* called in any thread, with the connection's lock not held */
5951 g_dbus_connection_call_internal (GDBusConnection *connection,
5952 const gchar *bus_name,
5953 const gchar *object_path,
5954 const gchar *interface_name,
5955 const gchar *method_name,
5956 GVariant *parameters,
5957 const GVariantType *reply_type,
5958 GDBusCallFlags flags,
5960 GUnixFDList *fd_list,
5961 GCancellable *cancellable,
5962 GAsyncReadyCallback callback,
5965 GDBusMessage *message;
5968 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5969 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5970 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5971 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5972 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5973 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5974 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5975 g_return_if_fail (check_initialized (connection));
5977 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5979 g_return_if_fail (fd_list == NULL);
5982 message = g_dbus_message_new_method_call (bus_name,
5986 add_call_flags (message, flags);
5987 if (parameters != NULL)
5988 g_dbus_message_set_body (message, parameters);
5991 if (fd_list != NULL)
5992 g_dbus_message_set_unix_fd_list (message, fd_list);
5995 /* If the user has no callback then we can just send the message with
5996 * the G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set and skip all
5997 * the logic for processing the reply. If the service sends the reply
5998 * anyway then it will just be ignored.
6000 if (callback != NULL)
6004 state = g_slice_new0 (CallState);
6005 state->simple = g_simple_async_result_new (G_OBJECT (connection),
6006 callback, user_data,
6007 g_dbus_connection_call_internal);
6008 g_simple_async_result_set_check_cancellable (state->simple, cancellable);
6009 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
6011 if (reply_type == NULL)
6012 reply_type = G_VARIANT_TYPE_ANY;
6014 state->reply_type = g_variant_type_copy (reply_type);
6016 g_dbus_connection_send_message_with_reply (connection,
6018 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
6022 g_dbus_connection_call_done,
6024 serial = state->serial;
6028 GDBusMessageFlags flags;
6030 flags = g_dbus_message_get_flags (message);
6031 flags |= G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
6032 g_dbus_message_set_flags (message, flags);
6034 g_dbus_connection_send_message (connection,
6036 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
6040 if (G_UNLIKELY (_g_dbus_debug_call ()))
6042 _g_dbus_debug_print_lock ();
6043 g_print ("========================================================================\n"
6044 "GDBus-debug:Call:\n"
6045 " >>>> ASYNC %s.%s()\n"
6047 " owned by name %s (serial %d)\n",
6051 bus_name != NULL ? bus_name : "(none)",
6053 _g_dbus_debug_print_unlock ();
6056 if (message != NULL)
6057 g_object_unref (message);
6060 /* called in any thread, with the connection's lock not held */
6062 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
6063 GUnixFDList **out_fd_list,
6067 GSimpleAsyncResult *simple;
6070 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
6071 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
6072 g_dbus_connection_call_internal), NULL);
6073 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6075 simple = G_SIMPLE_ASYNC_RESULT (res);
6077 if (g_simple_async_result_propagate_error (simple, error))
6080 state = g_simple_async_result_get_op_res_gpointer (simple);
6081 if (out_fd_list != NULL)
6082 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
6083 return g_variant_ref (state->value);
6086 /* called in any user thread, with the connection's lock not held */
6088 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
6089 const gchar *bus_name,
6090 const gchar *object_path,
6091 const gchar *interface_name,
6092 const gchar *method_name,
6093 GVariant *parameters,
6094 const GVariantType *reply_type,
6095 GDBusCallFlags flags,
6097 GUnixFDList *fd_list,
6098 GUnixFDList **out_fd_list,
6099 GCancellable *cancellable,
6102 GDBusMessage *message;
6103 GDBusMessage *reply;
6105 GError *local_error;
6106 GDBusSendMessageFlags send_flags;
6112 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
6113 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
6114 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
6115 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
6116 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
6117 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
6118 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
6120 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
6122 g_return_val_if_fail (fd_list == NULL, NULL);
6124 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6126 if (!(flags & CALL_FLAGS_INITIALIZING))
6127 g_return_val_if_fail (check_initialized (connection), FALSE);
6129 if (reply_type == NULL)
6130 reply_type = G_VARIANT_TYPE_ANY;
6132 message = g_dbus_message_new_method_call (bus_name,
6136 add_call_flags (message, flags);
6137 if (parameters != NULL)
6138 g_dbus_message_set_body (message, parameters);
6141 if (fd_list != NULL)
6142 g_dbus_message_set_unix_fd_list (message, fd_list);
6145 if (G_UNLIKELY (_g_dbus_debug_call ()))
6147 _g_dbus_debug_print_lock ();
6148 g_print ("========================================================================\n"
6149 "GDBus-debug:Call:\n"
6150 " >>>> SYNC %s.%s()\n"
6152 " owned by name %s\n",
6156 bus_name != NULL ? bus_name : "(none)");
6157 _g_dbus_debug_print_unlock ();
6162 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
6164 /* translate from one flavour of flags to another... */
6165 if (flags & CALL_FLAGS_INITIALIZING)
6166 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
6168 reply = g_dbus_connection_send_message_with_reply_sync (connection,
6172 NULL, /* volatile guint32 *out_serial */
6176 if (G_UNLIKELY (_g_dbus_debug_call ()))
6178 _g_dbus_debug_print_lock ();
6179 g_print ("========================================================================\n"
6180 "GDBus-debug:Call:\n"
6181 " <<<< SYNC COMPLETE %s.%s()\n"
6187 g_print ("SUCCESS\n");
6191 g_print ("FAILED: %s\n",
6192 local_error->message);
6194 _g_dbus_debug_print_unlock ();
6200 *error = local_error;
6202 g_error_free (local_error);
6206 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
6209 if (message != NULL)
6210 g_object_unref (message);
6212 g_object_unref (reply);
6217 /* ---------------------------------------------------------------------------------------------------- */
6220 * g_dbus_connection_call:
6221 * @connection: a #GDBusConnection
6222 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6223 * @connection is not a message bus connection
6224 * @object_path: path of remote object
6225 * @interface_name: D-Bus interface to invoke method on
6226 * @method_name: the name of the method to invoke
6227 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6228 * or %NULL if not passing parameters
6229 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6230 * @flags: flags from the #GDBusCallFlags enumeration
6231 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6232 * timeout or %G_MAXINT for no timeout
6233 * @cancellable: (allow-none): a #GCancellable or %NULL
6234 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request
6235 * is satisfied or %NULL if you don't care about the result of the
6237 * @user_data: the data to pass to @callback
6239 * Asynchronously invokes the @method_name method on the
6240 * @interface_name D-Bus interface on the remote object at
6241 * @object_path owned by @bus_name.
6243 * If @connection is closed then the operation will fail with
6244 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
6245 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
6246 * not compatible with the D-Bus protocol, the operation fails with
6247 * %G_IO_ERROR_INVALID_ARGUMENT.
6249 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
6250 * error will be raised if it does not match. Said another way, if you give a @reply_type
6251 * then any non-%NULL return value will be of this type.
6253 * If the @parameters #GVariant is floating, it is consumed. This allows
6254 * convenient 'inline' use of g_variant_new(), e.g.:
6255 * |[<!-- language="C" -->
6256 * g_dbus_connection_call (connection,
6257 * "org.freedesktop.StringThings",
6258 * "/org/freedesktop/StringThings",
6259 * "org.freedesktop.StringThings",
6261 * g_variant_new ("(ss)",
6265 * G_DBUS_CALL_FLAGS_NONE,
6268 * (GAsyncReadyCallback) two_strings_done,
6272 * This is an asynchronous method. When the operation is finished,
6273 * @callback will be invoked in the
6274 * [thread-default main context][g-main-context-push-thread-default]
6275 * of the thread you are calling this method from. You can then call
6276 * g_dbus_connection_call_finish() to get the result of the operation.
6277 * See g_dbus_connection_call_sync() for the synchronous version of this
6280 * If @callback is %NULL then the D-Bus method call message will be sent with
6281 * the %G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set.
6286 g_dbus_connection_call (GDBusConnection *connection,
6287 const gchar *bus_name,
6288 const gchar *object_path,
6289 const gchar *interface_name,
6290 const gchar *method_name,
6291 GVariant *parameters,
6292 const GVariantType *reply_type,
6293 GDBusCallFlags flags,
6295 GCancellable *cancellable,
6296 GAsyncReadyCallback callback,
6299 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);
6303 * g_dbus_connection_call_finish:
6304 * @connection: a #GDBusConnection
6305 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call()
6306 * @error: return location for error or %NULL
6308 * Finishes an operation started with g_dbus_connection_call().
6310 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6311 * return values. Free with g_variant_unref().
6316 g_dbus_connection_call_finish (GDBusConnection *connection,
6320 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
6324 * g_dbus_connection_call_sync:
6325 * @connection: a #GDBusConnection
6326 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6327 * @connection is not a message bus connection
6328 * @object_path: path of remote object
6329 * @interface_name: D-Bus interface to invoke method on
6330 * @method_name: the name of the method to invoke
6331 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6332 * or %NULL if not passing parameters
6333 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6334 * @flags: flags from the #GDBusCallFlags enumeration
6335 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6336 * timeout or %G_MAXINT for no timeout
6337 * @cancellable: (allow-none): a #GCancellable or %NULL
6338 * @error: return location for error or %NULL
6340 * Synchronously invokes the @method_name method on the
6341 * @interface_name D-Bus interface on the remote object at
6342 * @object_path owned by @bus_name.
6344 * If @connection is closed then the operation will fail with
6345 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
6346 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
6347 * contains a value not compatible with the D-Bus protocol, the operation
6348 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
6350 * If @reply_type is non-%NULL then the reply will be checked for having
6351 * this type and an error will be raised if it does not match. Said
6352 * another way, if you give a @reply_type then any non-%NULL return
6353 * value will be of this type.
6355 * If the @parameters #GVariant is floating, it is consumed.
6356 * This allows convenient 'inline' use of g_variant_new(), e.g.:
6357 * |[<!-- language="C" -->
6358 * g_dbus_connection_call_sync (connection,
6359 * "org.freedesktop.StringThings",
6360 * "/org/freedesktop/StringThings",
6361 * "org.freedesktop.StringThings",
6363 * g_variant_new ("(ss)",
6367 * G_DBUS_CALL_FLAGS_NONE,
6373 * The calling thread is blocked until a reply is received. See
6374 * g_dbus_connection_call() for the asynchronous version of
6377 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6378 * return values. Free with g_variant_unref().
6383 g_dbus_connection_call_sync (GDBusConnection *connection,
6384 const gchar *bus_name,
6385 const gchar *object_path,
6386 const gchar *interface_name,
6387 const gchar *method_name,
6388 GVariant *parameters,
6389 const GVariantType *reply_type,
6390 GDBusCallFlags flags,
6392 GCancellable *cancellable,
6395 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);
6398 /* ---------------------------------------------------------------------------------------------------- */
6403 * g_dbus_connection_call_with_unix_fd_list:
6404 * @connection: a #GDBusConnection
6405 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6406 * @connection is not a message bus connection
6407 * @object_path: path of remote object
6408 * @interface_name: D-Bus interface to invoke method on
6409 * @method_name: the name of the method to invoke
6410 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6411 * or %NULL if not passing parameters
6412 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6413 * @flags: flags from the #GDBusCallFlags enumeration
6414 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6415 * timeout or %G_MAXINT for no timeout
6416 * @fd_list: (allow-none): a #GUnixFDList or %NULL
6417 * @cancellable: (allow-none): a #GCancellable or %NULL
6418 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request is
6419 * satisfied or %NULL if you don't * care about the result of the
6421 * @user_data: The data to pass to @callback.
6423 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
6425 * This method is only available on UNIX.
6430 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
6431 const gchar *bus_name,
6432 const gchar *object_path,
6433 const gchar *interface_name,
6434 const gchar *method_name,
6435 GVariant *parameters,
6436 const GVariantType *reply_type,
6437 GDBusCallFlags flags,
6439 GUnixFDList *fd_list,
6440 GCancellable *cancellable,
6441 GAsyncReadyCallback callback,
6444 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);
6448 * g_dbus_connection_call_with_unix_fd_list_finish:
6449 * @connection: a #GDBusConnection
6450 * @out_fd_list: (out) (allow-none): return location for a #GUnixFDList or %NULL
6451 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
6452 * g_dbus_connection_call_with_unix_fd_list()
6453 * @error: return location for error or %NULL
6455 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
6457 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6458 * return values. Free with g_variant_unref().
6463 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
6464 GUnixFDList **out_fd_list,
6468 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
6472 * g_dbus_connection_call_with_unix_fd_list_sync:
6473 * @connection: a #GDBusConnection
6474 * @bus_name: (allow-none): a unique or well-known bus name or %NULL
6475 * if @connection is not a message bus connection
6476 * @object_path: path of remote object
6477 * @interface_name: D-Bus interface to invoke method on
6478 * @method_name: the name of the method to invoke
6479 * @parameters: (allow-none): a #GVariant tuple with parameters for
6480 * the method or %NULL if not passing parameters
6481 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6482 * @flags: flags from the #GDBusCallFlags enumeration
6483 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6484 * timeout or %G_MAXINT for no timeout
6485 * @fd_list: (allow-none): a #GUnixFDList or %NULL
6486 * @out_fd_list: (out) (allow-none): return location for a #GUnixFDList or %NULL
6487 * @cancellable: (allow-none): a #GCancellable or %NULL
6488 * @error: return location for error or %NULL
6490 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
6492 * This method is only available on UNIX.
6494 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6495 * return values. Free with g_variant_unref().
6500 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
6501 const gchar *bus_name,
6502 const gchar *object_path,
6503 const gchar *interface_name,
6504 const gchar *method_name,
6505 GVariant *parameters,
6506 const GVariantType *reply_type,
6507 GDBusCallFlags flags,
6509 GUnixFDList *fd_list,
6510 GUnixFDList **out_fd_list,
6511 GCancellable *cancellable,
6514 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);
6517 #endif /* G_OS_UNIX */
6519 /* ---------------------------------------------------------------------------------------------------- */
6521 struct ExportedSubtree
6525 GDBusConnection *connection;
6526 GDBusSubtreeVTable *vtable;
6527 GDBusSubtreeFlags flags;
6529 GMainContext *context;
6531 GDestroyNotify user_data_free_func;
6535 exported_subtree_free (ExportedSubtree *es)
6537 call_destroy_notify (es->context,
6538 es->user_data_free_func,
6541 g_main_context_unref (es->context);
6543 _g_dbus_subtree_vtable_free (es->vtable);
6544 g_free (es->object_path);
6548 /* called without lock held in the thread where the caller registered
6552 handle_subtree_introspect (GDBusConnection *connection,
6553 ExportedSubtree *es,
6554 GDBusMessage *message)
6558 GDBusMessage *reply;
6561 const gchar *sender;
6562 const gchar *requested_object_path;
6563 const gchar *requested_node;
6564 GDBusInterfaceInfo **interfaces;
6566 gchar **subnode_paths;
6567 gboolean has_properties_interface;
6568 gboolean has_introspectable_interface;
6572 requested_object_path = g_dbus_message_get_path (message);
6573 sender = g_dbus_message_get_sender (message);
6574 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6576 s = g_string_new (NULL);
6577 introspect_append_header (s);
6579 /* Strictly we don't need the children in dynamic mode, but we avoid the
6580 * conditionals to preserve code clarity
6582 children = es->vtable->enumerate (es->connection,
6589 requested_node = strrchr (requested_object_path, '/') + 1;
6591 /* Assert existence of object if we are not dynamic */
6592 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
6593 !_g_strv_has_string ((const gchar * const *) children, requested_node))
6598 requested_node = NULL;
6601 interfaces = es->vtable->introspect (es->connection,
6606 if (interfaces != NULL)
6608 has_properties_interface = FALSE;
6609 has_introspectable_interface = FALSE;
6611 for (n = 0; interfaces[n] != NULL; n++)
6613 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
6614 has_properties_interface = TRUE;
6615 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
6616 has_introspectable_interface = TRUE;
6618 if (!has_properties_interface)
6619 g_string_append (s, introspect_properties_interface);
6620 if (!has_introspectable_interface)
6621 g_string_append (s, introspect_introspectable_interface);
6623 for (n = 0; interfaces[n] != NULL; n++)
6625 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
6626 g_dbus_interface_info_unref (interfaces[n]);
6628 g_free (interfaces);
6631 /* then include <node> entries from the Subtree for the root */
6634 for (n = 0; children != NULL && children[n] != NULL; n++)
6635 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
6638 /* finally include nodes registered below us */
6639 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
6640 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
6641 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
6642 g_strfreev (subnode_paths);
6644 g_string_append (s, "</node>\n");
6646 reply = g_dbus_message_new_method_reply (message);
6647 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6648 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6649 g_object_unref (reply);
6654 g_string_free (s, TRUE);
6655 g_strfreev (children);
6659 /* called without lock held in the thread where the caller registered
6663 handle_subtree_method_invocation (GDBusConnection *connection,
6664 ExportedSubtree *es,
6665 GDBusMessage *message)
6668 const gchar *sender;
6669 const gchar *interface_name;
6670 const gchar *member;
6671 const gchar *signature;
6672 const gchar *requested_object_path;
6673 const gchar *requested_node;
6675 GDBusInterfaceInfo *interface_info;
6676 const GDBusInterfaceVTable *interface_vtable;
6677 gpointer interface_user_data;
6679 GDBusInterfaceInfo **interfaces;
6680 gboolean is_property_get;
6681 gboolean is_property_set;
6682 gboolean is_property_get_all;
6687 requested_object_path = g_dbus_message_get_path (message);
6688 sender = g_dbus_message_get_sender (message);
6689 interface_name = g_dbus_message_get_interface (message);
6690 member = g_dbus_message_get_member (message);
6691 signature = g_dbus_message_get_signature (message);
6692 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6694 is_property_get = FALSE;
6695 is_property_set = FALSE;
6696 is_property_get_all = FALSE;
6697 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6699 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6700 is_property_get = TRUE;
6701 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6702 is_property_set = TRUE;
6703 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6704 is_property_get_all = TRUE;
6709 requested_node = strrchr (requested_object_path, '/') + 1;
6711 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6713 /* We don't want to dispatch to unenumerated
6714 * nodes, so ensure that the child exists.
6719 children = es->vtable->enumerate (es->connection,
6724 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6725 g_strfreev (children);
6733 requested_node = NULL;
6736 /* get introspection data for the node */
6737 interfaces = es->vtable->introspect (es->connection,
6739 requested_object_path,
6743 if (interfaces == NULL)
6746 interface_info = NULL;
6747 for (n = 0; interfaces[n] != NULL; n++)
6749 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6750 interface_info = interfaces[n];
6753 /* dispatch the call if the user wants to handle it */
6754 if (interface_info != NULL)
6756 /* figure out where to dispatch the method call */
6757 interface_user_data = NULL;
6758 interface_vtable = es->vtable->dispatch (es->connection,
6763 &interface_user_data,
6765 if (interface_vtable == NULL)
6768 CONNECTION_LOCK (connection);
6769 handled = validate_and_maybe_schedule_method_call (es->connection,
6776 interface_user_data);
6777 CONNECTION_UNLOCK (connection);
6779 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6780 else if (is_property_get || is_property_set || is_property_get_all)
6782 if (is_property_get)
6783 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6784 else if (is_property_set)
6785 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6786 else if (is_property_get_all)
6787 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6789 g_assert_not_reached ();
6791 /* see if the object supports this interface at all */
6792 for (n = 0; interfaces[n] != NULL; n++)
6794 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6795 interface_info = interfaces[n];
6798 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6799 * claims it won't support the interface
6801 if (interface_info == NULL)
6803 GDBusMessage *reply;
6804 reply = g_dbus_message_new_method_error (message,
6805 "org.freedesktop.DBus.Error.InvalidArgs",
6806 _("No such interface '%s'"),
6808 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6809 g_object_unref (reply);
6814 /* figure out where to dispatch the property get/set/getall calls */
6815 interface_user_data = NULL;
6816 interface_vtable = es->vtable->dispatch (es->connection,
6821 &interface_user_data,
6823 if (interface_vtable == NULL)
6825 g_warning ("The subtree introspection function indicates that '%s' "
6826 "is a valid interface name, but calling the dispatch "
6827 "function on that interface gave us NULL", interface_name);
6831 if (is_property_get || is_property_set)
6833 CONNECTION_LOCK (connection);
6834 handled = validate_and_maybe_schedule_property_getset (es->connection,
6842 interface_user_data);
6843 CONNECTION_UNLOCK (connection);
6845 else if (is_property_get_all)
6847 CONNECTION_LOCK (connection);
6848 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6855 interface_user_data);
6856 CONNECTION_UNLOCK (connection);
6861 if (interfaces != NULL)
6863 for (n = 0; interfaces[n] != NULL; n++)
6864 g_dbus_interface_info_unref (interfaces[n]);
6865 g_free (interfaces);
6873 GDBusMessage *message;
6874 ExportedSubtree *es;
6875 } SubtreeDeferredData;
6878 subtree_deferred_data_free (SubtreeDeferredData *data)
6880 g_object_unref (data->message);
6884 /* called without lock held in the thread where the caller registered the subtree */
6886 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6888 SubtreeDeferredData *data = _data;
6893 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6894 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6895 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6896 handled = handle_subtree_introspect (data->es->connection,
6900 handled = handle_subtree_method_invocation (data->es->connection,
6906 CONNECTION_LOCK (data->es->connection);
6907 handled = handle_generic_unlocked (data->es->connection, data->message);
6908 CONNECTION_UNLOCK (data->es->connection);
6911 /* if we couldn't handle the request, just bail with the UnknownMethod error */
6914 GDBusMessage *reply;
6915 reply = g_dbus_message_new_method_error (data->message,
6916 "org.freedesktop.DBus.Error.UnknownMethod",
6917 _("Method '%s' on interface '%s' with signature '%s' does not exist"),
6918 g_dbus_message_get_member (data->message),
6919 g_dbus_message_get_interface (data->message),
6920 g_dbus_message_get_signature (data->message));
6921 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6922 g_object_unref (reply);
6928 /* called in GDBusWorker thread with connection's lock held */
6930 subtree_message_func (GDBusConnection *connection,
6931 ExportedSubtree *es,
6932 GDBusMessage *message)
6934 GSource *idle_source;
6935 SubtreeDeferredData *data;
6937 data = g_new0 (SubtreeDeferredData, 1);
6938 data->message = g_object_ref (message);
6941 /* defer this call to an idle handler in the right thread */
6942 idle_source = g_idle_source_new ();
6943 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
6944 g_source_set_callback (idle_source,
6945 process_subtree_vtable_message_in_idle_cb,
6947 (GDestroyNotify) subtree_deferred_data_free);
6948 g_source_set_name (idle_source, "[gio] process_subtree_vtable_message_in_idle_cb");
6949 g_source_attach (idle_source, es->context);
6950 g_source_unref (idle_source);
6952 /* since we own the entire subtree, handlers for objects not in the subtree have been
6953 * tried already by libdbus-1 - so we just need to ensure that we're always going
6954 * to reply to the message
6960 * g_dbus_connection_register_subtree:
6961 * @connection: a #GDBusConnection
6962 * @object_path: the object path to register the subtree at
6963 * @vtable: a #GDBusSubtreeVTable to enumerate, introspect and
6964 * dispatch nodes in the subtree
6965 * @flags: flags used to fine tune the behavior of the subtree
6966 * @user_data: data to pass to functions in @vtable
6967 * @user_data_free_func: function to call when the subtree is unregistered
6968 * @error: return location for error or %NULL
6970 * Registers a whole subtree of dynamic objects.
6972 * The @enumerate and @introspection functions in @vtable are used to
6973 * convey, to remote callers, what nodes exist in the subtree rooted
6976 * When handling remote calls into any node in the subtree, first the
6977 * @enumerate function is used to check if the node exists. If the node exists
6978 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6979 * the @introspection function is used to check if the node supports the
6980 * requested method. If so, the @dispatch function is used to determine
6981 * where to dispatch the call. The collected #GDBusInterfaceVTable and
6982 * #gpointer will be used to call into the interface vtable for processing
6985 * All calls into user-provided code will be invoked in the
6986 * [thread-default main context][g-main-context-push-thread-default]
6987 * of the thread you are calling this method from.
6989 * If an existing subtree is already registered at @object_path or
6990 * then @error is set to #G_IO_ERROR_EXISTS.
6992 * Note that it is valid to register regular objects (using
6993 * g_dbus_connection_register_object()) in a subtree registered with
6994 * g_dbus_connection_register_subtree() - if so, the subtree handler
6995 * is tried as the last resort. One way to think about a subtree
6996 * handler is to consider it a fallback handler for object paths not
6997 * registered via g_dbus_connection_register_object() or other bindings.
6999 * Note that @vtable will be copied so you cannot change it after
7002 * See this [server][gdbus-subtree-server] for an example of how to use
7005 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
7006 * that can be used with g_dbus_connection_unregister_subtree() .
7011 g_dbus_connection_register_subtree (GDBusConnection *connection,
7012 const gchar *object_path,
7013 const GDBusSubtreeVTable *vtable,
7014 GDBusSubtreeFlags flags,
7016 GDestroyNotify user_data_free_func,
7020 ExportedSubtree *es;
7022 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
7023 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
7024 g_return_val_if_fail (vtable != NULL, 0);
7025 g_return_val_if_fail (error == NULL || *error == NULL, 0);
7026 g_return_val_if_fail (check_initialized (connection), 0);
7030 CONNECTION_LOCK (connection);
7032 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
7038 _("A subtree is already exported for %s"),
7043 es = g_new0 (ExportedSubtree, 1);
7044 es->object_path = g_strdup (object_path);
7045 es->connection = connection;
7047 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
7049 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
7050 es->user_data = user_data;
7051 es->user_data_free_func = user_data_free_func;
7052 es->context = g_main_context_ref_thread_default ();
7054 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
7055 g_hash_table_insert (connection->map_id_to_es,
7056 GUINT_TO_POINTER (es->id),
7062 CONNECTION_UNLOCK (connection);
7067 /* ---------------------------------------------------------------------------------------------------- */
7070 * g_dbus_connection_unregister_subtree:
7071 * @connection: a #GDBusConnection
7072 * @registration_id: a subtree registration id obtained from
7073 * g_dbus_connection_register_subtree()
7075 * Unregisters a subtree.
7077 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise
7082 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
7083 guint registration_id)
7085 ExportedSubtree *es;
7088 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
7089 g_return_val_if_fail (check_initialized (connection), FALSE);
7093 CONNECTION_LOCK (connection);
7095 es = g_hash_table_lookup (connection->map_id_to_es,
7096 GUINT_TO_POINTER (registration_id));
7100 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
7101 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
7106 CONNECTION_UNLOCK (connection);
7111 /* ---------------------------------------------------------------------------------------------------- */
7113 /* may be called in any thread, with connection's lock held */
7115 handle_generic_ping_unlocked (GDBusConnection *connection,
7116 const gchar *object_path,
7117 GDBusMessage *message)
7119 GDBusMessage *reply;
7120 reply = g_dbus_message_new_method_reply (message);
7121 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7122 g_object_unref (reply);
7125 /* may be called in any thread, with connection's lock held */
7127 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
7128 const gchar *object_path,
7129 GDBusMessage *message)
7131 GDBusMessage *reply;
7134 if (connection->machine_id == NULL)
7139 connection->machine_id = _g_dbus_get_machine_id (&error);
7140 if (connection->machine_id == NULL)
7142 reply = g_dbus_message_new_method_error_literal (message,
7143 "org.freedesktop.DBus.Error.Failed",
7145 g_error_free (error);
7151 reply = g_dbus_message_new_method_reply (message);
7152 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
7154 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7155 g_object_unref (reply);
7158 /* may be called in any thread, with connection's lock held */
7160 handle_generic_introspect_unlocked (GDBusConnection *connection,
7161 const gchar *object_path,
7162 GDBusMessage *message)
7167 GDBusMessage *reply;
7169 /* first the header */
7170 s = g_string_new (NULL);
7171 introspect_append_header (s);
7173 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
7174 for (n = 0; registered != NULL && registered[n] != NULL; n++)
7175 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
7176 g_strfreev (registered);
7177 g_string_append (s, "</node>\n");
7179 reply = g_dbus_message_new_method_reply (message);
7180 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
7181 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7182 g_object_unref (reply);
7183 g_string_free (s, TRUE);
7186 /* may be called in any thread, with connection's lock held */
7188 handle_generic_unlocked (GDBusConnection *connection,
7189 GDBusMessage *message)
7192 const gchar *interface_name;
7193 const gchar *member;
7194 const gchar *signature;
7197 CONNECTION_ENSURE_LOCK (connection);
7201 interface_name = g_dbus_message_get_interface (message);
7202 member = g_dbus_message_get_member (message);
7203 signature = g_dbus_message_get_signature (message);
7204 path = g_dbus_message_get_path (message);
7206 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
7207 g_strcmp0 (member, "Introspect") == 0 &&
7208 g_strcmp0 (signature, "") == 0)
7210 handle_generic_introspect_unlocked (connection, path, message);
7213 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7214 g_strcmp0 (member, "Ping") == 0 &&
7215 g_strcmp0 (signature, "") == 0)
7217 handle_generic_ping_unlocked (connection, path, message);
7220 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7221 g_strcmp0 (member, "GetMachineId") == 0 &&
7222 g_strcmp0 (signature, "") == 0)
7224 handle_generic_get_machine_id_unlocked (connection, path, message);
7231 /* ---------------------------------------------------------------------------------------------------- */
7233 /* called in GDBusWorker thread with connection's lock held */
7235 distribute_method_call (GDBusConnection *connection,
7236 GDBusMessage *message)
7238 GDBusMessage *reply;
7240 ExportedSubtree *es;
7241 const gchar *object_path;
7242 const gchar *interface_name;
7243 const gchar *member;
7245 gchar *subtree_path;
7248 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
7250 interface_name = g_dbus_message_get_interface (message);
7251 member = g_dbus_message_get_member (message);
7252 path = g_dbus_message_get_path (message);
7253 subtree_path = g_strdup (path);
7254 needle = strrchr (subtree_path, '/');
7255 if (needle != NULL && needle != subtree_path)
7261 g_free (subtree_path);
7262 subtree_path = NULL;
7266 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
7268 _g_dbus_debug_print_lock ();
7269 g_print ("========================================================================\n"
7270 "GDBus-debug:Incoming:\n"
7271 " <<<< METHOD INVOCATION %s.%s()\n"
7273 " invoked by name %s\n"
7275 interface_name, member,
7277 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
7278 g_dbus_message_get_serial (message));
7279 _g_dbus_debug_print_unlock ();
7282 object_path = g_dbus_message_get_path (message);
7283 g_assert (object_path != NULL);
7285 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
7288 if (obj_message_func (connection, eo, message))
7292 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
7295 if (subtree_message_func (connection, es, message))
7299 if (subtree_path != NULL)
7301 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
7304 if (subtree_message_func (connection, es, message))
7309 if (handle_generic_unlocked (connection, message))
7312 /* if we end up here, the message has not been not handled - so return an error saying this */
7313 reply = g_dbus_message_new_method_error (message,
7314 "org.freedesktop.DBus.Error.UnknownMethod",
7315 _("No such interface '%s' on object at path %s"),
7318 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7319 g_object_unref (reply);
7322 g_free (subtree_path);
7325 /* ---------------------------------------------------------------------------------------------------- */
7327 /* Called in any user thread, with the message_bus_lock held. */
7329 message_bus_get_singleton (GBusType bus_type,
7333 const gchar *starter_bus;
7339 case G_BUS_TYPE_SESSION:
7340 ret = &the_session_bus;
7343 case G_BUS_TYPE_SYSTEM:
7344 ret = &the_system_bus;
7347 case G_BUS_TYPE_STARTER:
7348 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
7349 if (g_strcmp0 (starter_bus, "session") == 0)
7351 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
7354 else if (g_strcmp0 (starter_bus, "system") == 0)
7356 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
7361 if (starter_bus != NULL)
7365 G_IO_ERROR_INVALID_ARGUMENT,
7366 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
7367 " - unknown value '%s'"),
7372 g_set_error_literal (error,
7374 G_IO_ERROR_INVALID_ARGUMENT,
7375 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
7376 "variable is not set"));
7382 g_assert_not_reached ();
7390 /* Called in any user thread, without holding locks. */
7391 static GDBusConnection *
7392 get_uninitialized_connection (GBusType bus_type,
7393 GCancellable *cancellable,
7396 GWeakRef *singleton;
7397 GDBusConnection *ret;
7401 G_LOCK (message_bus_lock);
7402 singleton = message_bus_get_singleton (bus_type, error);
7403 if (singleton == NULL)
7406 ret = g_weak_ref_get (singleton);
7411 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
7412 if (address == NULL)
7414 ret = g_object_new (G_TYPE_DBUS_CONNECTION,
7416 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
7417 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
7418 "exit-on-close", TRUE,
7421 g_weak_ref_set (singleton, ret);
7425 g_assert (ret != NULL);
7428 G_UNLOCK (message_bus_lock);
7432 /* May be called from any thread. Must not hold message_bus_lock. */
7434 _g_bus_get_singleton_if_exists (GBusType bus_type)
7436 GWeakRef *singleton;
7437 GDBusConnection *ret = NULL;
7439 G_LOCK (message_bus_lock);
7440 singleton = message_bus_get_singleton (bus_type, NULL);
7441 if (singleton == NULL)
7444 ret = g_weak_ref_get (singleton);
7447 G_UNLOCK (message_bus_lock);
7453 * @bus_type: a #GBusType
7454 * @cancellable: (allow-none): a #GCancellable or %NULL
7455 * @error: return location for error or %NULL
7457 * Synchronously connects to the message bus specified by @bus_type.
7458 * Note that the returned object may shared with other callers,
7459 * e.g. if two separate parts of a process calls this function with
7460 * the same @bus_type, they will share the same object.
7462 * This is a synchronous failable function. See g_bus_get() and
7463 * g_bus_get_finish() for the asynchronous version.
7465 * The returned object is a singleton, that is, shared with other
7466 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7467 * event that you need a private message bus connection, use
7468 * g_dbus_address_get_for_bus_sync() and
7469 * g_dbus_connection_new_for_address().
7471 * Note that the returned #GDBusConnection object will (usually) have
7472 * the #GDBusConnection:exit-on-close property set to %TRUE.
7474 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7475 * Free with g_object_unref().
7480 g_bus_get_sync (GBusType bus_type,
7481 GCancellable *cancellable,
7484 GDBusConnection *connection;
7486 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7488 connection = get_uninitialized_connection (bus_type, cancellable, error);
7489 if (connection == NULL)
7492 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
7494 g_object_unref (connection);
7503 bus_get_async_initable_cb (GObject *source_object,
7507 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
7511 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
7515 g_assert (error != NULL);
7516 g_simple_async_result_take_error (simple, error);
7517 g_object_unref (source_object);
7521 g_simple_async_result_set_op_res_gpointer (simple,
7525 g_simple_async_result_complete_in_idle (simple);
7526 g_object_unref (simple);
7531 * @bus_type: a #GBusType
7532 * @cancellable: (allow-none): a #GCancellable or %NULL
7533 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
7534 * @user_data: the data to pass to @callback
7536 * Asynchronously connects to the message bus specified by @bus_type.
7538 * When the operation is finished, @callback will be invoked. You can
7539 * then call g_bus_get_finish() to get the result of the operation.
7541 * This is a asynchronous failable function. See g_bus_get_sync() for
7542 * the synchronous version.
7547 g_bus_get (GBusType bus_type,
7548 GCancellable *cancellable,
7549 GAsyncReadyCallback callback,
7552 GDBusConnection *connection;
7553 GSimpleAsyncResult *simple;
7556 simple = g_simple_async_result_new (NULL,
7560 g_simple_async_result_set_check_cancellable (simple, cancellable);
7563 connection = get_uninitialized_connection (bus_type, cancellable, &error);
7564 if (connection == NULL)
7566 g_assert (error != NULL);
7567 g_simple_async_result_take_error (simple, error);
7568 g_simple_async_result_complete_in_idle (simple);
7569 g_object_unref (simple);
7573 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
7576 bus_get_async_initable_cb,
7583 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
7585 * @error: return location for error or %NULL
7587 * Finishes an operation started with g_bus_get().
7589 * The returned object is a singleton, that is, shared with other
7590 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7591 * event that you need a private message bus connection, use
7592 * g_dbus_address_get_for_bus_sync() and
7593 * g_dbus_connection_new_for_address().
7595 * Note that the returned #GDBusConnection object will (usually) have
7596 * the #GDBusConnection:exit-on-close property set to %TRUE.
7598 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7599 * Free with g_object_unref().
7604 g_bus_get_finish (GAsyncResult *res,
7607 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
7609 GDBusConnection *ret;
7611 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7613 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
7617 if (g_simple_async_result_propagate_error (simple, error))
7620 object = g_simple_async_result_get_op_res_gpointer (simple);
7621 g_assert (object != NULL);
7622 ret = g_object_ref (G_DBUS_CONNECTION (object));
7628 /* ---------------------------------------------------------------------------------------------------- */