1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
18 * Author: David Zeuthen <davidz@redhat.com>
24 * - would be nice to expose GDBusAuthMechanism and an extension point
26 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
27 * the mechanism VFuncs need to be able to set an error.
29 * - Need to document other mechanisms/sources for determining the D-Bus
30 * address of a well-known bus.
32 * - e.g. on Win32 we need code like from here
34 * http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
36 * that was never copied over here because it originally was copy-paste
37 * from the GPLv2 / AFL 2.1 libdbus sources.
39 * - on OS X we need to look in launchd for the address
41 * https://bugs.freedesktop.org/show_bug.cgi?id=14259
43 * - on X11 we need to look in a X11 property on the X server
44 * - (we can also just use dbus-launch(1) from the D-Bus
47 * - (ideally) this requires D-Bus spec work because none of
48 * this has never really been specced out properly (except
51 * - Related to the above, we also need to be able to launch a message bus
52 * instance.... Since we don't want to write our own bus daemon we should
53 * launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
55 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
56 * to specify where the nonce is stored. This will allow people to use
57 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
58 * to easily achieve secure RPC via nonce-tcp.
60 * - need to expose an extension point for resolving D-Bus address and
61 * turning them into GIOStream objects. This will allow us to implement
62 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
64 * - see g_dbus_address_connect() in gdbusaddress.c
66 * - would be cute to use kernel-specific APIs to resolve fds for
67 * debug output when using G_DBUS_DEBUG=message, e.g. in addition to
69 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
71 * maybe we can show more information about what fd 21 really is.
72 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
73 * Initial experiments on Linux 2.6 suggests that the symlink looks
78 * e.g. not of much use.
80 * - GDBus High-Level docs
81 * - Proxy: properties, signals...
82 * - Connection: IOStream based, ::close, connection setup steps
83 * mainloop integration, threading
84 * - Differences from libdbus (extend "Migrating from")
85 * - the message handling thread
86 * - Using GVariant instead of GValue
87 * - Explain why the high-level API is a good thing and what
88 * kind of pitfalls it avoids
89 * - Export objects before claiming names
90 * - Talk about auto-starting services (cf. GBusNameWatcherFlags)
92 * - use abstract sockets in test code
93 * - right now it doesn't work, dbus-daemon(1) fails with
95 * /gdbus/connection/filter: Failed to start message bus: Failed to bind
96 * socket "/tmp/g-dbus-tests-pid-28531": Address already in use
97 * ** WARNING **: Error reading address from dbus daemon, 0 bytes read
107 #include "gdbusauth.h"
108 #include "gdbusutils.h"
109 #include "gdbusaddress.h"
110 #include "gdbusmessage.h"
111 #include "gdbusconnection.h"
112 #include "gdbuserror.h"
113 #include "gioenumtypes.h"
114 #include "gdbusintrospection.h"
115 #include "gdbusmethodinvocation.h"
116 #include "gdbusprivate.h"
117 #include "gdbusauthobserver.h"
118 #include "ginitable.h"
119 #include "gasyncinitable.h"
120 #include "giostream.h"
121 #include "gasyncresult.h"
122 #include "gsimpleasyncresult.h"
126 #include "gkdbusconnection.h"
127 #include "gunixconnection.h"
128 #include "gunixfdmessage.h"
131 #include "glibintl.h"
134 * SECTION:gdbusconnection
135 * @short_description: D-Bus Connections
136 * @include: gio/gio.h
138 * The #GDBusConnection type is used for D-Bus connections to remote
139 * peers such as a message buses. It is a low-level API that offers a
140 * lot of flexibility. For instance, it lets you establish a connection
141 * over any transport that can by represented as an #GIOStream.
143 * This class is rarely used directly in D-Bus clients. If you are writing
144 * a D-Bus client, it is often easier to use the g_bus_own_name(),
145 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
147 * As an exception to the usual GLib rule that a particular object must not
148 * be used by two threads at the same time, #GDBusConnection's methods may be
149 * called from any thread. This is so that g_bus_get() and g_bus_get_sync()
150 * can safely return the same #GDBusConnection when called from any thread.
152 * Most of the ways to obtain a #GDBusConnection automatically initialize it
153 * (i.e. connect to D-Bus): for instance, g_dbus_connection_new() and
154 * g_bus_get(), and the synchronous versions of those methods, give you an
155 * initialized connection. Language bindings for GIO should use
156 * g_initable_new() or g_async_initable_new_async(), which also initialize the
159 * If you construct an uninitialized #GDBusConnection, such as via
160 * g_object_new(), you must initialize it via g_initable_init() or
161 * g_async_initable_init_async() before using its methods or properties.
162 * Calling methods or accessing properties on a #GDBusConnection that has not
163 * completed initialization successfully is considered to be invalid, and leads
164 * to undefined behaviour. In particular, if initialization fails with a
165 * #GError, the only valid thing you can do with that #GDBusConnection is to
166 * free it with g_object_unref().
168 * ## An example D-Bus server # {#gdbus-server}
170 * Here is an example for a D-Bus server:
171 * [gdbus-example-server.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-server.c)
173 * ## An example for exporting a subtree # {#gdbus-subtree-server}
175 * Here is an example for exporting a subtree:
176 * [gdbus-example-subtree.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-subtree.c)
178 * ## An example for file descriptor passing # {#gdbus-unix-fd-client}
180 * Here is an example for passing UNIX file descriptors:
181 * [gdbus-unix-fd-client.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-unix-fd-client.c)
183 * ## An example for exporting a GObject # {#gdbus-export}
185 * Here is an example for exporting a #GObject:
186 * [gdbus-example-export.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-export.c)
189 /* ---------------------------------------------------------------------------------------------------- */
191 typedef struct _GDBusConnectionClass GDBusConnectionClass;
194 * GDBusConnectionClass:
195 * @closed: Signal class handler for the #GDBusConnection::closed signal.
197 * Class structure for #GDBusConnection.
201 struct _GDBusConnectionClass
204 GObjectClass parent_class;
208 void (*closed) (GDBusConnection *connection,
209 gboolean remote_peer_vanished,
213 G_LOCK_DEFINE_STATIC (message_bus_lock);
215 static GWeakRef the_session_bus;
216 static GWeakRef the_system_bus;
217 static GWeakRef the_user_bus;
218 static GWeakRef the_machine_bus;
220 /* Extra pseudo-member of GDBusSendMessageFlags.
221 * Set by initable_init() to indicate that despite not being initialized yet,
222 * enough of the only-valid-after-init members are set that we can send a
223 * message, and we're being called from its thread, so no memory barrier is
224 * required before accessing them.
226 #define SEND_MESSAGE_FLAGS_INITIALIZING (1<<31)
228 /* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
229 #define CALL_FLAGS_INITIALIZING (1<<31)
231 /* ---------------------------------------------------------------------------------------------------- */
235 GDestroyNotify callback;
237 GMainContext *context;
238 } CallDestroyNotifyData;
241 call_destroy_notify_data_in_idle (gpointer user_data)
243 CallDestroyNotifyData *data = user_data;
244 data->callback (data->user_data);
249 call_destroy_notify_data_free (CallDestroyNotifyData *data)
251 if (data->context != NULL)
252 g_main_context_unref (data->context);
257 * call_destroy_notify: <internal>
258 * @context: (allow-none): A #GMainContext or %NULL.
259 * @callback: (allow-none): A #GDestroyNotify or %NULL.
260 * @user_data: Data to pass to @callback.
262 * Schedules @callback to run in @context.
265 call_destroy_notify (GMainContext *context,
266 GDestroyNotify callback,
269 GSource *idle_source;
270 CallDestroyNotifyData *data;
272 if (callback == NULL)
275 data = g_new0 (CallDestroyNotifyData, 1);
276 data->callback = callback;
277 data->user_data = user_data;
278 data->context = context;
279 if (data->context != NULL)
280 g_main_context_ref (data->context);
282 idle_source = g_idle_source_new ();
283 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
284 g_source_set_callback (idle_source,
285 call_destroy_notify_data_in_idle,
287 (GDestroyNotify) call_destroy_notify_data_free);
288 g_source_set_name (idle_source, "[gio] call_destroy_notify_data_in_idle");
289 g_source_attach (idle_source, data->context);
290 g_source_unref (idle_source);
296 /* ---------------------------------------------------------------------------------------------------- */
299 _g_strv_has_string (const gchar* const *haystack,
304 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
306 if (g_strcmp0 (haystack[n], needle) == 0)
312 /* ---------------------------------------------------------------------------------------------------- */
315 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
317 // TODO: for some reason this doesn't work on Windows
318 #define CONNECTION_ENSURE_LOCK(obj) do { \
319 if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock))) \
321 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
322 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
327 #define CONNECTION_LOCK(obj) do { \
328 g_mutex_lock (&(obj)->lock); \
331 #define CONNECTION_UNLOCK(obj) do { \
332 g_mutex_unlock (&(obj)->lock); \
335 /* Flags in connection->atomic_flags */
337 FLAG_INITIALIZED = 1 << 0,
338 FLAG_EXIT_ON_CLOSE = 1 << 1,
345 * The #GDBusConnection structure contains only private data and
346 * should only be accessed using the provided API.
350 struct _GDBusConnection
353 GObject parent_instance;
355 /* ------------------------------------------------------------------------ */
356 /* -- General object state ------------------------------------------------ */
357 /* ------------------------------------------------------------------------ */
359 /* General-purpose lock for most fields */
362 /* A lock used in the init() method of the GInitable interface - see comments
363 * in initable_init() for why a separate lock is needed.
365 * If you need both @lock and @init_lock, you must take @init_lock first.
369 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
370 * someone calls org.freedesktop.DBus.Peer.GetMachineId(). Protected by @lock.
374 /* The underlying stream used for communication
375 * Read-only after initable_init(), so it may be read if you either
376 * hold @init_lock or check for initialization first.
380 /* The object used for authentication (if any).
381 * Read-only after initable_init(), so it may be read if you either
382 * hold @init_lock or check for initialization first.
386 /* Last serial used. Protected by @lock. */
389 /* The object used to send/receive messages.
390 * Read-only after initable_init(), so it may be read if you either
391 * hold @init_lock or check for initialization first.
395 /* If connected to a message bus, this contains the unique name assigned to
396 * us by the bus (e.g. ":1.42").
397 * Read-only after initable_init(), so it may be read if you either
398 * hold @init_lock or check for initialization first.
400 gchar *bus_unique_name;
402 /* The GUID returned by the other side if we authenticed as a client or
403 * the GUID to use if authenticating as a server.
404 * Read-only after initable_init(), so it may be read if you either
405 * hold @init_lock or check for initialization first.
409 /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
410 * Inspect @initialization_error to see whether it succeeded or failed.
412 * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
414 * FLAG_CLOSED is the closed property. It may be read at any time, but
415 * may only be written while holding @lock.
417 volatile gint atomic_flags;
419 /* If the connection could not be established during initable_init(),
420 * this GError will be set.
421 * Read-only after initable_init(), so it may be read if you either
422 * hold @init_lock or check for initialization first.
424 GError *initialization_error;
426 /* The result of g_main_context_ref_thread_default() when the object
427 * was created (the GObject _init() function) - this is used for delivery
428 * of the :closed GObject signal.
430 * Only set in the GObject init function, so no locks are needed.
432 GMainContext *main_context_at_construction;
434 /* Read-only construct properties, no locks needed */
436 GDBusConnectionFlags flags;
438 /* Map used for managing method replies, protected by @lock */
439 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
441 /* Maps used for managing signal subscription, protected by @lock */
442 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
443 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
444 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
446 /* Maps used for managing exported objects and subtrees,
449 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
450 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
451 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
452 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
454 /* Map used for storing last used serials for each thread, protected by @lock */
455 GHashTable *map_thread_to_last_serial;
457 /* Structure used for message filters, protected by @lock */
460 /* Capabilities negotiated during authentication
461 * Read-only after initable_init(), so it may be read without holding a
462 * lock, if you check for initialization first.
464 GDBusCapabilityFlags capabilities;
466 /* Protected by @init_lock */
467 GDBusAuthObserver *authentication_observer;
469 /* Read-only after initable_init(), so it may be read if you either
470 * hold @init_lock or check for initialization first.
472 GCredentials *credentials;
474 /* set to TRUE when finalizing */
478 typedef struct ExportedObject ExportedObject;
479 static void exported_object_free (ExportedObject *eo);
481 typedef struct ExportedSubtree ExportedSubtree;
482 static void exported_subtree_free (ExportedSubtree *es);
500 PROP_CAPABILITY_FLAGS,
501 PROP_AUTHENTICATION_OBSERVER,
504 static void distribute_signals (GDBusConnection *connection,
505 GDBusMessage *message);
507 static void distribute_method_call (GDBusConnection *connection,
508 GDBusMessage *message);
510 static gboolean handle_generic_unlocked (GDBusConnection *connection,
511 GDBusMessage *message);
514 static void purge_all_signal_subscriptions (GDBusConnection *connection);
515 static void purge_all_filters (GDBusConnection *connection);
517 static void schedule_method_call (GDBusConnection *connection,
518 GDBusMessage *message,
519 guint registration_id,
520 guint subtree_registration_id,
521 const GDBusInterfaceInfo *interface_info,
522 const GDBusMethodInfo *method_info,
523 const GDBusPropertyInfo *property_info,
524 GVariant *parameters,
525 const GDBusInterfaceVTable *vtable,
526 GMainContext *main_context,
529 #define _G_ENSURE_LOCK(name) do { \
530 if (G_UNLIKELY (G_TRYLOCK(name))) \
532 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
533 "_G_ENSURE_LOCK: Lock '" #name "' is not locked"); \
537 static guint signals[LAST_SIGNAL] = { 0 };
539 static void initable_iface_init (GInitableIface *initable_iface);
540 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
542 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
543 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
544 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
548 * Check that all members of @connection that can only be accessed after
549 * the connection is initialized can safely be accessed. If not,
550 * log a critical warning. This function is a memory barrier.
552 * Returns: %TRUE if initialized
555 check_initialized (GDBusConnection *connection)
557 /* The access to @atomic_flags isn't conditional, so that this function
558 * provides a memory barrier for thread-safety even if checks are disabled.
559 * (If you don't want this stricter guarantee, you can call
560 * g_return_if_fail (check_initialized (c)).)
562 * This isn't strictly necessary now that we've decided use of an
563 * uninitialized GDBusConnection is undefined behaviour, but it seems
564 * better to be as deterministic as is feasible.
566 * (Anything that could suffer a crash from seeing undefined values
567 * must have a race condition - thread A initializes the connection while
568 * thread B calls a method without initialization, hoping that thread A will
569 * win the race - so its behaviour is undefined anyway.)
571 gint flags = g_atomic_int_get (&connection->atomic_flags);
573 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
575 /* We can safely access this, due to the memory barrier above */
576 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
582 MAY_BE_UNINITIALIZED = (1<<1)
583 } CheckUnclosedFlags;
586 * Check the same thing as check_initialized(), and also that the
587 * connection is not closed. If the connection is uninitialized,
588 * raise a critical warning (it's programmer error); if it's closed,
589 * raise a recoverable GError (it's a runtime error).
591 * This function is a memory barrier.
593 * Returns: %TRUE if initialized and not closed
596 check_unclosed (GDBusConnection *connection,
597 CheckUnclosedFlags check,
600 /* check_initialized() is effectively inlined, so we don't waste time
601 * doing two memory barriers
603 gint flags = g_atomic_int_get (&connection->atomic_flags);
605 if (!(check & MAY_BE_UNINITIALIZED))
607 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
608 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
611 if (flags & FLAG_CLOSED)
613 g_set_error_literal (error,
616 _("The connection is closed"));
623 static GHashTable *alive_connections = NULL;
626 g_dbus_connection_dispose (GObject *object)
628 GDBusConnection *connection = G_DBUS_CONNECTION (object);
630 G_LOCK (message_bus_lock);
631 CONNECTION_LOCK (connection);
632 if (connection->worker != NULL)
634 _g_dbus_worker_stop (connection->worker);
635 connection->worker = NULL;
636 if (alive_connections != NULL)
637 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
641 if (alive_connections != NULL)
642 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
644 CONNECTION_UNLOCK (connection);
645 G_UNLOCK (message_bus_lock);
647 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
648 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
652 g_dbus_connection_finalize (GObject *object)
654 GDBusConnection *connection = G_DBUS_CONNECTION (object);
656 connection->finalizing = TRUE;
658 purge_all_signal_subscriptions (connection);
660 purge_all_filters (connection);
661 g_ptr_array_unref (connection->filters);
663 if (connection->authentication_observer != NULL)
664 g_object_unref (connection->authentication_observer);
666 if (connection->auth != NULL)
667 g_object_unref (connection->auth);
669 if (connection->credentials)
670 g_object_unref (connection->credentials);
672 if (connection->stream != NULL)
674 g_object_unref (connection->stream);
675 connection->stream = NULL;
678 g_free (connection->address);
680 g_free (connection->guid);
681 g_free (connection->bus_unique_name);
683 if (connection->initialization_error != NULL)
684 g_error_free (connection->initialization_error);
686 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
688 g_hash_table_unref (connection->map_rule_to_signal_data);
689 g_hash_table_unref (connection->map_id_to_signal_data);
690 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
692 g_hash_table_unref (connection->map_id_to_ei);
693 g_hash_table_unref (connection->map_object_path_to_eo);
694 g_hash_table_unref (connection->map_id_to_es);
695 g_hash_table_unref (connection->map_object_path_to_es);
697 g_hash_table_unref (connection->map_thread_to_last_serial);
699 g_main_context_unref (connection->main_context_at_construction);
701 g_free (connection->machine_id);
703 g_mutex_clear (&connection->init_lock);
704 g_mutex_clear (&connection->lock);
706 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
709 /* called in any user thread, with the connection's lock not held */
711 g_dbus_connection_get_property (GObject *object,
716 GDBusConnection *connection = G_DBUS_CONNECTION (object);
721 g_value_set_object (value, g_dbus_connection_get_stream (connection));
725 g_value_set_string (value, g_dbus_connection_get_guid (connection));
728 case PROP_UNIQUE_NAME:
729 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
733 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
736 case PROP_EXIT_ON_CLOSE:
737 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
740 case PROP_CAPABILITY_FLAGS:
741 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
745 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
750 /* called in any user thread, with the connection's lock not held */
752 g_dbus_connection_set_property (GObject *object,
757 GDBusConnection *connection = G_DBUS_CONNECTION (object);
762 connection->stream = g_value_dup_object (value);
766 connection->guid = g_value_dup_string (value);
770 connection->address = g_value_dup_string (value);
774 connection->flags = g_value_get_flags (value);
777 case PROP_EXIT_ON_CLOSE:
778 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
781 case PROP_AUTHENTICATION_OBSERVER:
782 connection->authentication_observer = g_value_dup_object (value);
786 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
791 /* Base-class implementation of GDBusConnection::closed.
793 * Called in a user thread, by the main context that was thread-default when
794 * the object was constructed.
797 g_dbus_connection_real_closed (GDBusConnection *connection,
798 gboolean remote_peer_vanished,
801 gint flags = g_atomic_int_get (&connection->atomic_flags);
803 /* Because atomic int access is a memory barrier, we can safely read
804 * initialization_error without a lock, as long as we do it afterwards.
806 if (remote_peer_vanished &&
807 (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
808 (flags & FLAG_INITIALIZED) != 0 &&
809 connection->initialization_error == NULL)
813 g_printerr ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
816 g_quark_to_string (error->domain), error->code);
820 g_printerr ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
827 g_dbus_connection_class_init (GDBusConnectionClass *klass)
829 GObjectClass *gobject_class;
831 gobject_class = G_OBJECT_CLASS (klass);
833 gobject_class->finalize = g_dbus_connection_finalize;
834 gobject_class->dispose = g_dbus_connection_dispose;
835 gobject_class->set_property = g_dbus_connection_set_property;
836 gobject_class->get_property = g_dbus_connection_get_property;
838 klass->closed = g_dbus_connection_real_closed;
841 * GDBusConnection:stream:
843 * The underlying #GIOStream used for I/O.
845 * If this is passed on construction and is a #GSocketConnection,
846 * then the corresponding #GSocket will be put into non-blocking mode.
848 * While the #GDBusConnection is active, it will interact with this
849 * stream from a worker thread, so it is not safe to interact with
850 * the stream directly.
854 g_object_class_install_property (gobject_class,
856 g_param_spec_object ("stream",
858 P_("The underlying streams used for I/O"),
862 G_PARAM_CONSTRUCT_ONLY |
863 G_PARAM_STATIC_NAME |
864 G_PARAM_STATIC_BLURB |
865 G_PARAM_STATIC_NICK));
868 * GDBusConnection:address:
870 * A D-Bus address specifying potential endpoints that can be used
871 * when establishing the connection.
875 g_object_class_install_property (gobject_class,
877 g_param_spec_string ("address",
879 P_("D-Bus address specifying potential socket endpoints"),
882 G_PARAM_CONSTRUCT_ONLY |
883 G_PARAM_STATIC_NAME |
884 G_PARAM_STATIC_BLURB |
885 G_PARAM_STATIC_NICK));
888 * GDBusConnection:flags:
890 * Flags from the #GDBusConnectionFlags enumeration.
894 g_object_class_install_property (gobject_class,
896 g_param_spec_flags ("flags",
899 G_TYPE_DBUS_CONNECTION_FLAGS,
900 G_DBUS_CONNECTION_FLAGS_NONE,
902 G_PARAM_CONSTRUCT_ONLY |
903 G_PARAM_STATIC_NAME |
904 G_PARAM_STATIC_BLURB |
905 G_PARAM_STATIC_NICK));
908 * GDBusConnection:guid:
910 * The GUID of the peer performing the role of server when
913 * If you are constructing a #GDBusConnection and pass
914 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
915 * #GDBusConnection:flags property then you MUST also set this
916 * property to a valid guid.
918 * If you are constructing a #GDBusConnection and pass
919 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
920 * #GDBusConnection:flags property you will be able to read the GUID
921 * of the other peer here after the connection has been successfully
926 g_object_class_install_property (gobject_class,
928 g_param_spec_string ("guid",
930 P_("GUID of the server peer"),
934 G_PARAM_CONSTRUCT_ONLY |
935 G_PARAM_STATIC_NAME |
936 G_PARAM_STATIC_BLURB |
937 G_PARAM_STATIC_NICK));
940 * GDBusConnection:unique-name:
942 * The unique name as assigned by the message bus or %NULL if the
943 * connection is not open or not a message bus connection.
947 g_object_class_install_property (gobject_class,
949 g_param_spec_string ("unique-name",
951 P_("Unique name of bus connection"),
954 G_PARAM_STATIC_NAME |
955 G_PARAM_STATIC_BLURB |
956 G_PARAM_STATIC_NICK));
959 * GDBusConnection:closed:
961 * A boolean specifying whether the connection has been closed.
965 g_object_class_install_property (gobject_class,
967 g_param_spec_boolean ("closed",
969 P_("Whether the connection is closed"),
972 G_PARAM_STATIC_NAME |
973 G_PARAM_STATIC_BLURB |
974 G_PARAM_STATIC_NICK));
977 * GDBusConnection:exit-on-close:
979 * A boolean specifying whether the process will be terminated (by
980 * calling `raise(SIGTERM)`) if the connection is closed by the
983 * Note that #GDBusConnection objects returned by g_bus_get_finish()
984 * and g_bus_get_sync() will (usually) have this property set to %TRUE.
988 g_object_class_install_property (gobject_class,
990 g_param_spec_boolean ("exit-on-close",
992 P_("Whether the process is terminated when the connection is closed"),
996 G_PARAM_STATIC_NAME |
997 G_PARAM_STATIC_BLURB |
998 G_PARAM_STATIC_NICK));
1001 * GDBusConnection:capabilities:
1003 * Flags from the #GDBusCapabilityFlags enumeration
1004 * representing connection features negotiated with the other peer.
1008 g_object_class_install_property (gobject_class,
1009 PROP_CAPABILITY_FLAGS,
1010 g_param_spec_flags ("capabilities",
1013 G_TYPE_DBUS_CAPABILITY_FLAGS,
1014 G_DBUS_CAPABILITY_FLAGS_NONE,
1016 G_PARAM_STATIC_NAME |
1017 G_PARAM_STATIC_BLURB |
1018 G_PARAM_STATIC_NICK));
1021 * GDBusConnection:authentication-observer:
1023 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
1027 g_object_class_install_property (gobject_class,
1028 PROP_AUTHENTICATION_OBSERVER,
1029 g_param_spec_object ("authentication-observer",
1030 P_("Authentication Observer"),
1031 P_("Object used to assist in the authentication process"),
1032 G_TYPE_DBUS_AUTH_OBSERVER,
1034 G_PARAM_CONSTRUCT_ONLY |
1035 G_PARAM_STATIC_NAME |
1036 G_PARAM_STATIC_BLURB |
1037 G_PARAM_STATIC_NICK));
1040 * GDBusConnection::closed:
1041 * @connection: the #GDBusConnection emitting the signal
1042 * @remote_peer_vanished: %TRUE if @connection is closed because the
1043 * remote peer closed its end of the connection
1044 * @error: (allow-none): a #GError with more details about the event or %NULL
1046 * Emitted when the connection is closed.
1048 * The cause of this event can be
1050 * - If g_dbus_connection_close() is called. In this case
1051 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
1053 * - If the remote peer closes the connection. In this case
1054 * @remote_peer_vanished is set to %TRUE and @error is set.
1056 * - If the remote peer sends invalid or malformed data. In this
1057 * case @remote_peer_vanished is set to %FALSE and @error is set.
1059 * Upon receiving this signal, you should give up your reference to
1060 * @connection. You are guaranteed that this signal is emitted only
1065 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
1066 G_TYPE_DBUS_CONNECTION,
1068 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1079 g_dbus_connection_init (GDBusConnection *connection)
1081 g_mutex_init (&connection->lock);
1082 g_mutex_init (&connection->init_lock);
1084 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
1086 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1088 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1090 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1093 (GDestroyNotify) g_ptr_array_unref);
1095 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1098 (GDestroyNotify) exported_object_free);
1100 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1103 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1106 (GDestroyNotify) exported_subtree_free);
1108 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1111 connection->map_thread_to_last_serial = g_hash_table_new (g_direct_hash,
1114 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1116 connection->filters = g_ptr_array_new ();
1120 * g_dbus_connection_get_stream:
1121 * @connection: a #GDBusConnection
1123 * Gets the underlying stream used for IO.
1125 * While the #GDBusConnection is active, it will interact with this
1126 * stream from a worker thread, so it is not safe to interact with
1127 * the stream directly.
1129 * Returns: (transfer none): the stream used for IO
1134 g_dbus_connection_get_stream (GDBusConnection *connection)
1136 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1138 /* do not use g_return_val_if_fail(), we want the memory barrier */
1139 if (!check_initialized (connection))
1142 return connection->stream;
1146 * g_dbus_connection_start_message_processing:
1147 * @connection: a #GDBusConnection
1149 * If @connection was created with
1150 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1151 * starts processing messages. Does nothing on if @connection wasn't
1152 * created with this flag or if the method has already been called.
1157 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1159 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1161 /* do not use g_return_val_if_fail(), we want the memory barrier */
1162 if (!check_initialized (connection))
1165 g_assert (connection->worker != NULL);
1166 _g_dbus_worker_unfreeze (connection->worker);
1170 * g_dbus_connection_is_closed:
1171 * @connection: a #GDBusConnection
1173 * Gets whether @connection is closed.
1175 * Returns: %TRUE if the connection is closed, %FALSE otherwise
1180 g_dbus_connection_is_closed (GDBusConnection *connection)
1184 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1186 flags = g_atomic_int_get (&connection->atomic_flags);
1188 return (flags & FLAG_CLOSED) ? TRUE : FALSE;
1192 * g_dbus_connection_get_capabilities:
1193 * @connection: a #GDBusConnection
1195 * Gets the capabilities negotiated with the remote peer
1197 * Returns: zero or more flags from the #GDBusCapabilityFlags enumeration
1201 GDBusCapabilityFlags
1202 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1204 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1206 /* do not use g_return_val_if_fail(), we want the memory barrier */
1207 if (!check_initialized (connection))
1208 return G_DBUS_CAPABILITY_FLAGS_NONE;
1210 return connection->capabilities;
1213 /* ---------------------------------------------------------------------------------------------------- */
1215 /* Called in a temporary thread without holding locks. */
1217 flush_in_thread_func (GSimpleAsyncResult *res,
1219 GCancellable *cancellable)
1224 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1227 g_simple_async_result_take_error (res, error);
1231 * g_dbus_connection_flush:
1232 * @connection: a #GDBusConnection
1233 * @cancellable: (allow-none): a #GCancellable or %NULL
1234 * @callback: (allow-none): a #GAsyncReadyCallback to call when the
1235 * request is satisfied or %NULL if you don't care about the result
1236 * @user_data: The data to pass to @callback
1238 * Asynchronously flushes @connection, that is, writes all queued
1239 * outgoing message to the transport and then flushes the transport
1240 * (using g_output_stream_flush_async()). This is useful in programs
1241 * that wants to emit a D-Bus signal and then exit immediately. Without
1242 * flushing the connection, there is no guaranteed that the message has
1243 * been sent to the networking buffers in the OS kernel.
1245 * This is an asynchronous method. When the operation is finished,
1246 * @callback will be invoked in the
1247 * [thread-default main context][g-main-context-push-thread-default]
1248 * of the thread you are calling this method from. You can
1249 * then call g_dbus_connection_flush_finish() to get the result of the
1250 * operation. See g_dbus_connection_flush_sync() for the synchronous
1256 g_dbus_connection_flush (GDBusConnection *connection,
1257 GCancellable *cancellable,
1258 GAsyncReadyCallback callback,
1261 GSimpleAsyncResult *simple;
1263 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1265 simple = g_simple_async_result_new (G_OBJECT (connection),
1268 g_dbus_connection_flush);
1269 g_simple_async_result_set_check_cancellable (simple, cancellable);
1270 g_simple_async_result_run_in_thread (simple,
1271 flush_in_thread_func,
1274 g_object_unref (simple);
1278 * g_dbus_connection_flush_finish:
1279 * @connection: a #GDBusConnection
1280 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1281 * to g_dbus_connection_flush()
1282 * @error: return location for error or %NULL
1284 * Finishes an operation started with g_dbus_connection_flush().
1286 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1291 g_dbus_connection_flush_finish (GDBusConnection *connection,
1295 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1300 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1301 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1302 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1304 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1306 if (g_simple_async_result_propagate_error (simple, error))
1316 * g_dbus_connection_flush_sync:
1317 * @connection: a #GDBusConnection
1318 * @cancellable: (allow-none): a #GCancellable or %NULL
1319 * @error: return location for error or %NULL
1321 * Synchronously flushes @connection. The calling thread is blocked
1322 * until this is done. See g_dbus_connection_flush() for the
1323 * asynchronous version of this method and more details about what it
1326 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1331 g_dbus_connection_flush_sync (GDBusConnection *connection,
1332 GCancellable *cancellable,
1337 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1338 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1342 /* This is only a best-effort attempt to see whether the connection is
1343 * closed, so it doesn't need the lock. If the connection closes just
1344 * after this check, but before scheduling the flush operation, the
1345 * result will be more or less the same as if the connection closed while
1346 * the flush operation was pending - it'll fail with either CLOSED or
1349 if (!check_unclosed (connection, 0, error))
1352 g_assert (connection->worker != NULL);
1354 ret = _g_dbus_worker_flush_sync (connection->worker,
1362 /* ---------------------------------------------------------------------------------------------------- */
1366 GDBusConnection *connection;
1368 gboolean remote_peer_vanished;
1372 emit_closed_data_free (EmitClosedData *data)
1374 g_object_unref (data->connection);
1375 if (data->error != NULL)
1376 g_error_free (data->error);
1380 /* Called in a user thread that has acquired the main context that was
1381 * thread-default when the object was constructed
1384 emit_closed_in_idle (gpointer user_data)
1386 EmitClosedData *data = user_data;
1389 g_object_notify (G_OBJECT (data->connection), "closed");
1390 g_signal_emit (data->connection,
1391 signals[CLOSED_SIGNAL],
1393 data->remote_peer_vanished,
1399 /* Can be called from any thread, must hold lock.
1400 * FLAG_CLOSED must already have been set.
1403 schedule_closed_unlocked (GDBusConnection *connection,
1404 gboolean remote_peer_vanished,
1407 GSource *idle_source;
1408 EmitClosedData *data;
1410 CONNECTION_ENSURE_LOCK (connection);
1412 data = g_new0 (EmitClosedData, 1);
1413 data->connection = g_object_ref (connection);
1414 data->remote_peer_vanished = remote_peer_vanished;
1415 data->error = error != NULL ? g_error_copy (error) : NULL;
1417 idle_source = g_idle_source_new ();
1418 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1419 g_source_set_callback (idle_source,
1420 emit_closed_in_idle,
1422 (GDestroyNotify) emit_closed_data_free);
1423 g_source_set_name (idle_source, "[gio] emit_closed_in_idle");
1424 g_source_attach (idle_source, connection->main_context_at_construction);
1425 g_source_unref (idle_source);
1428 /* ---------------------------------------------------------------------------------------------------- */
1431 * g_dbus_connection_close:
1432 * @connection: a #GDBusConnection
1433 * @cancellable: (allow-none): a #GCancellable or %NULL
1434 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request is
1435 * satisfied or %NULL if you don't care about the result
1436 * @user_data: The data to pass to @callback
1438 * Closes @connection. Note that this never causes the process to
1439 * exit (this might only happen if the other end of a shared message
1440 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1442 * Once the connection is closed, operations such as sending a message
1443 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1444 * will not automatically flush the connection so queued messages may
1445 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1447 * If @connection is already closed, this method fails with
1448 * %G_IO_ERROR_CLOSED.
1450 * When @connection has been closed, the #GDBusConnection::closed
1451 * signal is emitted in the
1452 * [thread-default main context][g-main-context-push-thread-default]
1453 * of the thread that @connection was constructed in.
1455 * This is an asynchronous method. When the operation is finished,
1456 * @callback will be invoked in the
1457 * [thread-default main context][g-main-context-push-thread-default]
1458 * of the thread you are calling this method from. You can
1459 * then call g_dbus_connection_close_finish() to get the result of the
1460 * operation. See g_dbus_connection_close_sync() for the synchronous
1466 g_dbus_connection_close (GDBusConnection *connection,
1467 GCancellable *cancellable,
1468 GAsyncReadyCallback callback,
1471 GSimpleAsyncResult *simple;
1473 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1475 /* do not use g_return_val_if_fail(), we want the memory barrier */
1476 if (!check_initialized (connection))
1479 g_assert (connection->worker != NULL);
1481 simple = g_simple_async_result_new (G_OBJECT (connection),
1484 g_dbus_connection_close);
1485 g_simple_async_result_set_check_cancellable (simple, cancellable);
1486 _g_dbus_worker_close (connection->worker, cancellable, simple);
1487 g_object_unref (simple);
1491 * g_dbus_connection_close_finish:
1492 * @connection: a #GDBusConnection
1493 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1494 * to g_dbus_connection_close()
1495 * @error: return location for error or %NULL
1497 * Finishes an operation started with g_dbus_connection_close().
1499 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1504 g_dbus_connection_close_finish (GDBusConnection *connection,
1508 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1513 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1514 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1515 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1517 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1519 if (g_simple_async_result_propagate_error (simple, error))
1530 GAsyncResult *result;
1533 /* Can be called by any thread, without the connection lock */
1535 sync_close_cb (GObject *source_object,
1539 SyncCloseData *data = user_data;
1541 data->result = g_object_ref (res);
1542 g_main_loop_quit (data->loop);
1546 * g_dbus_connection_close_sync:
1547 * @connection: a #GDBusConnection
1548 * @cancellable: (allow-none): a #GCancellable or %NULL
1549 * @error: return location for error or %NULL
1551 * Synchronously closees @connection. The calling thread is blocked
1552 * until this is done. See g_dbus_connection_close() for the
1553 * asynchronous version of this method and more details about what it
1556 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1561 g_dbus_connection_close_sync (GDBusConnection *connection,
1562 GCancellable *cancellable,
1567 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1568 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1572 if (check_unclosed (connection, 0, error))
1574 GMainContext *context;
1577 context = g_main_context_new ();
1578 g_main_context_push_thread_default (context);
1579 data.loop = g_main_loop_new (context, TRUE);
1582 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1583 g_main_loop_run (data.loop);
1584 ret = g_dbus_connection_close_finish (connection, data.result, error);
1586 g_object_unref (data.result);
1587 g_main_loop_unref (data.loop);
1588 g_main_context_pop_thread_default (context);
1589 g_main_context_unref (context);
1595 /* ---------------------------------------------------------------------------------------------------- */
1598 * g_dbus_get_bus_id:
1599 * @connection: a #GDBusConnection
1600 * @error: return location for error or %NULL
1602 * Synchronously returns the unique ID of the bus.
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,
1618 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1619 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1624 if (G_IS_KDBUS_CONNECTION (connection->stream))
1626 result = _g_kdbus_GetBusId (connection, error);
1630 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1631 "org.freedesktop.DBus", "GetId",
1632 NULL, G_VARIANT_TYPE ("(s)"),
1633 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1638 g_variant_get (result, "(s)", &bus_id);
1639 g_variant_unref (result);
1648 LIST_ACTIVATABLE_NAMES,
1650 } GDBusListNameType;
1653 _g_dbus_get_list_internal (GDBusConnection *connection,
1655 GDBusListNameType list_name_type,
1667 if (list_name_type == LIST_QUEUED_OWNERS)
1669 if (G_IS_KDBUS_CONNECTION (connection->stream))
1670 result = _g_kdbus_GetListQueuedOwners (connection, name, error);
1672 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1673 "org.freedesktop.DBus", "ListQueuedOwners",
1674 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(as)"),
1675 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1681 if (list_name_type == LIST_NAMES)
1682 method_name = "ListNames";
1684 method_name = "ListActivatableNames";
1686 if (G_IS_KDBUS_CONNECTION (connection->stream))
1687 result = _g_kdbus_GetListNames (connection, list_name_type, error);
1689 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1690 "org.freedesktop.DBus", method_name,
1691 NULL, G_VARIANT_TYPE ("(as)"),
1692 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1697 g_variant_get (result, "(as)", &iter);
1698 n = g_variant_iter_n_children (iter);
1699 strv = g_new (gchar *, n + 1);
1702 while (g_variant_iter_loop (iter, "s", &str))
1704 strv[i] = g_strdup (str);
1709 g_variant_iter_free (iter);
1710 g_variant_unref (result);
1717 * g_dbus_get_list_names:
1718 * @connection: a #GDBusConnection
1719 * @error: return location for error or %NULL
1721 * Synchronously returns a list of all currently-owned names on the bus.
1723 * The calling thread is blocked until a reply is received.
1725 * Returns: a list of all currently-owned names on the bus or %NULL if
1726 * @error is set. Free with g_strfreev().
1731 g_dbus_get_list_names (GDBusConnection *connection,
1736 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1737 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1739 strv = _g_dbus_get_list_internal (connection, NULL, LIST_NAMES, error);
1745 * g_dbus_get_list_activatable_names:
1746 * @connection: a #GDBusConnection
1747 * @error: return location for error or %NULL
1749 * Synchronously returns a list of all names that can be activated on the bus.
1751 * The calling thread is blocked until a reply is received.
1753 * Returns: a list of all names that can be activated on the bus or %NULL if
1754 * @error is set. Free with g_strfreev().
1759 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 (error == NULL || *error == NULL, NULL);
1767 strv = _g_dbus_get_list_internal (connection, NULL, LIST_ACTIVATABLE_NAMES, error);
1773 * g_dbus_get_list_queued_names:
1774 * @connection: a #GDBusConnection
1775 * @name: a unique or well-known bus name
1776 * @error: return location for error or %NULL
1778 * Synchronously returns the unique bus names of connections currently queued
1781 * If @name contains a value not compatible with the D-Bus syntax and naming
1782 * conventions for bus names, the operation returns %NULL and @error is set.
1784 * The calling thread is blocked until a reply is received.
1786 * Returns: the unique bus names of connections currently queued for the @name
1787 * or %NULL if @error is set. Free with g_strfreev().
1792 g_dbus_get_list_queued_owners (GDBusConnection *connection,
1798 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1799 g_return_val_if_fail (name == NULL || g_dbus_is_name (name), NULL);
1800 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1802 strv = _g_dbus_get_list_internal (connection, name, LIST_QUEUED_OWNERS, error);
1808 * g_dbus_get_name_owner:
1809 * @connection: a #GDBusConnection
1810 * @name: well-known bus name to get the owner of
1811 * @error: return location for error or %NULL
1813 * Synchronously returns the unique connection name of the primary owner of
1814 * the name given. If the requested name doesn't have an owner, an @error is
1817 * If @name contains a value not compatible with the D-Bus syntax and naming
1818 * conventions for bus names, the operation returns %NULL and @error is set.
1820 * The calling thread is blocked until a reply is received.
1822 * Returns: the unique connection name of the primary owner of the
1823 * name given. If the requested name doesn't have an owner, function
1824 * returns %NULL and @error is set. Free with g_free().
1829 g_dbus_get_name_owner (GDBusConnection *connection,
1836 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1837 g_return_val_if_fail (name == NULL || g_dbus_is_name (name), NULL);
1838 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1843 if (G_IS_KDBUS_CONNECTION (connection->stream))
1844 result = _g_kdbus_GetNameOwner (connection, name, error);
1846 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1847 "org.freedesktop.DBus", "GetNameOwner",
1848 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(s)"),
1849 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1852 g_variant_get (result, "(s)", &name_owner);
1853 g_variant_unref (result);
1862 * g_dbus_name_has_owner:
1863 * @connection: a #GDBusConnection
1864 * @name: a unique or well-known bus name
1865 * @error: return location for error or %NULL
1867 * Synchronously checks if the specified name exists (currently has an owner).
1869 * If @name contains a value not compatible with the D-Bus syntax and naming
1870 * conventions for bus names, the operation returns %NULL and @error is set.
1872 * The calling thread is blocked until a reply is received.
1874 * Returns: %TRUE if specified name exists (currently has an owner)
1875 * If the requested name doesn't have an owner or @error is set,
1876 * function returns %FALSE.
1881 g_dbus_name_has_owner (GDBusConnection *connection,
1888 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1889 g_return_val_if_fail (name == NULL || g_dbus_is_name (name), NULL);
1890 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1894 if (G_IS_KDBUS_CONNECTION (connection->stream))
1895 result = _g_kdbus_NameHasOwner (connection, name, error);
1897 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1898 "org.freedesktop.DBus", "NameHasOwner",
1899 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(b)"),
1900 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1903 g_variant_get (result, "(b)", &ret);
1904 g_variant_unref (result);
1913 * g_dbus_get_connection_pid:
1914 * @connection: a #GDBusConnection
1915 * @name: a unique or well-known bus name of the connection to query
1916 * @error: return location for error or %NULL
1918 * Synchronously returns the Unix process ID of the process connected to the
1919 * bus. If unable to determine it, an @error is returned.
1921 * If @name contains a value not compatible with the D-Bus syntax and naming
1922 * conventions for bus names, the operation returns (guint32) -1 and @error
1925 * The calling thread is blocked until a reply is received.
1927 * Returns: the Unix process ID of the process connected to the bus or
1928 * (guint32) -1 if @error is set.
1933 g_dbus_get_connection_pid (GDBusConnection *connection,
1940 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), -1);
1941 g_return_val_if_fail (name == NULL || g_dbus_is_name (name), -1);
1942 g_return_val_if_fail (error == NULL || *error == NULL, -1);
1947 if (G_IS_KDBUS_CONNECTION (connection->stream))
1948 result = _g_kdbus_GetConnectionUnixProcessID (connection, name, error);
1950 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1951 "org.freedesktop.DBus", "GetConnectionUnixProcessID",
1952 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(u)"),
1953 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1956 g_variant_get (result, "(u)", &pid);
1957 g_variant_unref (result);
1964 * g_dbus_get_connection_uid:
1965 * @connection: a #GDBusConnection
1966 * @name: a unique or well-known bus name of the connection to query
1967 * @error: return location for error or %NULL
1969 * Synchronously returns the Unix user ID of the process connected to the
1970 * bus. If unable to determine it, an @error is returned.
1972 * If @name contains a value not compatible with the D-Bus syntax and naming
1973 * conventions for bus names, the operation returns (guint32) -1 and @error
1976 * The calling thread is blocked until a reply is received.
1978 * Returns: the Unix user ID of the process connected to the bus or
1979 * (guint32) -1 if @error is set.
1984 g_dbus_get_connection_uid (GDBusConnection *connection,
1991 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), -1);
1992 g_return_val_if_fail (name == NULL || g_dbus_is_name (name), -1);
1993 g_return_val_if_fail (error == NULL || *error == NULL, -1);
1998 if (G_IS_KDBUS_CONNECTION (connection->stream))
1999 result = _g_kdbus_GetConnectionUnixUser (connection, name, error);
2001 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
2002 "org.freedesktop.DBus", "GetConnectionUnixUser",
2003 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(u)"),
2004 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
2007 g_variant_get (result, "(u)", &uid);
2008 g_variant_unref (result);
2014 /* ---------------------------------------------------------------------------------------------------- */
2017 * g_dbus_connection_get_last_serial:
2018 * @connection: a #GDBusConnection
2020 * Retrieves the last serial number assigned to a #GDBusMessage on
2021 * the current thread. This includes messages sent via both low-level
2022 * API such as g_dbus_connection_send_message() as well as
2023 * high-level API such as g_dbus_connection_emit_signal(),
2024 * g_dbus_connection_call() or g_dbus_proxy_call().
2026 * Returns: the last used serial or zero when no message has been sent
2027 * within the current thread
2032 g_dbus_connection_get_last_serial (GDBusConnection *connection)
2036 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2038 CONNECTION_LOCK (connection);
2039 ret = GPOINTER_TO_UINT (g_hash_table_lookup (connection->map_thread_to_last_serial,
2041 CONNECTION_UNLOCK (connection);
2046 /* ---------------------------------------------------------------------------------------------------- */
2048 /* Can be called by any thread, with the connection lock held */
2050 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
2051 GDBusMessage *message,
2052 GDBusSendMessageFlags flags,
2053 volatile guint32 *out_serial,
2058 guint32 serial_to_use;
2061 CONNECTION_ENSURE_LOCK (connection);
2063 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2064 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
2066 /* TODO: check all necessary headers are present */
2071 if (out_serial != NULL)
2074 /* If we're in initable_init(), don't check for being initialized, to avoid
2075 * chicken-and-egg problems. initable_init() is responsible for setting up
2076 * our prerequisites (mainly connection->worker), and only calling us
2077 * from its own thread (so no memory barrier is needed).
2079 if (!check_unclosed (connection,
2080 (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
2084 blob = g_dbus_message_to_blob (message,
2086 connection->capabilities,
2091 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
2092 serial_to_use = g_dbus_message_get_serial (message);
2094 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
2099 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
2102 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
2105 g_assert_not_reached ();
2110 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
2111 blob_size, serial_to_use, connection);
2112 g_printerr ("----\n");
2113 hexdump (blob, blob_size);
2114 g_printerr ("----\n");
2117 /* TODO: use connection->auth to encode the blob */
2119 if (out_serial != NULL)
2120 *out_serial = serial_to_use;
2122 /* store used serial for the current thread */
2123 /* TODO: watch the thread disposal and remove associated record
2125 * - see https://bugzilla.gnome.org/show_bug.cgi?id=676825#c7
2127 g_hash_table_replace (connection->map_thread_to_last_serial,
2129 GUINT_TO_POINTER (serial_to_use));
2131 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
2132 g_dbus_message_set_serial (message, serial_to_use);
2134 g_dbus_message_lock (message);
2135 _g_dbus_worker_send_message (connection->worker,
2139 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
2150 * g_dbus_connection_send_message:
2151 * @connection: a #GDBusConnection
2152 * @message: a #GDBusMessage
2153 * @flags: flags affecting how the message is sent
2154 * @out_serial: (out) (allow-none): return location for serial number assigned
2155 * to @message when sending it or %NULL
2156 * @error: Return location for error or %NULL
2158 * Asynchronously sends @message to the peer represented by @connection.
2160 * Unless @flags contain the
2161 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2162 * will be assigned by @connection and set on @message via
2163 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2164 * serial number used will be written to this location prior to
2165 * submitting the message to the underlying transport.
2167 * If @connection is closed then the operation will fail with
2168 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
2169 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2171 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2172 * for an example of how to use this low-level API to send and receive
2173 * UNIX file descriptors.
2175 * Note that @message must be unlocked, unless @flags contain the
2176 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2178 * Returns: %TRUE if the message was well-formed and queued for
2179 * transmission, %FALSE if @error is set
2184 g_dbus_connection_send_message (GDBusConnection *connection,
2185 GDBusMessage *message,
2186 GDBusSendMessageFlags flags,
2187 volatile guint32 *out_serial,
2192 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2193 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
2194 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
2195 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2197 CONNECTION_LOCK (connection);
2198 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
2199 CONNECTION_UNLOCK (connection);
2203 /* ---------------------------------------------------------------------------------------------------- */
2207 volatile gint ref_count;
2208 GDBusConnection *connection;
2210 GSimpleAsyncResult *simple;
2212 GMainContext *main_context;
2214 GCancellable *cancellable;
2216 gulong cancellable_handler_id;
2218 GSource *timeout_source;
2223 /* Can be called from any thread with or without lock held */
2224 static SendMessageData *
2225 send_message_data_ref (SendMessageData *data)
2227 g_atomic_int_inc (&data->ref_count);
2231 /* Can be called from any thread with or without lock held */
2233 send_message_data_unref (SendMessageData *data)
2235 if (g_atomic_int_dec_and_test (&data->ref_count))
2237 g_assert (data->timeout_source == NULL);
2238 g_assert (data->simple == NULL);
2239 g_assert (data->cancellable_handler_id == 0);
2240 g_object_unref (data->connection);
2241 if (data->cancellable != NULL)
2242 g_object_unref (data->cancellable);
2243 g_main_context_unref (data->main_context);
2248 /* ---------------------------------------------------------------------------------------------------- */
2250 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
2252 send_message_with_reply_deliver (SendMessageData *data, gboolean remove)
2254 CONNECTION_ENSURE_LOCK (data->connection);
2256 g_assert (!data->delivered);
2258 data->delivered = TRUE;
2260 g_simple_async_result_complete_in_idle (data->simple);
2261 g_object_unref (data->simple);
2262 data->simple = NULL;
2264 if (data->timeout_source != NULL)
2266 g_source_destroy (data->timeout_source);
2267 data->timeout_source = NULL;
2269 if (data->cancellable_handler_id > 0)
2271 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
2272 data->cancellable_handler_id = 0;
2277 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
2278 GUINT_TO_POINTER (data->serial)));
2281 send_message_data_unref (data);
2284 /* ---------------------------------------------------------------------------------------------------- */
2286 /* Can be called from any thread with lock held */
2288 send_message_data_deliver_reply_unlocked (SendMessageData *data,
2289 GDBusMessage *reply)
2291 if (data->delivered)
2294 g_simple_async_result_set_op_res_gpointer (data->simple,
2295 g_object_ref (reply),
2298 send_message_with_reply_deliver (data, TRUE);
2304 /* ---------------------------------------------------------------------------------------------------- */
2306 /* Called from a user thread, lock is not held */
2308 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
2310 SendMessageData *data = user_data;
2312 CONNECTION_LOCK (data->connection);
2313 if (data->delivered)
2316 g_simple_async_result_set_error (data->simple,
2318 G_IO_ERROR_CANCELLED,
2319 _("Operation was cancelled"));
2321 send_message_with_reply_deliver (data, TRUE);
2324 CONNECTION_UNLOCK (data->connection);
2328 /* Can be called from any thread with or without lock held */
2330 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
2333 SendMessageData *data = user_data;
2334 GSource *idle_source;
2336 /* postpone cancellation to idle handler since we may be called directly
2337 * via g_cancellable_connect() (e.g. holding lock)
2339 idle_source = g_idle_source_new ();
2340 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
2341 g_source_set_callback (idle_source,
2342 send_message_with_reply_cancelled_idle_cb,
2343 send_message_data_ref (data),
2344 (GDestroyNotify) send_message_data_unref);
2345 g_source_set_name (idle_source, "[gio] send_message_with_reply_cancelled_idle_cb");
2346 g_source_attach (idle_source, data->main_context);
2347 g_source_unref (idle_source);
2350 /* ---------------------------------------------------------------------------------------------------- */
2352 /* Called from a user thread, lock is not held */
2354 send_message_with_reply_timeout_cb (gpointer user_data)
2356 SendMessageData *data = user_data;
2358 CONNECTION_LOCK (data->connection);
2359 if (data->delivered)
2362 g_simple_async_result_set_error (data->simple,
2364 G_IO_ERROR_TIMED_OUT,
2365 _("Timeout was reached"));
2367 send_message_with_reply_deliver (data, TRUE);
2370 CONNECTION_UNLOCK (data->connection);
2375 /* ---------------------------------------------------------------------------------------------------- */
2377 /* Called from a user thread, connection's lock is held */
2379 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
2380 GDBusMessage *message,
2381 GDBusSendMessageFlags flags,
2383 volatile guint32 *out_serial,
2384 GCancellable *cancellable,
2385 GAsyncReadyCallback callback,
2388 GSimpleAsyncResult *simple;
2389 SendMessageData *data;
2391 volatile guint32 serial;
2395 if (out_serial == NULL)
2396 out_serial = &serial;
2398 if (timeout_msec == -1)
2399 timeout_msec = 25 * 1000;
2401 simple = g_simple_async_result_new (G_OBJECT (connection),
2404 g_dbus_connection_send_message_with_reply);
2405 g_simple_async_result_set_check_cancellable (simple, cancellable);
2407 if (g_cancellable_is_cancelled (cancellable))
2409 g_simple_async_result_set_error (simple,
2411 G_IO_ERROR_CANCELLED,
2412 _("Operation was cancelled"));
2413 g_simple_async_result_complete_in_idle (simple);
2414 g_object_unref (simple);
2419 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
2421 g_simple_async_result_take_error (simple, error);
2422 g_simple_async_result_complete_in_idle (simple);
2423 g_object_unref (simple);
2427 data = g_new0 (SendMessageData, 1);
2428 data->ref_count = 1;
2429 data->connection = g_object_ref (connection);
2430 data->simple = simple;
2431 data->serial = *out_serial;
2432 data->main_context = g_main_context_ref_thread_default ();
2434 if (cancellable != NULL)
2436 data->cancellable = g_object_ref (cancellable);
2437 data->cancellable_handler_id = g_cancellable_connect (cancellable,
2438 G_CALLBACK (send_message_with_reply_cancelled_cb),
2439 send_message_data_ref (data),
2440 (GDestroyNotify) send_message_data_unref);
2443 if (timeout_msec != G_MAXINT)
2445 data->timeout_source = g_timeout_source_new (timeout_msec);
2446 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
2447 g_source_set_callback (data->timeout_source,
2448 send_message_with_reply_timeout_cb,
2449 send_message_data_ref (data),
2450 (GDestroyNotify) send_message_data_unref);
2451 g_source_attach (data->timeout_source, data->main_context);
2452 g_source_unref (data->timeout_source);
2455 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
2456 GUINT_TO_POINTER (*out_serial),
2464 * g_dbus_connection_send_message_with_reply:
2465 * @connection: a #GDBusConnection
2466 * @message: a #GDBusMessage
2467 * @flags: flags affecting how the message is sent
2468 * @timeout_msec: the timeout in milliseconds, -1 to use the default
2469 * timeout or %G_MAXINT for no timeout
2470 * @out_serial: (out) (allow-none): return location for serial number assigned
2471 * to @message when sending it or %NULL
2472 * @cancellable: (allow-none): a #GCancellable or %NULL
2473 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request
2474 * is satisfied or %NULL if you don't care about the result
2475 * @user_data: The data to pass to @callback
2477 * Asynchronously sends @message to the peer represented by @connection.
2479 * Unless @flags contain the
2480 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2481 * will be assigned by @connection and set on @message via
2482 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2483 * serial number used will be written to this location prior to
2484 * submitting the message to the underlying transport.
2486 * If @connection is closed then the operation will fail with
2487 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2488 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2489 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2491 * This is an asynchronous method. When the operation is finished, @callback
2492 * will be invoked in the
2493 * [thread-default main context][g-main-context-push-thread-default]
2494 * of the thread you are calling this method from. You can then call
2495 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
2496 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
2498 * Note that @message must be unlocked, unless @flags contain the
2499 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2501 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2502 * for an example of how to use this low-level API to send and receive
2503 * UNIX file descriptors.
2508 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
2509 GDBusMessage *message,
2510 GDBusSendMessageFlags flags,
2512 volatile guint32 *out_serial,
2513 GCancellable *cancellable,
2514 GAsyncReadyCallback callback,
2517 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2518 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2519 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2520 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2522 CONNECTION_LOCK (connection);
2523 g_dbus_connection_send_message_with_reply_unlocked (connection,
2531 CONNECTION_UNLOCK (connection);
2535 * g_dbus_connection_send_message_with_reply_finish:
2536 * @connection: a #GDBusConnection
2537 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
2538 * g_dbus_connection_send_message_with_reply()
2539 * @error: teturn location for error or %NULL
2541 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2543 * Note that @error is only set if a local in-process error
2544 * occurred. That is to say that the returned #GDBusMessage object may
2545 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2546 * g_dbus_message_to_gerror() to transcode this to a #GError.
2548 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2549 * for an example of how to use this low-level API to send and receive
2550 * UNIX file descriptors.
2552 * Returns: (transfer full): a locked #GDBusMessage or %NULL if @error is set
2557 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2561 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2562 GDBusMessage *reply;
2564 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2565 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2569 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
2571 if (g_simple_async_result_propagate_error (simple, error))
2574 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
2580 /* ---------------------------------------------------------------------------------------------------- */
2585 GMainContext *context;
2587 } SendMessageSyncData;
2589 /* Called from a user thread, lock is not held */
2591 send_message_with_reply_sync_cb (GDBusConnection *connection,
2595 SendMessageSyncData *data = user_data;
2596 data->res = g_object_ref (res);
2597 g_main_loop_quit (data->loop);
2601 * g_dbus_connection_send_message_with_reply_sync:
2602 * @connection: a #GDBusConnection
2603 * @message: a #GDBusMessage
2604 * @flags: flags affecting how the message is sent.
2605 * @timeout_msec: the timeout in milliseconds, -1 to use the default
2606 * timeout or %G_MAXINT for no timeout
2607 * @out_serial: (out) (allow-none): return location for serial number
2608 * assigned to @message when sending it or %NULL
2609 * @cancellable: (allow-none): a #GCancellable or %NULL
2610 * @error: return location for error or %NULL
2612 * Synchronously sends @message to the peer represented by @connection
2613 * and blocks the calling thread until a reply is received or the
2614 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2615 * for the asynchronous version of this method.
2617 * Unless @flags contain the
2618 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2619 * will be assigned by @connection and set on @message via
2620 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2621 * serial number used will be written to this location prior to
2622 * submitting the message to the underlying transport.
2624 * If @connection is closed then the operation will fail with
2625 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2626 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2627 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2629 * Note that @error is only set if a local in-process error
2630 * occurred. That is to say that the returned #GDBusMessage object may
2631 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2632 * g_dbus_message_to_gerror() to transcode this to a #GError.
2634 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2635 * for an example of how to use this low-level API to send and receive
2636 * UNIX file descriptors.
2638 * Note that @message must be unlocked, unless @flags contain the
2639 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2641 * Returns: (transfer full): a locked #GDBusMessage that is the reply
2642 * to @message or %NULL if @error is set
2647 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2648 GDBusMessage *message,
2649 GDBusSendMessageFlags flags,
2651 volatile guint32 *out_serial,
2652 GCancellable *cancellable,
2655 SendMessageSyncData *data;
2656 GDBusMessage *reply;
2658 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2659 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2660 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2661 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2662 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2664 data = g_new0 (SendMessageSyncData, 1);
2665 data->context = g_main_context_new ();
2666 data->loop = g_main_loop_new (data->context, FALSE);
2668 g_main_context_push_thread_default (data->context);
2670 g_dbus_connection_send_message_with_reply (connection,
2676 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2678 g_main_loop_run (data->loop);
2679 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2683 g_main_context_pop_thread_default (data->context);
2685 g_main_context_unref (data->context);
2686 g_main_loop_unref (data->loop);
2687 g_object_unref (data->res);
2693 /* ---------------------------------------------------------------------------------------------------- */
2697 GDBusMessageFilterFunction func;
2704 GDBusMessageFilterFunction filter_function;
2706 GDestroyNotify user_data_free_func;
2709 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2711 on_worker_message_received (GDBusWorker *worker,
2712 GDBusMessage *message,
2715 GDBusConnection *connection;
2716 FilterCallback *filters;
2721 G_LOCK (message_bus_lock);
2722 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2725 G_UNLOCK (message_bus_lock);
2728 connection = G_DBUS_CONNECTION (user_data);
2729 g_object_ref (connection);
2730 G_UNLOCK (message_bus_lock);
2732 //g_debug ("in on_worker_message_received");
2734 g_object_ref (message);
2735 g_dbus_message_lock (message);
2737 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2739 /* First collect the set of callback functions */
2740 CONNECTION_LOCK (connection);
2741 num_filters = connection->filters->len;
2742 filters = g_new0 (FilterCallback, num_filters);
2743 for (n = 0; n < num_filters; n++)
2745 FilterData *data = connection->filters->pdata[n];
2746 filters[n].func = data->filter_function;
2747 filters[n].user_data = data->user_data;
2749 CONNECTION_UNLOCK (connection);
2751 /* then call the filters in order (without holding the lock) */
2752 for (n = 0; n < num_filters; n++)
2754 message = filters[n].func (connection,
2757 filters[n].user_data);
2758 if (message == NULL)
2760 g_dbus_message_lock (message);
2763 /* Standard dispatch unless the filter ate the message - no need to
2764 * do anything if the message was altered
2766 if (message != NULL)
2768 GDBusMessageType message_type;
2770 message_type = g_dbus_message_get_message_type (message);
2771 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2773 guint32 reply_serial;
2774 SendMessageData *send_message_data;
2776 reply_serial = g_dbus_message_get_reply_serial (message);
2777 CONNECTION_LOCK (connection);
2778 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2779 GUINT_TO_POINTER (reply_serial));
2780 if (send_message_data != NULL)
2782 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2783 send_message_data_deliver_reply_unlocked (send_message_data, message);
2787 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2789 CONNECTION_UNLOCK (connection);
2791 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2793 CONNECTION_LOCK (connection);
2794 distribute_signals (connection, message);
2795 CONNECTION_UNLOCK (connection);
2797 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2799 CONNECTION_LOCK (connection);
2800 distribute_method_call (connection, message);
2801 CONNECTION_UNLOCK (connection);
2805 if (message != NULL)
2806 g_object_unref (message);
2807 g_object_unref (connection);
2811 /* Called in GDBusWorker's thread, lock is not held */
2812 static GDBusMessage *
2813 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2814 GDBusMessage *message,
2817 GDBusConnection *connection;
2818 FilterCallback *filters;
2823 G_LOCK (message_bus_lock);
2824 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2827 G_UNLOCK (message_bus_lock);
2830 connection = G_DBUS_CONNECTION (user_data);
2831 g_object_ref (connection);
2832 G_UNLOCK (message_bus_lock);
2834 //g_debug ("in on_worker_message_about_to_be_sent");
2836 /* First collect the set of callback functions */
2837 CONNECTION_LOCK (connection);
2838 num_filters = connection->filters->len;
2839 filters = g_new0 (FilterCallback, num_filters);
2840 for (n = 0; n < num_filters; n++)
2842 FilterData *data = connection->filters->pdata[n];
2843 filters[n].func = data->filter_function;
2844 filters[n].user_data = data->user_data;
2846 CONNECTION_UNLOCK (connection);
2848 /* then call the filters in order (without holding the lock) */
2849 for (n = 0; n < num_filters; n++)
2851 g_dbus_message_lock (message);
2852 message = filters[n].func (connection,
2855 filters[n].user_data);
2856 if (message == NULL)
2860 g_object_unref (connection);
2866 /* called with connection lock held, in GDBusWorker thread */
2868 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2870 SendMessageData *data = value;
2872 if (data->delivered)
2875 g_simple_async_result_set_error (data->simple,
2878 _("The connection is closed"));
2880 /* Ask send_message_with_reply_deliver not to remove the element from the
2881 * hash table - we're in the middle of a foreach; that would be unsafe.
2882 * Instead, return TRUE from this function so that it gets removed safely.
2884 send_message_with_reply_deliver (data, FALSE);
2888 /* Called in GDBusWorker's thread - we must not block - without lock held */
2890 on_worker_closed (GDBusWorker *worker,
2891 gboolean remote_peer_vanished,
2895 GDBusConnection *connection;
2897 guint old_atomic_flags;
2899 G_LOCK (message_bus_lock);
2900 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2903 G_UNLOCK (message_bus_lock);
2906 connection = G_DBUS_CONNECTION (user_data);
2907 g_object_ref (connection);
2908 G_UNLOCK (message_bus_lock);
2910 //g_debug ("in on_worker_closed: %s", error->message);
2912 CONNECTION_LOCK (connection);
2913 /* Even though this is atomic, we do it inside the lock to avoid breaking
2914 * assumptions in remove_match_rule(). We'd need the lock in a moment
2915 * anyway, so, no loss.
2917 old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
2919 if (!(old_atomic_flags & FLAG_CLOSED))
2921 g_hash_table_foreach_remove (connection->map_method_serial_to_send_message_data, cancel_method_on_close, NULL);
2922 schedule_closed_unlocked (connection, remote_peer_vanished, error);
2924 CONNECTION_UNLOCK (connection);
2926 g_object_unref (connection);
2929 /* ---------------------------------------------------------------------------------------------------- */
2931 /* Determines the biggest set of capabilities we can support on this
2934 * Called with the init_lock held.
2936 static GDBusCapabilityFlags
2937 get_offered_capabilities_max (GDBusConnection *connection)
2939 GDBusCapabilityFlags ret;
2940 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2942 if (G_IS_UNIX_CONNECTION (connection->stream))
2943 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2948 /* Called in a user thread, lock is not held */
2950 initable_init (GInitable *initable,
2951 GCancellable *cancellable,
2954 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2957 /* This method needs to be idempotent to work with the singleton
2958 * pattern. See the docs for g_initable_init(). We implement this by
2961 * Unfortunately we can't use the main lock since the on_worker_*()
2962 * callbacks above needs the lock during initialization (for message
2963 * bus connections we do a synchronous Hello() call on the bus).
2965 g_mutex_lock (&connection->init_lock);
2969 /* Make this a no-op if we're already initialized (successfully or
2972 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
2974 ret = (connection->initialization_error == NULL);
2978 /* Because of init_lock, we can't get here twice in different threads */
2979 g_assert (connection->initialization_error == NULL);
2981 /* The user can pass multiple (but mutally exclusive) construct
2984 * - stream (of type GIOStream)
2985 * - address (of type gchar*)
2987 * At the end of the day we end up with a non-NULL GIOStream
2988 * object in connection->stream.
2990 if (connection->address != NULL)
2992 g_assert (connection->stream == NULL);
2994 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2995 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2997 g_set_error_literal (&connection->initialization_error,
2999 G_IO_ERROR_INVALID_ARGUMENT,
3000 _("Unsupported flags encountered when constructing a client-side connection"));
3004 connection->stream = g_dbus_address_get_stream_sync (connection->address,
3005 NULL, /* TODO: out_guid */
3007 &connection->initialization_error);
3008 if (connection->stream == NULL)
3011 else if (connection->stream != NULL)
3017 g_assert_not_reached ();
3020 /* [KDBUS] Skip authentication process for kdbus transport */
3021 if (G_IS_KDBUS_CONNECTION (connection->stream))
3026 /* Authenticate the connection */
3027 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
3029 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
3030 g_assert (connection->guid != NULL);
3031 connection->auth = _g_dbus_auth_new (connection->stream);
3032 if (!_g_dbus_auth_run_server (connection->auth,
3033 connection->authentication_observer,
3035 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
3036 get_offered_capabilities_max (connection),
3037 &connection->capabilities,
3038 &connection->credentials,
3040 &connection->initialization_error))
3043 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
3045 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
3046 g_assert (connection->guid == NULL);
3047 connection->auth = _g_dbus_auth_new (connection->stream);
3048 connection->guid = _g_dbus_auth_run_client (connection->auth,
3049 connection->authentication_observer,
3050 get_offered_capabilities_max (connection),
3051 &connection->capabilities,
3053 &connection->initialization_error);
3054 if (connection->guid == NULL)
3058 if (connection->authentication_observer != NULL)
3060 g_object_unref (connection->authentication_observer);
3061 connection->authentication_observer = NULL;
3066 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
3068 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
3071 /* We want all IO operations to be non-blocking since they happen in
3072 * the worker thread which is shared by _all_ connections.
3074 if (G_IS_SOCKET_CONNECTION (connection->stream))
3076 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
3080 G_LOCK (message_bus_lock);
3081 if (alive_connections == NULL)
3082 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
3083 g_hash_table_insert (alive_connections, connection, connection);
3084 G_UNLOCK (message_bus_lock);
3086 connection->worker = _g_dbus_worker_new (connection->stream,
3087 connection->capabilities,
3088 ((connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) != 0),
3089 on_worker_message_received,
3090 on_worker_message_about_to_be_sent,
3094 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
3095 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3097 GVariant *hello_result;
3099 /* we could lift this restriction by adding code in gdbusprivate.c */
3100 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
3102 g_set_error_literal (&connection->initialization_error,
3105 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
3109 if (G_IS_KDBUS_CONNECTION (connection->stream))
3111 hello_result = _g_kdbus_Hello (connection->stream, &connection->initialization_error);
3115 hello_result = g_dbus_connection_call_sync (connection,
3116 "org.freedesktop.DBus", /* name */
3117 "/org/freedesktop/DBus", /* path */
3118 "org.freedesktop.DBus", /* interface */
3120 NULL, /* parameters */
3121 G_VARIANT_TYPE ("(s)"),
3122 CALL_FLAGS_INITIALIZING,
3124 NULL, /* TODO: cancellable */
3125 &connection->initialization_error);
3128 if (hello_result == NULL)
3131 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
3132 g_variant_unref (hello_result);
3133 //g_debug ("unique name is '%s'", connection->bus_unique_name);
3140 g_assert (connection->initialization_error != NULL);
3141 g_propagate_error (error, g_error_copy (connection->initialization_error));
3144 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
3145 g_mutex_unlock (&connection->init_lock);
3151 initable_iface_init (GInitableIface *initable_iface)
3153 initable_iface->init = initable_init;
3156 /* ---------------------------------------------------------------------------------------------------- */
3159 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
3164 /* ---------------------------------------------------------------------------------------------------- */
3167 * g_dbus_connection_new:
3168 * @stream: a #GIOStream
3169 * @guid: (allow-none): the GUID to use if a authenticating as a server or %NULL
3170 * @flags: flags describing how to make the connection
3171 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3172 * @cancellable: (allow-none): a #GCancellable or %NULL
3173 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
3174 * @user_data: the data to pass to @callback
3176 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
3177 * with the end represented by @stream.
3179 * If @stream is a #GSocketConnection, then the corresponding #GSocket
3180 * will be put into non-blocking mode.
3182 * The D-Bus connection will interact with @stream from a worker thread.
3183 * As a result, the caller should not interact with @stream after this
3184 * method has been called, except by calling g_object_unref() on it.
3186 * If @observer is not %NULL it may be used to control the
3187 * authentication process.
3189 * When the operation is finished, @callback will be invoked. You can
3190 * then call g_dbus_connection_new_finish() to get the result of the
3193 * This is a asynchronous failable constructor. See
3194 * g_dbus_connection_new_sync() for the synchronous
3200 g_dbus_connection_new (GIOStream *stream,
3202 GDBusConnectionFlags flags,
3203 GDBusAuthObserver *observer,
3204 GCancellable *cancellable,
3205 GAsyncReadyCallback callback,
3208 g_return_if_fail (G_IS_IO_STREAM (stream));
3209 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
3217 "authentication-observer", observer,
3222 * g_dbus_connection_new_finish:
3223 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback
3224 * passed to g_dbus_connection_new().
3225 * @error: return location for error or %NULL
3227 * Finishes an operation started with g_dbus_connection_new().
3229 * Returns: a #GDBusConnection or %NULL if @error is set. Free
3230 * with g_object_unref().
3235 g_dbus_connection_new_finish (GAsyncResult *res,
3239 GObject *source_object;
3241 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
3242 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3244 source_object = g_async_result_get_source_object (res);
3245 g_assert (source_object != NULL);
3246 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
3249 g_object_unref (source_object);
3251 return G_DBUS_CONNECTION (object);
3257 * g_dbus_connection_new_sync:
3258 * @stream: a #GIOStream
3259 * @guid: (allow-none): the GUID to use if a authenticating as a server or %NULL
3260 * @flags: flags describing how to make the connection
3261 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3262 * @cancellable: (allow-none): a #GCancellable or %NULL
3263 * @error: return location for error or %NULL
3265 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
3266 * with the end represented by @stream.
3268 * If @stream is a #GSocketConnection, then the corresponding #GSocket
3269 * will be put into non-blocking mode.
3271 * The D-Bus connection will interact with @stream from a worker thread.
3272 * As a result, the caller should not interact with @stream after this
3273 * method has been called, except by calling g_object_unref() on it.
3275 * If @observer is not %NULL it may be used to control the
3276 * authentication process.
3278 * This is a synchronous failable constructor. See
3279 * g_dbus_connection_new() for the asynchronous version.
3281 * Returns: a #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
3286 g_dbus_connection_new_sync (GIOStream *stream,
3288 GDBusConnectionFlags flags,
3289 GDBusAuthObserver *observer,
3290 GCancellable *cancellable,
3293 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
3294 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3295 return g_initable_new (G_TYPE_DBUS_CONNECTION,
3301 "authentication-observer", observer,
3305 /* ---------------------------------------------------------------------------------------------------- */
3308 * g_dbus_connection_new_for_address:
3309 * @address: a D-Bus address
3310 * @flags: flags describing how to make the connection
3311 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3312 * @cancellable: (allow-none): a #GCancellable or %NULL
3313 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
3314 * @user_data: the data to pass to @callback
3316 * Asynchronously connects and sets up a D-Bus client connection for
3317 * exchanging D-Bus messages with an endpoint specified by @address
3318 * which must be in the D-Bus address format.
3320 * This constructor can only be used to initiate client-side
3321 * connections - use g_dbus_connection_new() if you need to act as the
3322 * server. In particular, @flags cannot contain the
3323 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
3324 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
3326 * When the operation is finished, @callback will be invoked. You can
3327 * then call g_dbus_connection_new_finish() to get the result of the
3330 * If @observer is not %NULL it may be used to control the
3331 * authentication process.
3333 * This is a asynchronous failable constructor. See
3334 * g_dbus_connection_new_for_address_sync() for the synchronous
3340 g_dbus_connection_new_for_address (const gchar *address,
3341 GDBusConnectionFlags flags,
3342 GDBusAuthObserver *observer,
3343 GCancellable *cancellable,
3344 GAsyncReadyCallback callback,
3347 g_return_if_fail (address != NULL);
3348 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
3355 "authentication-observer", observer,
3360 * g_dbus_connection_new_for_address_finish:
3361 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
3362 * to g_dbus_connection_new()
3363 * @error: return location for error or %NULL
3365 * Finishes an operation started with g_dbus_connection_new_for_address().
3367 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
3373 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
3377 GObject *source_object;
3379 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
3380 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3382 source_object = g_async_result_get_source_object (res);
3383 g_assert (source_object != NULL);
3384 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
3387 g_object_unref (source_object);
3389 return G_DBUS_CONNECTION (object);
3395 * g_dbus_connection_new_for_address_sync:
3396 * @address: a D-Bus address
3397 * @flags: flags describing how to make the connection
3398 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3399 * @cancellable: (allow-none): a #GCancellable or %NULL
3400 * @error: return location for error or %NULL
3402 * Synchronously connects and sets up a D-Bus client connection for
3403 * exchanging D-Bus messages with an endpoint specified by @address
3404 * which must be in the D-Bus address format.
3406 * This constructor can only be used to initiate client-side
3407 * connections - use g_dbus_connection_new_sync() if you need to act
3408 * as the server. In particular, @flags cannot contain the
3409 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
3410 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
3412 * This is a synchronous failable constructor. See
3413 * g_dbus_connection_new_for_address() for the asynchronous version.
3415 * If @observer is not %NULL it may be used to control the
3416 * authentication process.
3418 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
3424 g_dbus_connection_new_for_address_sync (const gchar *address,
3425 GDBusConnectionFlags flags,
3426 GDBusAuthObserver *observer,
3427 GCancellable *cancellable,
3430 g_return_val_if_fail (address != NULL, NULL);
3431 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3432 return g_initable_new (G_TYPE_DBUS_CONNECTION,
3437 "authentication-observer", observer,
3441 /* ---------------------------------------------------------------------------------------------------- */
3444 * g_dbus_connection_set_exit_on_close:
3445 * @connection: a #GDBusConnection
3446 * @exit_on_close: whether the process should be terminated
3447 * when @connection is closed by the remote peer
3449 * Sets whether the process should be terminated when @connection is
3450 * closed by the remote peer. See #GDBusConnection:exit-on-close for
3453 * Note that this function should be used with care. Most modern UNIX
3454 * desktops tie the notion of a user session the session bus, and expect
3455 * all of a users applications to quit when their bus connection goes away.
3456 * If you are setting @exit_on_close to %FALSE for the shared session
3457 * bus connection, you should make sure that your application exits
3458 * when the user session ends.
3463 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
3464 gboolean exit_on_close)
3466 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3469 g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
3471 g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
3476 * g_dbus_connection_get_exit_on_close:
3477 * @connection: a #GDBusConnection
3479 * Gets whether the process is terminated when @connection is
3480 * closed by the remote peer. See
3481 * #GDBusConnection:exit-on-close for more details.
3483 * Returns: whether the process is terminated when @connection is
3484 * closed by the remote peer
3489 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
3491 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3493 if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
3500 * g_dbus_connection_get_guid:
3501 * @connection: a #GDBusConnection
3503 * The GUID of the peer performing the role of server when
3504 * authenticating. See #GDBusConnection:guid for more details.
3506 * Returns: The GUID. Do not free this string, it is owned by
3512 g_dbus_connection_get_guid (GDBusConnection *connection)
3514 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3515 return connection->guid;
3519 * g_dbus_connection_get_unique_name:
3520 * @connection: a #GDBusConnection
3522 * Gets the unique name of @connection as assigned by the message
3523 * bus. This can also be used to figure out if @connection is a
3524 * message bus connection.
3526 * Returns: the unique name or %NULL if @connection is not a message
3527 * bus connection. Do not free this string, it is owned by
3533 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3535 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3537 /* do not use g_return_val_if_fail(), we want the memory barrier */
3538 if (!check_initialized (connection))
3541 return connection->bus_unique_name;
3545 * g_dbus_connection_get_peer_credentials:
3546 * @connection: a #GDBusConnection
3548 * Gets the credentials of the authenticated peer. This will always
3549 * return %NULL unless @connection acted as a server
3550 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3551 * when set up and the client passed credentials as part of the
3552 * authentication process.
3554 * In a message bus setup, the message bus is always the server and
3555 * each application is a client. So this method will always return
3556 * %NULL for message bus clients.
3558 * Returns: (transfer none): a #GCredentials or %NULL if not available.
3559 * Do not free this object, it is owned by @connection.
3564 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3566 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3568 /* do not use g_return_val_if_fail(), we want the memory barrier */
3569 if (!check_initialized (connection))
3572 return connection->credentials;
3575 /* ---------------------------------------------------------------------------------------------------- */
3577 static guint _global_filter_id = 1;
3580 * g_dbus_connection_add_filter:
3581 * @connection: a #GDBusConnection
3582 * @filter_function: a filter function
3583 * @user_data: user data to pass to @filter_function
3584 * @user_data_free_func: function to free @user_data with when filter
3585 * is removed or %NULL
3587 * Adds a message filter. Filters are handlers that are run on all
3588 * incoming and outgoing messages, prior to standard dispatch. Filters
3589 * are run in the order that they were added. The same handler can be
3590 * added as a filter more than once, in which case it will be run more
3591 * than once. Filters added during a filter callback won't be run on
3592 * the message being processed. Filter functions are allowed to modify
3593 * and even drop messages.
3595 * Note that filters are run in a dedicated message handling thread so
3596 * they can't block and, generally, can't do anything but signal a
3597 * worker thread. Also note that filters are rarely needed - use API
3598 * such as g_dbus_connection_send_message_with_reply(),
3599 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3601 * If a filter consumes an incoming message the message is not
3602 * dispatched anywhere else - not even the standard dispatch machinery
3603 * (that API such as g_dbus_connection_signal_subscribe() and
3604 * g_dbus_connection_send_message_with_reply() relies on) will see the
3605 * message. Similary, if a filter consumes an outgoing message, the
3606 * message will not be sent to the other peer.
3608 * Returns: a filter identifier that can be used with
3609 * g_dbus_connection_remove_filter()
3614 g_dbus_connection_add_filter (GDBusConnection *connection,
3615 GDBusMessageFilterFunction filter_function,
3617 GDestroyNotify user_data_free_func)
3621 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3622 g_return_val_if_fail (filter_function != NULL, 0);
3623 g_return_val_if_fail (check_initialized (connection), 0);
3625 CONNECTION_LOCK (connection);
3626 data = g_new0 (FilterData, 1);
3627 data->id = _global_filter_id++; /* TODO: overflow etc. */
3628 data->filter_function = filter_function;
3629 data->user_data = user_data;
3630 data->user_data_free_func = user_data_free_func;
3631 g_ptr_array_add (connection->filters, data);
3632 CONNECTION_UNLOCK (connection);
3637 /* only called from finalize(), removes all filters */
3639 purge_all_filters (GDBusConnection *connection)
3642 for (n = 0; n < connection->filters->len; n++)
3644 FilterData *data = connection->filters->pdata[n];
3645 if (data->user_data_free_func != NULL)
3646 data->user_data_free_func (data->user_data);
3652 * g_dbus_connection_remove_filter:
3653 * @connection: a #GDBusConnection
3654 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3661 g_dbus_connection_remove_filter (GDBusConnection *connection,
3665 FilterData *to_destroy;
3667 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3668 g_return_if_fail (check_initialized (connection));
3670 CONNECTION_LOCK (connection);
3672 for (n = 0; n < connection->filters->len; n++)
3674 FilterData *data = connection->filters->pdata[n];
3675 if (data->id == filter_id)
3677 g_ptr_array_remove_index (connection->filters, n);
3682 CONNECTION_UNLOCK (connection);
3684 /* do free without holding lock */
3685 if (to_destroy != NULL)
3687 if (to_destroy->user_data_free_func != NULL)
3688 to_destroy->user_data_free_func (to_destroy->user_data);
3689 g_free (to_destroy);
3693 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3697 /* ---------------------------------------------------------------------------------------------------- */
3703 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3704 gchar *interface_name;
3708 GDBusSignalFlags flags;
3709 GArray *subscribers;
3714 GDBusSignalCallback callback;
3716 GDestroyNotify user_data_free_func;
3718 GMainContext *context;
3722 signal_data_free (SignalData *signal_data)
3724 g_free (signal_data->rule);
3725 g_free (signal_data->sender);
3726 g_free (signal_data->sender_unique_name);
3727 g_free (signal_data->interface_name);
3728 g_free (signal_data->member);
3729 g_free (signal_data->object_path);
3730 g_free (signal_data->arg0);
3731 g_array_free (signal_data->subscribers, TRUE);
3732 g_free (signal_data);
3736 args_to_rule (const gchar *sender,
3737 const gchar *interface_name,
3738 const gchar *member,
3739 const gchar *object_path,
3741 GDBusSignalFlags flags)
3745 rule = g_string_new ("type='signal'");
3746 if (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE)
3747 g_string_prepend_c (rule, '-');
3749 g_string_append_printf (rule, ",sender='%s'", sender);
3750 if (interface_name != NULL)
3751 g_string_append_printf (rule, ",interface='%s'", interface_name);
3753 g_string_append_printf (rule, ",member='%s'", member);
3754 if (object_path != NULL)
3755 g_string_append_printf (rule, ",path='%s'", object_path);
3759 if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3760 g_string_append_printf (rule, ",arg0path='%s'", arg0);
3761 else if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3762 g_string_append_printf (rule, ",arg0namespace='%s'", arg0);
3764 g_string_append_printf (rule, ",arg0='%s'", arg0);
3767 return g_string_free (rule, FALSE);
3770 static guint _global_subscriber_id = 1;
3771 static guint _global_registration_id = 1;
3772 static guint _global_subtree_registration_id = 1;
3774 /* ---------------------------------------------------------------------------------------------------- */
3776 /* Called in a user thread, lock is held */
3778 add_match_rule (GDBusConnection *connection,
3779 const gchar *match_rule)
3782 GDBusMessage *message;
3784 if (match_rule[0] == '-')
3787 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3788 "/org/freedesktop/DBus", /* path */
3789 "org.freedesktop.DBus", /* interface */
3791 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3793 if (!g_dbus_connection_send_message_unlocked (connection,
3795 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3799 g_critical ("Error while sending AddMatch() message: %s", error->message);
3800 g_error_free (error);
3802 g_object_unref (message);
3805 /* ---------------------------------------------------------------------------------------------------- */
3807 /* Called in a user thread, lock is held */
3809 remove_match_rule (GDBusConnection *connection,
3810 const gchar *match_rule)
3813 GDBusMessage *message;
3815 if (match_rule[0] == '-')
3818 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3819 "/org/freedesktop/DBus", /* path */
3820 "org.freedesktop.DBus", /* interface */
3822 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3825 if (!g_dbus_connection_send_message_unlocked (connection,
3827 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3831 /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
3832 * critical; but we're holding the lock, and our caller checked whether
3833 * we were already closed, so we can't get that error.
3835 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3836 g_error_free (error);
3838 g_object_unref (message);
3841 /* ---------------------------------------------------------------------------------------------------- */
3844 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3846 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3847 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3848 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3849 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3850 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3853 /* ---------------------------------------------------------------------------------------------------- */
3856 * g_dbus_connection_signal_subscribe:
3857 * @connection: a #GDBusConnection
3858 * @sender: (allow-none): sender name to match on (unique or well-known name)
3859 * or %NULL to listen from all senders
3860 * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3861 * match on all interfaces
3862 * @member: (allow-none): D-Bus signal name to match on or %NULL to match on
3864 * @object_path: (allow-none): object path to match on or %NULL to match on
3866 * @arg0: (allow-none): contents of first string argument to match on or %NULL
3867 * to match on all kinds of arguments
3868 * @flags: flags describing how to subscribe to the signal (currently unused)
3869 * @callback: callback to invoke when there is a signal matching the requested data
3870 * @user_data: user data to pass to @callback
3871 * @user_data_free_func: (allow-none): function to free @user_data with when
3872 * subscription is removed or %NULL
3874 * Subscribes to signals on @connection and invokes @callback with a whenever
3875 * the signal is received. Note that @callback will be invoked in the
3876 * [thread-default main context][g-main-context-push-thread-default]
3877 * of the thread you are calling this method from.
3879 * If @connection is not a message bus connection, @sender must be
3882 * If @sender is a well-known name note that @callback is invoked with
3883 * the unique name for the owner of @sender, not the well-known name
3884 * as one would expect. This is because the message bus rewrites the
3885 * name. As such, to avoid certain race conditions, users should be
3886 * tracking the name owner of the well-known name and use that when
3887 * processing the received signal.
3889 * If one of %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE or
3890 * %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH are given, @arg0 is
3891 * interpreted as part of a namespace or path. The first argument
3892 * of a signal is matched against that part as specified by D-Bus.
3894 * Returns: a subscription identifier that can be used with g_dbus_connection_signal_unsubscribe()
3899 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3900 const gchar *sender,
3901 const gchar *interface_name,
3902 const gchar *member,
3903 const gchar *object_path,
3905 GDBusSignalFlags flags,
3906 GDBusSignalCallback callback,
3908 GDestroyNotify user_data_free_func)
3911 SignalData *signal_data;
3912 SignalSubscriber subscriber;
3913 GPtrArray *signal_data_array;
3914 const gchar *sender_unique_name;
3916 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3917 * an OOM condition. We might want to change that but that would involve making
3918 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3919 * handle that. And there's really no sensible way of handling this short of retrying
3920 * to add the match rule... and then there's the little thing that, hey, maybe there's
3921 * a reason the bus in an OOM condition.
3923 * Doable, but not really sure it's worth it...
3926 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3927 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3928 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3929 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3930 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3931 g_return_val_if_fail (callback != NULL, 0);
3932 g_return_val_if_fail (check_initialized (connection), 0);
3933 g_return_val_if_fail (!((flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH) && (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)), 0);
3934 g_return_val_if_fail (!(arg0 == NULL && (flags & (G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH | G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE))), 0);
3936 CONNECTION_LOCK (connection);
3938 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3939 * with a '-' character to prefix the rule (which will otherwise be
3942 * This allows us to hash the rule and do our lifecycle tracking in
3943 * the usual way, but the '-' prevents the match rule from ever
3944 * actually being send to the bus (either for add or remove).
3946 rule = args_to_rule (sender, interface_name, member, object_path, arg0, flags);
3948 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3949 sender_unique_name = sender;
3951 sender_unique_name = "";
3953 subscriber.callback = callback;
3954 subscriber.user_data = user_data;
3955 subscriber.user_data_free_func = user_data_free_func;
3956 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3957 subscriber.context = g_main_context_ref_thread_default ();
3959 /* see if we've already have this rule */
3960 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3961 if (signal_data != NULL)
3963 g_array_append_val (signal_data->subscribers, subscriber);
3968 signal_data = g_new0 (SignalData, 1);
3969 signal_data->rule = rule;
3970 signal_data->sender = g_strdup (sender);
3971 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3972 signal_data->interface_name = g_strdup (interface_name);
3973 signal_data->member = g_strdup (member);
3974 signal_data->object_path = g_strdup (object_path);
3975 signal_data->arg0 = g_strdup (arg0);
3976 signal_data->flags = flags;
3977 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3978 g_array_append_val (signal_data->subscribers, subscriber);
3980 g_hash_table_insert (connection->map_rule_to_signal_data,
3984 /* Add the match rule to the bus...
3986 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3987 * always send such messages to us.
3989 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3991 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3992 add_match_rule (connection, signal_data->rule);
3995 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3996 signal_data->sender_unique_name);
3997 if (signal_data_array == NULL)
3999 signal_data_array = g_ptr_array_new ();
4000 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
4001 g_strdup (signal_data->sender_unique_name),
4004 g_ptr_array_add (signal_data_array, signal_data);
4007 g_hash_table_insert (connection->map_id_to_signal_data,
4008 GUINT_TO_POINTER (subscriber.id),
4011 CONNECTION_UNLOCK (connection);
4013 return subscriber.id;
4016 /* ---------------------------------------------------------------------------------------------------- */
4018 /* called in any thread */
4019 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
4021 unsubscribe_id_internal (GDBusConnection *connection,
4022 guint subscription_id,
4023 GArray *out_removed_subscribers)
4025 SignalData *signal_data;
4026 GPtrArray *signal_data_array;
4029 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
4030 GUINT_TO_POINTER (subscription_id));
4031 if (signal_data == NULL)
4033 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
4037 for (n = 0; n < signal_data->subscribers->len; n++)
4039 SignalSubscriber *subscriber;
4041 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
4042 if (subscriber->id != subscription_id)
4045 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
4046 GUINT_TO_POINTER (subscription_id)));
4047 g_array_append_val (out_removed_subscribers, *subscriber);
4048 g_array_remove_index (signal_data->subscribers, n);
4050 if (signal_data->subscribers->len == 0)
4052 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
4054 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
4055 signal_data->sender_unique_name);
4056 g_warn_if_fail (signal_data_array != NULL);
4057 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
4059 if (signal_data_array->len == 0)
4061 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
4062 signal_data->sender_unique_name));
4065 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
4066 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
4067 !is_signal_data_for_name_lost_or_acquired (signal_data) &&
4068 !g_dbus_connection_is_closed (connection) &&
4069 !connection->finalizing)
4071 /* The check for g_dbus_connection_is_closed() means that
4072 * sending the RemoveMatch message can't fail with
4073 * G_IO_ERROR_CLOSED, because we're holding the lock,
4074 * so on_worker_closed() can't happen between the check we just
4075 * did, and releasing the lock later.
4077 remove_match_rule (connection, signal_data->rule);
4080 signal_data_free (signal_data);
4086 g_assert_not_reached ();
4093 * g_dbus_connection_signal_unsubscribe:
4094 * @connection: a #GDBusConnection
4095 * @subscription_id: a subscription id obtained from
4096 * g_dbus_connection_signal_subscribe()
4098 * Unsubscribes from signals.
4103 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
4104 guint subscription_id)
4106 GArray *subscribers;
4109 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4110 g_return_if_fail (check_initialized (connection));
4112 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
4114 CONNECTION_LOCK (connection);
4115 unsubscribe_id_internal (connection,
4118 CONNECTION_UNLOCK (connection);
4121 g_assert (subscribers->len == 0 || subscribers->len == 1);
4123 /* call GDestroyNotify without lock held */
4124 for (n = 0; n < subscribers->len; n++)
4126 SignalSubscriber *subscriber;
4127 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
4128 call_destroy_notify (subscriber->context,
4129 subscriber->user_data_free_func,
4130 subscriber->user_data);
4131 g_main_context_unref (subscriber->context);
4134 g_array_free (subscribers, TRUE);
4137 /* ---------------------------------------------------------------------------------------------------- */
4141 guint subscription_id;
4142 GDBusSignalCallback callback;
4144 GDBusMessage *message;
4145 GDBusConnection *connection;
4146 const gchar *sender;
4148 const gchar *interface;
4149 const gchar *member;
4152 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
4156 emit_signal_instance_in_idle_cb (gpointer data)
4158 SignalInstance *signal_instance = data;
4159 GVariant *parameters;
4160 gboolean has_subscription;
4162 parameters = g_dbus_message_get_body (signal_instance->message);
4163 if (parameters == NULL)
4165 parameters = g_variant_new ("()");
4166 g_variant_ref_sink (parameters);
4170 g_variant_ref (parameters);
4174 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
4175 signal_instance->subscription_id,
4176 signal_instance->sender,
4177 signal_instance->path,
4178 signal_instance->interface,
4179 signal_instance->member,
4180 g_variant_print (parameters, TRUE));
4183 /* Careful here, don't do the callback if we no longer has the subscription */
4184 CONNECTION_LOCK (signal_instance->connection);
4185 has_subscription = FALSE;
4186 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
4187 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
4188 has_subscription = TRUE;
4189 CONNECTION_UNLOCK (signal_instance->connection);
4191 if (has_subscription)
4192 signal_instance->callback (signal_instance->connection,
4193 signal_instance->sender,
4194 signal_instance->path,
4195 signal_instance->interface,
4196 signal_instance->member,
4198 signal_instance->user_data);
4200 g_variant_unref (parameters);
4206 signal_instance_free (SignalInstance *signal_instance)
4208 g_object_unref (signal_instance->message);
4209 g_object_unref (signal_instance->connection);
4210 g_free (signal_instance);
4214 namespace_rule_matches (const gchar *namespace,
4220 len_namespace = strlen (namespace);
4221 len_name = strlen (name);
4223 if (len_name < len_namespace)
4226 if (memcmp (namespace, name, len_namespace) != 0)
4229 return len_namespace == len_name || name[len_namespace] == '.';
4233 path_rule_matches (const gchar *path_a,
4234 const gchar *path_b)
4238 len_a = strlen (path_a);
4239 len_b = strlen (path_b);
4241 if (len_a < len_b && path_a[len_a - 1] != '/')
4244 if (len_b < len_a && path_b[len_b - 1] != '/')
4247 return memcmp (path_a, path_b, MIN (len_a, len_b)) == 0;
4250 /* called in GDBusWorker thread WITH lock held */
4252 schedule_callbacks (GDBusConnection *connection,
4253 GPtrArray *signal_data_array,
4254 GDBusMessage *message,
4255 const gchar *sender)
4258 const gchar *interface;
4259 const gchar *member;
4268 interface = g_dbus_message_get_interface (message);
4269 member = g_dbus_message_get_member (message);
4270 path = g_dbus_message_get_path (message);
4271 arg0 = g_dbus_message_get_arg0 (message);
4274 g_print ("In schedule_callbacks:\n"
4276 " interface = '%s'\n"
4287 /* TODO: if this is slow, then we can change signal_data_array into
4288 * map_object_path_to_signal_data_array or something.
4290 for (n = 0; n < signal_data_array->len; n++)
4292 SignalData *signal_data = signal_data_array->pdata[n];
4294 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
4297 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
4300 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
4303 if (signal_data->arg0 != NULL)
4308 if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
4310 if (!namespace_rule_matches (signal_data->arg0, arg0))
4313 else if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
4315 if (!path_rule_matches (signal_data->arg0, arg0))
4318 else if (!g_str_equal (signal_data->arg0, arg0))
4322 for (m = 0; m < signal_data->subscribers->len; m++)
4324 SignalSubscriber *subscriber;
4325 GSource *idle_source;
4326 SignalInstance *signal_instance;
4328 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
4330 signal_instance = g_new0 (SignalInstance, 1);
4331 signal_instance->subscription_id = subscriber->id;
4332 signal_instance->callback = subscriber->callback;
4333 signal_instance->user_data = subscriber->user_data;
4334 signal_instance->message = g_object_ref (message);
4335 signal_instance->connection = g_object_ref (connection);
4336 signal_instance->sender = sender;
4337 signal_instance->path = path;
4338 signal_instance->interface = interface;
4339 signal_instance->member = member;
4341 idle_source = g_idle_source_new ();
4342 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4343 g_source_set_callback (idle_source,
4344 emit_signal_instance_in_idle_cb,
4346 (GDestroyNotify) signal_instance_free);
4347 g_source_set_name (idle_source, "[gio] emit_signal_instance_in_idle_cb");
4348 g_source_attach (idle_source, subscriber->context);
4349 g_source_unref (idle_source);
4354 /* called in GDBusWorker thread with lock held */
4356 distribute_signals (GDBusConnection *connection,
4357 GDBusMessage *message)
4359 GPtrArray *signal_data_array;
4360 const gchar *sender;
4362 sender = g_dbus_message_get_sender (message);
4364 if (G_UNLIKELY (_g_dbus_debug_signal ()))
4366 _g_dbus_debug_print_lock ();
4367 g_print ("========================================================================\n"
4368 "GDBus-debug:Signal:\n"
4369 " <<<< RECEIVED SIGNAL %s.%s\n"
4371 " sent by name %s\n",
4372 g_dbus_message_get_interface (message),
4373 g_dbus_message_get_member (message),
4374 g_dbus_message_get_path (message),
4375 sender != NULL ? sender : "(none)");
4376 _g_dbus_debug_print_unlock ();
4379 /* collect subscribers that match on sender */
4382 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
4383 if (signal_data_array != NULL)
4384 schedule_callbacks (connection, signal_data_array, message, sender);
4387 /* collect subscribers not matching on sender */
4388 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
4389 if (signal_data_array != NULL)
4390 schedule_callbacks (connection, signal_data_array, message, sender);
4393 /* ---------------------------------------------------------------------------------------------------- */
4395 /* only called from finalize(), removes all subscriptions */
4397 purge_all_signal_subscriptions (GDBusConnection *connection)
4399 GHashTableIter iter;
4402 GArray *subscribers;
4405 ids = g_array_new (FALSE, FALSE, sizeof (guint));
4406 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
4407 while (g_hash_table_iter_next (&iter, &key, NULL))
4409 guint subscription_id = GPOINTER_TO_UINT (key);
4410 g_array_append_val (ids, subscription_id);
4413 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
4414 for (n = 0; n < ids->len; n++)
4416 guint subscription_id = g_array_index (ids, guint, n);
4417 unsubscribe_id_internal (connection,
4421 g_array_free (ids, TRUE);
4423 /* call GDestroyNotify without lock held */
4424 for (n = 0; n < subscribers->len; n++)
4426 SignalSubscriber *subscriber;
4427 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
4428 call_destroy_notify (subscriber->context,
4429 subscriber->user_data_free_func,
4430 subscriber->user_data);
4431 g_main_context_unref (subscriber->context);
4434 g_array_free (subscribers, TRUE);
4437 /* ---------------------------------------------------------------------------------------------------- */
4439 static GDBusInterfaceVTable *
4440 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
4442 /* Don't waste memory by copying padding - remember to update this
4443 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
4445 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4449 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
4454 /* ---------------------------------------------------------------------------------------------------- */
4456 static GDBusSubtreeVTable *
4457 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
4459 /* Don't waste memory by copying padding - remember to update this
4460 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
4462 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4466 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
4471 /* ---------------------------------------------------------------------------------------------------- */
4473 struct ExportedObject
4476 GDBusConnection *connection;
4478 /* maps gchar* -> ExportedInterface* */
4479 GHashTable *map_if_name_to_ei;
4482 /* only called with lock held */
4484 exported_object_free (ExportedObject *eo)
4486 g_free (eo->object_path);
4487 g_hash_table_unref (eo->map_if_name_to_ei);
4496 gchar *interface_name;
4497 GDBusInterfaceVTable *vtable;
4498 GDBusInterfaceInfo *interface_info;
4500 GMainContext *context;
4502 GDestroyNotify user_data_free_func;
4503 } ExportedInterface;
4505 /* called with lock held */
4507 exported_interface_free (ExportedInterface *ei)
4509 g_dbus_interface_info_cache_release (ei->interface_info);
4510 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
4512 call_destroy_notify (ei->context,
4513 ei->user_data_free_func,
4516 g_main_context_unref (ei->context);
4518 g_free (ei->interface_name);
4519 _g_dbus_interface_vtable_free (ei->vtable);
4523 /* ---------------------------------------------------------------------------------------------------- */
4525 /* Convenience function to check if @registration_id (if not zero) or
4526 * @subtree_registration_id (if not zero) has been unregistered. If
4527 * so, returns %TRUE.
4529 * May be called by any thread. Caller must *not* hold lock.
4532 has_object_been_unregistered (GDBusConnection *connection,
4533 guint registration_id,
4534 guint subtree_registration_id)
4538 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4542 CONNECTION_LOCK (connection);
4543 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
4544 GUINT_TO_POINTER (registration_id)) == NULL)
4548 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
4549 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
4553 CONNECTION_UNLOCK (connection);
4558 /* ---------------------------------------------------------------------------------------------------- */
4562 GDBusConnection *connection;
4563 GDBusMessage *message;
4565 const gchar *property_name;
4566 const GDBusInterfaceVTable *vtable;
4567 GDBusInterfaceInfo *interface_info;
4568 const GDBusPropertyInfo *property_info;
4569 guint registration_id;
4570 guint subtree_registration_id;
4574 property_data_free (PropertyData *data)
4576 g_object_unref (data->connection);
4577 g_object_unref (data->message);
4581 /* called in thread where object was registered - no locks held */
4583 invoke_get_property_in_idle_cb (gpointer _data)
4585 PropertyData *data = _data;
4588 GDBusMessage *reply;
4590 if (has_object_been_unregistered (data->connection,
4591 data->registration_id,
4592 data->subtree_registration_id))
4594 reply = g_dbus_message_new_method_error (data->message,
4595 "org.freedesktop.DBus.Error.UnknownMethod",
4596 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4597 g_dbus_message_get_path (data->message));
4598 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4599 g_object_unref (reply);
4604 value = data->vtable->get_property (data->connection,
4605 g_dbus_message_get_sender (data->message),
4606 g_dbus_message_get_path (data->message),
4607 data->interface_info->name,
4608 data->property_name,
4615 g_assert_no_error (error);
4617 g_variant_take_ref (value);
4618 reply = g_dbus_message_new_method_reply (data->message);
4619 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4620 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4621 g_variant_unref (value);
4622 g_object_unref (reply);
4626 gchar *dbus_error_name;
4627 g_assert (error != NULL);
4628 dbus_error_name = g_dbus_error_encode_gerror (error);
4629 reply = g_dbus_message_new_method_error_literal (data->message,
4632 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4633 g_free (dbus_error_name);
4634 g_error_free (error);
4635 g_object_unref (reply);
4642 /* called in thread where object was registered - no locks held */
4644 invoke_set_property_in_idle_cb (gpointer _data)
4646 PropertyData *data = _data;
4648 GDBusMessage *reply;
4654 g_variant_get (g_dbus_message_get_body (data->message),
4660 if (!data->vtable->set_property (data->connection,
4661 g_dbus_message_get_sender (data->message),
4662 g_dbus_message_get_path (data->message),
4663 data->interface_info->name,
4664 data->property_name,
4669 gchar *dbus_error_name;
4670 g_assert (error != NULL);
4671 dbus_error_name = g_dbus_error_encode_gerror (error);
4672 reply = g_dbus_message_new_method_error_literal (data->message,
4675 g_free (dbus_error_name);
4676 g_error_free (error);
4680 reply = g_dbus_message_new_method_reply (data->message);
4683 g_assert (reply != NULL);
4684 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4685 g_object_unref (reply);
4686 g_variant_unref (value);
4691 /* called in any thread with connection's lock held */
4693 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4694 GDBusMessage *message,
4695 guint registration_id,
4696 guint subtree_registration_id,
4698 GDBusInterfaceInfo *interface_info,
4699 const GDBusInterfaceVTable *vtable,
4700 GMainContext *main_context,
4704 const char *interface_name;
4705 const char *property_name;
4706 const GDBusPropertyInfo *property_info;
4707 GSource *idle_source;
4708 PropertyData *property_data;
4709 GDBusMessage *reply;
4714 g_variant_get (g_dbus_message_get_body (message),
4719 g_variant_get (g_dbus_message_get_body (message),
4728 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4730 property_info = NULL;
4732 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4733 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4734 if (property_info == NULL)
4736 reply = g_dbus_message_new_method_error (message,
4737 "org.freedesktop.DBus.Error.InvalidArgs",
4738 _("No such property '%s'"),
4740 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4741 g_object_unref (reply);
4746 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4748 reply = g_dbus_message_new_method_error (message,
4749 "org.freedesktop.DBus.Error.InvalidArgs",
4750 _("Property '%s' is not readable"),
4752 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4753 g_object_unref (reply);
4757 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4759 reply = g_dbus_message_new_method_error (message,
4760 "org.freedesktop.DBus.Error.InvalidArgs",
4761 _("Property '%s' is not writable"),
4763 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4764 g_object_unref (reply);
4773 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4774 * of the given value is wrong
4776 g_variant_get_child (g_dbus_message_get_body (message), 2, "v", &value);
4777 if (g_strcmp0 (g_variant_get_type_string (value), property_info->signature) != 0)
4779 reply = g_dbus_message_new_method_error (message,
4780 "org.freedesktop.DBus.Error.InvalidArgs",
4781 _("Error setting property '%s': Expected type '%s' but got '%s'"),
4782 property_name, property_info->signature,
4783 g_variant_get_type_string (value));
4784 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4785 g_variant_unref (value);
4786 g_object_unref (reply);
4791 g_variant_unref (value);
4794 /* If the vtable pointer for get_property() resp. set_property() is
4795 * NULL then dispatch the call via the method_call() handler.
4799 if (vtable->get_property == NULL)
4801 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4802 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4803 vtable, main_context, user_data);
4810 if (vtable->set_property == NULL)
4812 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4813 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4814 vtable, main_context, user_data);
4820 /* ok, got the property info - call user code in an idle handler */
4821 property_data = g_new0 (PropertyData, 1);
4822 property_data->connection = g_object_ref (connection);
4823 property_data->message = g_object_ref (message);
4824 property_data->user_data = user_data;
4825 property_data->property_name = property_name;
4826 property_data->vtable = vtable;
4827 property_data->interface_info = interface_info;
4828 property_data->property_info = property_info;
4829 property_data->registration_id = registration_id;
4830 property_data->subtree_registration_id = subtree_registration_id;
4832 idle_source = g_idle_source_new ();
4833 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4834 g_source_set_callback (idle_source,
4835 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4837 (GDestroyNotify) property_data_free);
4839 g_source_set_name (idle_source, "[gio] invoke_get_property_in_idle_cb");
4841 g_source_set_name (idle_source, "[gio] invoke_set_property_in_idle_cb");
4842 g_source_attach (idle_source, main_context);
4843 g_source_unref (idle_source);
4851 /* called in GDBusWorker thread with connection's lock held */
4853 handle_getset_property (GDBusConnection *connection,
4855 GDBusMessage *message,
4858 ExportedInterface *ei;
4860 const char *interface_name;
4861 const char *property_name;
4866 g_variant_get (g_dbus_message_get_body (message),
4871 g_variant_get (g_dbus_message_get_body (message),
4877 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4878 * no such interface registered
4880 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4883 GDBusMessage *reply;
4884 reply = g_dbus_message_new_method_error (message,
4885 "org.freedesktop.DBus.Error.InvalidArgs",
4886 _("No such interface '%s'"),
4888 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4889 g_object_unref (reply);
4894 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4907 /* ---------------------------------------------------------------------------------------------------- */
4911 GDBusConnection *connection;
4912 GDBusMessage *message;
4914 const GDBusInterfaceVTable *vtable;
4915 GDBusInterfaceInfo *interface_info;
4916 guint registration_id;
4917 guint subtree_registration_id;
4918 } PropertyGetAllData;
4921 property_get_all_data_free (PropertyData *data)
4923 g_object_unref (data->connection);
4924 g_object_unref (data->message);
4928 /* called in thread where object was registered - no locks held */
4930 invoke_get_all_properties_in_idle_cb (gpointer _data)
4932 PropertyGetAllData *data = _data;
4933 GVariantBuilder builder;
4934 GDBusMessage *reply;
4937 if (has_object_been_unregistered (data->connection,
4938 data->registration_id,
4939 data->subtree_registration_id))
4941 reply = g_dbus_message_new_method_error (data->message,
4942 "org.freedesktop.DBus.Error.UnknownMethod",
4943 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4944 g_dbus_message_get_path (data->message));
4945 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4946 g_object_unref (reply);
4950 /* TODO: Right now we never fail this call - we just omit values if
4951 * a get_property() call is failing.
4953 * We could fail the whole call if just a single get_property() call
4954 * returns an error. We need clarification in the D-Bus spec about this.
4956 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4957 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4958 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4960 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4963 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4966 value = data->vtable->get_property (data->connection,
4967 g_dbus_message_get_sender (data->message),
4968 g_dbus_message_get_path (data->message),
4969 data->interface_info->name,
4970 property_info->name,
4977 g_variant_take_ref (value);
4978 g_variant_builder_add (&builder,
4980 property_info->name,
4982 g_variant_unref (value);
4984 g_variant_builder_close (&builder);
4986 reply = g_dbus_message_new_method_reply (data->message);
4987 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4988 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4989 g_object_unref (reply);
4996 interface_has_readable_properties (GDBusInterfaceInfo *interface_info)
5000 if (!interface_info->properties)
5003 for (i = 0; interface_info->properties[i]; i++)
5004 if (interface_info->properties[i]->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE)
5010 /* called in any thread with connection's lock held */
5012 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
5013 GDBusMessage *message,
5014 guint registration_id,
5015 guint subtree_registration_id,
5016 GDBusInterfaceInfo *interface_info,
5017 const GDBusInterfaceVTable *vtable,
5018 GMainContext *main_context,
5022 GSource *idle_source;
5023 PropertyGetAllData *property_get_all_data;
5030 /* If the vtable pointer for get_property() is NULL but we have a
5031 * non-zero number of readable properties, then dispatch the call via
5032 * the method_call() handler.
5034 if (vtable->get_property == NULL && interface_has_readable_properties (interface_info))
5036 schedule_method_call (connection, message, registration_id, subtree_registration_id,
5037 interface_info, NULL, NULL, g_dbus_message_get_body (message),
5038 vtable, main_context, user_data);
5043 /* ok, got the property info - call user in an idle handler */
5044 property_get_all_data = g_new0 (PropertyGetAllData, 1);
5045 property_get_all_data->connection = g_object_ref (connection);
5046 property_get_all_data->message = g_object_ref (message);
5047 property_get_all_data->user_data = user_data;
5048 property_get_all_data->vtable = vtable;
5049 property_get_all_data->interface_info = interface_info;
5050 property_get_all_data->registration_id = registration_id;
5051 property_get_all_data->subtree_registration_id = subtree_registration_id;
5053 idle_source = g_idle_source_new ();
5054 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
5055 g_source_set_callback (idle_source,
5056 invoke_get_all_properties_in_idle_cb,
5057 property_get_all_data,
5058 (GDestroyNotify) property_get_all_data_free);
5059 g_source_set_name (idle_source, "[gio] invoke_get_all_properties_in_idle_cb");
5060 g_source_attach (idle_source, main_context);
5061 g_source_unref (idle_source);
5069 /* called in GDBusWorker thread with connection's lock held */
5071 handle_get_all_properties (GDBusConnection *connection,
5073 GDBusMessage *message)
5075 ExportedInterface *ei;
5077 const char *interface_name;
5081 g_variant_get (g_dbus_message_get_body (message),
5085 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
5086 * no such interface registered
5088 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5091 GDBusMessage *reply;
5092 reply = g_dbus_message_new_method_error (message,
5093 "org.freedesktop.DBus.Error.InvalidArgs",
5094 _("No such interface"),
5096 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5097 g_object_unref (reply);
5102 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
5114 /* ---------------------------------------------------------------------------------------------------- */
5116 static const gchar introspect_header[] =
5117 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
5118 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
5119 "<!-- GDBus " PACKAGE_VERSION " -->\n"
5122 static const gchar introspect_tail[] =
5125 static const gchar introspect_properties_interface[] =
5126 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
5127 " <method name=\"Get\">\n"
5128 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5129 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
5130 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
5132 " <method name=\"GetAll\">\n"
5133 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5134 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
5136 " <method name=\"Set\">\n"
5137 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5138 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
5139 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
5141 " <signal name=\"PropertiesChanged\">\n"
5142 " <arg type=\"s\" name=\"interface_name\"/>\n"
5143 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
5144 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
5148 static const gchar introspect_introspectable_interface[] =
5149 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
5150 " <method name=\"Introspect\">\n"
5151 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
5154 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
5155 " <method name=\"Ping\"/>\n"
5156 " <method name=\"GetMachineId\">\n"
5157 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
5162 introspect_append_header (GString *s)
5164 g_string_append (s, introspect_header);
5168 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
5170 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
5176 begin = object_path + path_len;
5177 end = strchr (begin, '/');
5179 s = g_strndup (begin, end - begin);
5181 s = g_strdup (begin);
5183 if (g_hash_table_lookup (set, s) == NULL)
5184 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
5190 /* TODO: we want a nicer public interface for this */
5191 /* called in any thread with connection's lock held */
5193 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
5198 GHashTableIter hash_iter;
5199 const gchar *object_path;
5205 CONNECTION_ENSURE_LOCK (connection);
5207 path_len = strlen (path);
5211 set = g_hash_table_new (g_str_hash, g_str_equal);
5213 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
5214 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
5215 maybe_add_path (path, path_len, object_path, set);
5217 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
5218 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
5219 maybe_add_path (path, path_len, object_path, set);
5221 p = g_ptr_array_new ();
5222 keys = g_hash_table_get_keys (set);
5223 for (l = keys; l != NULL; l = l->next)
5224 g_ptr_array_add (p, l->data);
5225 g_hash_table_unref (set);
5228 g_ptr_array_add (p, NULL);
5229 ret = (gchar **) g_ptr_array_free (p, FALSE);
5233 /* called in any thread with connection's lock not held */
5235 g_dbus_connection_list_registered (GDBusConnection *connection,
5239 CONNECTION_LOCK (connection);
5240 ret = g_dbus_connection_list_registered_unlocked (connection, path);
5241 CONNECTION_UNLOCK (connection);
5245 /* called in GDBusWorker thread with connection's lock held */
5247 handle_introspect (GDBusConnection *connection,
5249 GDBusMessage *message)
5253 GDBusMessage *reply;
5254 GHashTableIter hash_iter;
5255 ExportedInterface *ei;
5258 /* first the header with the standard interfaces */
5259 s = g_string_sized_new (sizeof (introspect_header) +
5260 sizeof (introspect_properties_interface) +
5261 sizeof (introspect_introspectable_interface) +
5262 sizeof (introspect_tail));
5263 introspect_append_header (s);
5264 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
5265 "org.freedesktop.DBus.Properties"))
5266 g_string_append (s, introspect_properties_interface);
5268 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
5269 "org.freedesktop.DBus.Introspectable"))
5270 g_string_append (s, introspect_introspectable_interface);
5272 /* then include the registered interfaces */
5273 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
5274 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
5275 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
5277 /* finally include nodes registered below us */
5278 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
5279 for (n = 0; registered != NULL && registered[n] != NULL; n++)
5280 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
5281 g_strfreev (registered);
5282 g_string_append (s, introspect_tail);
5284 reply = g_dbus_message_new_method_reply (message);
5285 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5286 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5287 g_object_unref (reply);
5288 g_string_free (s, TRUE);
5293 /* called in thread where object was registered - no locks held */
5295 call_in_idle_cb (gpointer user_data)
5297 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
5298 GDBusInterfaceVTable *vtable;
5299 guint registration_id;
5300 guint subtree_registration_id;
5302 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
5303 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
5305 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
5307 subtree_registration_id))
5309 GDBusMessage *reply;
5310 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
5311 "org.freedesktop.DBus.Error.UnknownMethod",
5312 _("No such interface '%s' on object at path %s"),
5313 g_dbus_method_invocation_get_interface_name (invocation),
5314 g_dbus_method_invocation_get_object_path (invocation));
5315 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5316 g_object_unref (reply);
5320 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
5321 g_assert (vtable != NULL && vtable->method_call != NULL);
5323 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
5324 g_dbus_method_invocation_get_sender (invocation),
5325 g_dbus_method_invocation_get_object_path (invocation),
5326 g_dbus_method_invocation_get_interface_name (invocation),
5327 g_dbus_method_invocation_get_method_name (invocation),
5328 g_dbus_method_invocation_get_parameters (invocation),
5329 g_object_ref (invocation),
5330 g_dbus_method_invocation_get_user_data (invocation));
5336 /* called in GDBusWorker thread with connection's lock held */
5338 schedule_method_call (GDBusConnection *connection,
5339 GDBusMessage *message,
5340 guint registration_id,
5341 guint subtree_registration_id,
5342 const GDBusInterfaceInfo *interface_info,
5343 const GDBusMethodInfo *method_info,
5344 const GDBusPropertyInfo *property_info,
5345 GVariant *parameters,
5346 const GDBusInterfaceVTable *vtable,
5347 GMainContext *main_context,
5350 GDBusMethodInvocation *invocation;
5351 GSource *idle_source;
5353 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
5354 g_dbus_message_get_path (message),
5355 g_dbus_message_get_interface (message),
5356 g_dbus_message_get_member (message),
5364 /* TODO: would be nicer with a real MethodData like we already
5365 * have PropertyData and PropertyGetAllData... */
5366 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
5367 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
5368 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
5370 idle_source = g_idle_source_new ();
5371 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
5372 g_source_set_callback (idle_source,
5376 g_source_set_name (idle_source, "[gio] call_in_idle_cb");
5377 g_source_attach (idle_source, main_context);
5378 g_source_unref (idle_source);
5381 /* called in GDBusWorker thread with connection's lock held */
5383 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
5384 GDBusMessage *message,
5385 guint registration_id,
5386 guint subtree_registration_id,
5387 GDBusInterfaceInfo *interface_info,
5388 const GDBusInterfaceVTable *vtable,
5389 GMainContext *main_context,
5392 GDBusMethodInfo *method_info;
5393 GDBusMessage *reply;
5394 GVariant *parameters;
5396 GVariantType *in_type;
5400 /* TODO: the cost of this is O(n) - it might be worth caching the result */
5401 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
5403 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
5404 * error to the caller
5406 if (method_info == NULL)
5408 reply = g_dbus_message_new_method_error (message,
5409 "org.freedesktop.DBus.Error.UnknownMethod",
5410 _("No such method '%s'"),
5411 g_dbus_message_get_member (message));
5412 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5413 g_object_unref (reply);
5418 parameters = g_dbus_message_get_body (message);
5419 if (parameters == NULL)
5421 parameters = g_variant_new ("()");
5422 g_variant_ref_sink (parameters);
5426 g_variant_ref (parameters);
5429 /* Check that the incoming args are of the right type - if they are not, return
5430 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
5432 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
5433 if (!g_variant_is_of_type (parameters, in_type))
5437 type_string = g_variant_type_dup_string (in_type);
5439 reply = g_dbus_message_new_method_error (message,
5440 "org.freedesktop.DBus.Error.InvalidArgs",
5441 _("Type of message, '%s', does not match expected type '%s'"),
5442 g_variant_get_type_string (parameters),
5444 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5445 g_variant_type_free (in_type);
5446 g_variant_unref (parameters);
5447 g_object_unref (reply);
5448 g_free (type_string);
5452 g_variant_type_free (in_type);
5454 /* schedule the call in idle */
5455 schedule_method_call (connection, message, registration_id, subtree_registration_id,
5456 interface_info, method_info, NULL, parameters,
5457 vtable, main_context, user_data);
5458 g_variant_unref (parameters);
5465 /* ---------------------------------------------------------------------------------------------------- */
5467 /* called in GDBusWorker thread with connection's lock held */
5469 obj_message_func (GDBusConnection *connection,
5471 GDBusMessage *message)
5473 const gchar *interface_name;
5474 const gchar *member;
5475 const gchar *signature;
5480 interface_name = g_dbus_message_get_interface (message);
5481 member = g_dbus_message_get_member (message);
5482 signature = g_dbus_message_get_signature (message);
5484 /* see if we have an interface for handling this call */
5485 if (interface_name != NULL)
5487 ExportedInterface *ei;
5488 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5491 /* we do - invoke the handler in idle in the right thread */
5493 /* handle no vtable or handler being present */
5494 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
5497 handled = validate_and_maybe_schedule_method_call (connection,
5509 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5510 g_strcmp0 (member, "Introspect") == 0 &&
5511 g_strcmp0 (signature, "") == 0)
5513 handled = handle_introspect (connection, eo, message);
5516 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5517 g_strcmp0 (member, "Get") == 0 &&
5518 g_strcmp0 (signature, "ss") == 0)
5520 handled = handle_getset_property (connection, eo, message, TRUE);
5523 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5524 g_strcmp0 (member, "Set") == 0 &&
5525 g_strcmp0 (signature, "ssv") == 0)
5527 handled = handle_getset_property (connection, eo, message, FALSE);
5530 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5531 g_strcmp0 (member, "GetAll") == 0 &&
5532 g_strcmp0 (signature, "s") == 0)
5534 handled = handle_get_all_properties (connection, eo, message);
5543 * g_dbus_connection_register_object:
5544 * @connection: a #GDBusConnection
5545 * @object_path: the object path to register at
5546 * @interface_info: introspection data for the interface
5547 * @vtable: (allow-none): a #GDBusInterfaceVTable to call into or %NULL
5548 * @user_data: (allow-none): data to pass to functions in @vtable
5549 * @user_data_free_func: function to call when the object path is unregistered
5550 * @error: return location for error or %NULL
5552 * Registers callbacks for exported objects at @object_path with the
5553 * D-Bus interface that is described in @interface_info.
5555 * Calls to functions in @vtable (and @user_data_free_func) will happen
5557 * [thread-default main context][g-main-context-push-thread-default]
5558 * of the thread you are calling this method from.
5560 * Note that all #GVariant values passed to functions in @vtable will match
5561 * the signature given in @interface_info - if a remote caller passes
5562 * incorrect values, the `org.freedesktop.DBus.Error.InvalidArgs`
5563 * is returned to the remote caller.
5565 * Additionally, if the remote caller attempts to invoke methods or
5566 * access properties not mentioned in @interface_info the
5567 * `org.freedesktop.DBus.Error.UnknownMethod` resp.
5568 * `org.freedesktop.DBus.Error.InvalidArgs` errors
5569 * are returned to the caller.
5571 * It is considered a programming error if the
5572 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
5573 * #GVariant of incorrect type.
5575 * If an existing callback is already registered at @object_path and
5576 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
5578 * GDBus automatically implements the standard D-Bus interfaces
5579 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
5580 * and org.freedesktop.Peer, so you don't have to implement those for the
5581 * objects you export. You can implement org.freedesktop.DBus.Properties
5582 * yourself, e.g. to handle getting and setting of properties asynchronously.
5584 * Note that the reference count on @interface_info will be
5585 * incremented by 1 (unless allocated statically, e.g. if the
5586 * reference count is -1, see g_dbus_interface_info_ref()) for as long
5587 * as the object is exported. Also note that @vtable will be copied.
5589 * See this [server][gdbus-server] for an example of how to use this method.
5591 * Returns: 0 if @error is set, otherwise a registration id (never 0)
5592 * that can be used with g_dbus_connection_unregister_object()
5597 g_dbus_connection_register_object (GDBusConnection *connection,
5598 const gchar *object_path,
5599 GDBusInterfaceInfo *interface_info,
5600 const GDBusInterfaceVTable *vtable,
5602 GDestroyNotify user_data_free_func,
5606 ExportedInterface *ei;
5609 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5610 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5611 g_return_val_if_fail (interface_info != NULL, 0);
5612 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
5613 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5614 g_return_val_if_fail (check_initialized (connection), 0);
5618 CONNECTION_LOCK (connection);
5620 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5623 eo = g_new0 (ExportedObject, 1);
5624 eo->object_path = g_strdup (object_path);
5625 eo->connection = connection;
5626 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
5629 (GDestroyNotify) exported_interface_free);
5630 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
5633 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
5639 _("An object is already exported for the interface %s at %s"),
5640 interface_info->name,
5645 ei = g_new0 (ExportedInterface, 1);
5646 ei->id = _global_registration_id++; /* TODO: overflow etc. */
5648 ei->user_data = user_data;
5649 ei->user_data_free_func = user_data_free_func;
5650 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
5651 ei->interface_info = g_dbus_interface_info_ref (interface_info);
5652 g_dbus_interface_info_cache_build (ei->interface_info);
5653 ei->interface_name = g_strdup (interface_info->name);
5654 ei->context = g_main_context_ref_thread_default ();
5656 g_hash_table_insert (eo->map_if_name_to_ei,
5657 (gpointer) ei->interface_name,
5659 g_hash_table_insert (connection->map_id_to_ei,
5660 GUINT_TO_POINTER (ei->id),
5666 CONNECTION_UNLOCK (connection);
5672 * g_dbus_connection_unregister_object:
5673 * @connection: a #GDBusConnection
5674 * @registration_id: a registration id obtained from
5675 * g_dbus_connection_register_object()
5677 * Unregisters an object.
5679 * Returns: %TRUE if the object was unregistered, %FALSE otherwise
5684 g_dbus_connection_unregister_object (GDBusConnection *connection,
5685 guint registration_id)
5687 ExportedInterface *ei;
5691 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5692 g_return_val_if_fail (check_initialized (connection), FALSE);
5696 CONNECTION_LOCK (connection);
5698 ei = g_hash_table_lookup (connection->map_id_to_ei,
5699 GUINT_TO_POINTER (registration_id));
5705 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5706 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5707 /* unregister object path if we have no more exported interfaces */
5708 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5709 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5715 CONNECTION_UNLOCK (connection);
5720 /* ---------------------------------------------------------------------------------------------------- */
5723 * g_dbus_connection_emit_signal:
5724 * @connection: a #GDBusConnection
5725 * @destination_bus_name: (allow-none): the unique bus name for the destination
5726 * for the signal or %NULL to emit to all listeners
5727 * @object_path: path of remote object
5728 * @interface_name: D-Bus interface to emit a signal on
5729 * @signal_name: the name of the signal to emit
5730 * @parameters: (allow-none): a #GVariant tuple with parameters for the signal
5731 * or %NULL if not passing parameters
5732 * @error: Return location for error or %NULL
5736 * If the parameters GVariant is floating, it is consumed.
5738 * This can only fail if @parameters is not compatible with the D-Bus protocol.
5740 * Returns: %TRUE unless @error is set
5745 g_dbus_connection_emit_signal (GDBusConnection *connection,
5746 const gchar *destination_bus_name,
5747 const gchar *object_path,
5748 const gchar *interface_name,
5749 const gchar *signal_name,
5750 GVariant *parameters,
5753 GDBusMessage *message;
5759 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5760 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5761 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5762 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5763 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5764 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5765 g_return_val_if_fail (check_initialized (connection), FALSE);
5767 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5769 _g_dbus_debug_print_lock ();
5770 g_print ("========================================================================\n"
5771 "GDBus-debug:Emission:\n"
5772 " >>>> SIGNAL EMISSION %s.%s()\n"
5774 " destination %s\n",
5775 interface_name, signal_name,
5777 destination_bus_name != NULL ? destination_bus_name : "(none)");
5778 _g_dbus_debug_print_unlock ();
5781 message = g_dbus_message_new_signal (object_path,
5785 if (destination_bus_name != NULL)
5786 g_dbus_message_set_header (message,
5787 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5788 g_variant_new_string (destination_bus_name));
5790 if (parameters != NULL)
5791 g_dbus_message_set_body (message, parameters);
5793 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5794 g_object_unref (message);
5800 add_call_flags (GDBusMessage *message,
5801 GDBusCallFlags flags)
5803 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5804 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
5808 decode_method_reply (GDBusMessage *reply,
5809 const gchar *method_name,
5810 const GVariantType *reply_type,
5811 GUnixFDList **out_fd_list,
5817 switch (g_dbus_message_get_message_type (reply))
5819 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5820 result = g_dbus_message_get_body (reply);
5823 result = g_variant_new ("()");
5824 g_variant_ref_sink (result);
5828 g_variant_ref (result);
5831 if (!g_variant_is_of_type (result, reply_type))
5833 gchar *type_string = g_variant_type_dup_string (reply_type);
5837 G_IO_ERROR_INVALID_ARGUMENT,
5838 _("Method '%s' returned type '%s', but expected '%s'"),
5839 method_name, g_variant_get_type_string (result), type_string);
5841 g_variant_unref (result);
5842 g_free (type_string);
5849 if (out_fd_list != NULL)
5851 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5852 if (*out_fd_list != NULL)
5853 g_object_ref (*out_fd_list);
5859 case G_DBUS_MESSAGE_TYPE_ERROR:
5860 g_dbus_message_to_gerror (reply, error);
5864 g_assert_not_reached ();
5874 GSimpleAsyncResult *simple;
5875 GVariantType *reply_type;
5876 gchar *method_name; /* for error message */
5880 GUnixFDList *fd_list;
5884 call_state_free (CallState *state)
5886 g_variant_type_free (state->reply_type);
5887 g_free (state->method_name);
5889 if (state->value != NULL)
5890 g_variant_unref (state->value);
5891 if (state->fd_list != NULL)
5892 g_object_unref (state->fd_list);
5893 g_slice_free (CallState, state);
5896 /* called in any thread, with the connection's lock not held */
5898 g_dbus_connection_call_done (GObject *source,
5899 GAsyncResult *result,
5902 GSimpleAsyncResult *simple;
5903 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5904 CallState *state = user_data;
5906 GDBusMessage *reply;
5909 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5913 if (G_UNLIKELY (_g_dbus_debug_call ()))
5915 _g_dbus_debug_print_lock ();
5916 g_print ("========================================================================\n"
5917 "GDBus-debug:Call:\n"
5918 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5924 g_print ("SUCCESS\n");
5928 g_print ("FAILED: %s\n",
5931 _g_dbus_debug_print_unlock ();
5935 state->value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5937 simple = state->simple; /* why? because state is freed before we unref simple.. */
5940 g_simple_async_result_take_error (state->simple, error);
5941 g_simple_async_result_complete (state->simple);
5942 call_state_free (state);
5946 g_simple_async_result_set_op_res_gpointer (state->simple, state, (GDestroyNotify) call_state_free);
5947 g_simple_async_result_complete (state->simple);
5949 g_clear_object (&reply);
5950 g_object_unref (simple);
5953 /* called in any thread, with the connection's lock not held */
5955 g_dbus_connection_call_internal (GDBusConnection *connection,
5956 const gchar *bus_name,
5957 const gchar *object_path,
5958 const gchar *interface_name,
5959 const gchar *method_name,
5960 GVariant *parameters,
5961 const GVariantType *reply_type,
5962 GDBusCallFlags flags,
5964 GUnixFDList *fd_list,
5965 GCancellable *cancellable,
5966 GAsyncReadyCallback callback,
5969 GDBusMessage *message;
5972 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5973 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5974 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5975 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5976 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5977 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5978 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5979 g_return_if_fail (check_initialized (connection));
5981 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5983 g_return_if_fail (fd_list == NULL);
5986 message = g_dbus_message_new_method_call (bus_name,
5990 add_call_flags (message, flags);
5991 if (parameters != NULL)
5992 g_dbus_message_set_body (message, parameters);
5995 if (fd_list != NULL)
5996 g_dbus_message_set_unix_fd_list (message, fd_list);
5999 /* If the user has no callback then we can just send the message with
6000 * the G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set and skip all
6001 * the logic for processing the reply. If the service sends the reply
6002 * anyway then it will just be ignored.
6004 if (callback != NULL)
6008 state = g_slice_new0 (CallState);
6009 state->simple = g_simple_async_result_new (G_OBJECT (connection),
6010 callback, user_data,
6011 g_dbus_connection_call_internal);
6012 g_simple_async_result_set_check_cancellable (state->simple, cancellable);
6013 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
6015 if (reply_type == NULL)
6016 reply_type = G_VARIANT_TYPE_ANY;
6018 state->reply_type = g_variant_type_copy (reply_type);
6020 g_dbus_connection_send_message_with_reply (connection,
6022 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
6026 g_dbus_connection_call_done,
6028 serial = state->serial;
6032 GDBusMessageFlags flags;
6034 flags = g_dbus_message_get_flags (message);
6035 flags |= G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
6036 g_dbus_message_set_flags (message, flags);
6038 g_dbus_connection_send_message (connection,
6040 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
6044 if (G_UNLIKELY (_g_dbus_debug_call ()))
6046 _g_dbus_debug_print_lock ();
6047 g_print ("========================================================================\n"
6048 "GDBus-debug:Call:\n"
6049 " >>>> ASYNC %s.%s()\n"
6051 " owned by name %s (serial %d)\n",
6055 bus_name != NULL ? bus_name : "(none)",
6057 _g_dbus_debug_print_unlock ();
6060 if (message != NULL)
6061 g_object_unref (message);
6064 /* called in any thread, with the connection's lock not held */
6066 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
6067 GUnixFDList **out_fd_list,
6071 GSimpleAsyncResult *simple;
6074 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
6075 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
6076 g_dbus_connection_call_internal), NULL);
6077 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6079 simple = G_SIMPLE_ASYNC_RESULT (res);
6081 if (g_simple_async_result_propagate_error (simple, error))
6084 state = g_simple_async_result_get_op_res_gpointer (simple);
6085 if (out_fd_list != NULL)
6086 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
6087 return g_variant_ref (state->value);
6090 /* called in any user thread, with the connection's lock not held */
6092 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
6093 const gchar *bus_name,
6094 const gchar *object_path,
6095 const gchar *interface_name,
6096 const gchar *method_name,
6097 GVariant *parameters,
6098 const GVariantType *reply_type,
6099 GDBusCallFlags flags,
6101 GUnixFDList *fd_list,
6102 GUnixFDList **out_fd_list,
6103 GCancellable *cancellable,
6106 GDBusMessage *message;
6107 GDBusMessage *reply;
6109 GError *local_error;
6110 GDBusSendMessageFlags send_flags;
6116 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
6117 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
6118 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
6119 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
6120 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
6121 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
6122 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
6124 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
6126 g_return_val_if_fail (fd_list == NULL, NULL);
6128 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6130 if (!(flags & CALL_FLAGS_INITIALIZING))
6131 g_return_val_if_fail (check_initialized (connection), FALSE);
6133 if (reply_type == NULL)
6134 reply_type = G_VARIANT_TYPE_ANY;
6136 message = g_dbus_message_new_method_call (bus_name,
6140 add_call_flags (message, flags);
6141 if (parameters != NULL)
6142 g_dbus_message_set_body (message, parameters);
6145 if (fd_list != NULL)
6146 g_dbus_message_set_unix_fd_list (message, fd_list);
6149 if (G_UNLIKELY (_g_dbus_debug_call ()))
6151 _g_dbus_debug_print_lock ();
6152 g_print ("========================================================================\n"
6153 "GDBus-debug:Call:\n"
6154 " >>>> SYNC %s.%s()\n"
6156 " owned by name %s\n",
6160 bus_name != NULL ? bus_name : "(none)");
6161 _g_dbus_debug_print_unlock ();
6166 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
6168 /* translate from one flavour of flags to another... */
6169 if (flags & CALL_FLAGS_INITIALIZING)
6170 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
6172 reply = g_dbus_connection_send_message_with_reply_sync (connection,
6176 NULL, /* volatile guint32 *out_serial */
6180 if (G_UNLIKELY (_g_dbus_debug_call ()))
6182 _g_dbus_debug_print_lock ();
6183 g_print ("========================================================================\n"
6184 "GDBus-debug:Call:\n"
6185 " <<<< SYNC COMPLETE %s.%s()\n"
6191 g_print ("SUCCESS\n");
6195 g_print ("FAILED: %s\n",
6196 local_error->message);
6198 _g_dbus_debug_print_unlock ();
6204 *error = local_error;
6206 g_error_free (local_error);
6210 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
6213 if (message != NULL)
6214 g_object_unref (message);
6216 g_object_unref (reply);
6221 /* ---------------------------------------------------------------------------------------------------- */
6224 * g_dbus_connection_call:
6225 * @connection: a #GDBusConnection
6226 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6227 * @connection is not a message bus connection
6228 * @object_path: path of remote object
6229 * @interface_name: D-Bus interface to invoke method on
6230 * @method_name: the name of the method to invoke
6231 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6232 * or %NULL if not passing parameters
6233 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6234 * @flags: flags from the #GDBusCallFlags enumeration
6235 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6236 * timeout or %G_MAXINT for no timeout
6237 * @cancellable: (allow-none): a #GCancellable or %NULL
6238 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request
6239 * is satisfied or %NULL if you don't care about the result of the
6241 * @user_data: the data to pass to @callback
6243 * Asynchronously invokes the @method_name method on the
6244 * @interface_name D-Bus interface on the remote object at
6245 * @object_path owned by @bus_name.
6247 * If @connection is closed then the operation will fail with
6248 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
6249 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
6250 * not compatible with the D-Bus protocol, the operation fails with
6251 * %G_IO_ERROR_INVALID_ARGUMENT.
6253 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
6254 * error will be raised if it does not match. Said another way, if you give a @reply_type
6255 * then any non-%NULL return value will be of this type.
6257 * If the @parameters #GVariant is floating, it is consumed. This allows
6258 * convenient 'inline' use of g_variant_new(), e.g.:
6259 * |[<!-- language="C" -->
6260 * g_dbus_connection_call (connection,
6261 * "org.freedesktop.StringThings",
6262 * "/org/freedesktop/StringThings",
6263 * "org.freedesktop.StringThings",
6265 * g_variant_new ("(ss)",
6269 * G_DBUS_CALL_FLAGS_NONE,
6272 * (GAsyncReadyCallback) two_strings_done,
6276 * This is an asynchronous method. When the operation is finished,
6277 * @callback will be invoked in the
6278 * [thread-default main context][g-main-context-push-thread-default]
6279 * of the thread you are calling this method from. You can then call
6280 * g_dbus_connection_call_finish() to get the result of the operation.
6281 * See g_dbus_connection_call_sync() for the synchronous version of this
6284 * If @callback is %NULL then the D-Bus method call message will be sent with
6285 * the %G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set.
6290 g_dbus_connection_call (GDBusConnection *connection,
6291 const gchar *bus_name,
6292 const gchar *object_path,
6293 const gchar *interface_name,
6294 const gchar *method_name,
6295 GVariant *parameters,
6296 const GVariantType *reply_type,
6297 GDBusCallFlags flags,
6299 GCancellable *cancellable,
6300 GAsyncReadyCallback callback,
6303 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);
6307 * g_dbus_connection_call_finish:
6308 * @connection: a #GDBusConnection
6309 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call()
6310 * @error: return location for error or %NULL
6312 * Finishes an operation started with g_dbus_connection_call().
6314 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6315 * return values. Free with g_variant_unref().
6320 g_dbus_connection_call_finish (GDBusConnection *connection,
6324 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
6328 * g_dbus_connection_call_sync:
6329 * @connection: a #GDBusConnection
6330 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6331 * @connection is not a message bus connection
6332 * @object_path: path of remote object
6333 * @interface_name: D-Bus interface to invoke method on
6334 * @method_name: the name of the method to invoke
6335 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6336 * or %NULL if not passing parameters
6337 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6338 * @flags: flags from the #GDBusCallFlags enumeration
6339 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6340 * timeout or %G_MAXINT for no timeout
6341 * @cancellable: (allow-none): a #GCancellable or %NULL
6342 * @error: return location for error or %NULL
6344 * Synchronously invokes the @method_name method on the
6345 * @interface_name D-Bus interface on the remote object at
6346 * @object_path owned by @bus_name.
6348 * If @connection is closed then the operation will fail with
6349 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
6350 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
6351 * contains a value not compatible with the D-Bus protocol, the operation
6352 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
6354 * If @reply_type is non-%NULL then the reply will be checked for having
6355 * this type and an error will be raised if it does not match. Said
6356 * another way, if you give a @reply_type then any non-%NULL return
6357 * value will be of this type.
6359 * If the @parameters #GVariant is floating, it is consumed.
6360 * This allows convenient 'inline' use of g_variant_new(), e.g.:
6361 * |[<!-- language="C" -->
6362 * g_dbus_connection_call_sync (connection,
6363 * "org.freedesktop.StringThings",
6364 * "/org/freedesktop/StringThings",
6365 * "org.freedesktop.StringThings",
6367 * g_variant_new ("(ss)",
6371 * G_DBUS_CALL_FLAGS_NONE,
6377 * The calling thread is blocked until a reply is received. See
6378 * g_dbus_connection_call() for the asynchronous version of
6381 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6382 * return values. Free with g_variant_unref().
6387 g_dbus_connection_call_sync (GDBusConnection *connection,
6388 const gchar *bus_name,
6389 const gchar *object_path,
6390 const gchar *interface_name,
6391 const gchar *method_name,
6392 GVariant *parameters,
6393 const GVariantType *reply_type,
6394 GDBusCallFlags flags,
6396 GCancellable *cancellable,
6399 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);
6402 /* ---------------------------------------------------------------------------------------------------- */
6407 * g_dbus_connection_call_with_unix_fd_list:
6408 * @connection: a #GDBusConnection
6409 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6410 * @connection is not a message bus connection
6411 * @object_path: path of remote object
6412 * @interface_name: D-Bus interface to invoke method on
6413 * @method_name: the name of the method to invoke
6414 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6415 * or %NULL if not passing parameters
6416 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6417 * @flags: flags from the #GDBusCallFlags enumeration
6418 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6419 * timeout or %G_MAXINT for no timeout
6420 * @fd_list: (allow-none): a #GUnixFDList or %NULL
6421 * @cancellable: (allow-none): a #GCancellable or %NULL
6422 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request is
6423 * satisfied or %NULL if you don't * care about the result of the
6425 * @user_data: The data to pass to @callback.
6427 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
6429 * This method is only available on UNIX.
6434 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
6435 const gchar *bus_name,
6436 const gchar *object_path,
6437 const gchar *interface_name,
6438 const gchar *method_name,
6439 GVariant *parameters,
6440 const GVariantType *reply_type,
6441 GDBusCallFlags flags,
6443 GUnixFDList *fd_list,
6444 GCancellable *cancellable,
6445 GAsyncReadyCallback callback,
6448 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);
6452 * g_dbus_connection_call_with_unix_fd_list_finish:
6453 * @connection: a #GDBusConnection
6454 * @out_fd_list: (out) (allow-none): return location for a #GUnixFDList or %NULL
6455 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
6456 * g_dbus_connection_call_with_unix_fd_list()
6457 * @error: return location for error or %NULL
6459 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
6461 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6462 * return values. Free with g_variant_unref().
6467 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
6468 GUnixFDList **out_fd_list,
6472 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
6476 * g_dbus_connection_call_with_unix_fd_list_sync:
6477 * @connection: a #GDBusConnection
6478 * @bus_name: (allow-none): a unique or well-known bus name or %NULL
6479 * if @connection is not a message bus connection
6480 * @object_path: path of remote object
6481 * @interface_name: D-Bus interface to invoke method on
6482 * @method_name: the name of the method to invoke
6483 * @parameters: (allow-none): a #GVariant tuple with parameters for
6484 * the method or %NULL if not passing parameters
6485 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6486 * @flags: flags from the #GDBusCallFlags enumeration
6487 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6488 * timeout or %G_MAXINT for no timeout
6489 * @fd_list: (allow-none): a #GUnixFDList or %NULL
6490 * @out_fd_list: (out) (allow-none): return location for a #GUnixFDList or %NULL
6491 * @cancellable: (allow-none): a #GCancellable or %NULL
6492 * @error: return location for error or %NULL
6494 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
6496 * This method is only available on UNIX.
6498 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6499 * return values. Free with g_variant_unref().
6504 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
6505 const gchar *bus_name,
6506 const gchar *object_path,
6507 const gchar *interface_name,
6508 const gchar *method_name,
6509 GVariant *parameters,
6510 const GVariantType *reply_type,
6511 GDBusCallFlags flags,
6513 GUnixFDList *fd_list,
6514 GUnixFDList **out_fd_list,
6515 GCancellable *cancellable,
6518 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);
6521 #endif /* G_OS_UNIX */
6523 /* ---------------------------------------------------------------------------------------------------- */
6525 struct ExportedSubtree
6529 GDBusConnection *connection;
6530 GDBusSubtreeVTable *vtable;
6531 GDBusSubtreeFlags flags;
6533 GMainContext *context;
6535 GDestroyNotify user_data_free_func;
6539 exported_subtree_free (ExportedSubtree *es)
6541 call_destroy_notify (es->context,
6542 es->user_data_free_func,
6545 g_main_context_unref (es->context);
6547 _g_dbus_subtree_vtable_free (es->vtable);
6548 g_free (es->object_path);
6552 /* called without lock held in the thread where the caller registered
6556 handle_subtree_introspect (GDBusConnection *connection,
6557 ExportedSubtree *es,
6558 GDBusMessage *message)
6562 GDBusMessage *reply;
6565 const gchar *sender;
6566 const gchar *requested_object_path;
6567 const gchar *requested_node;
6568 GDBusInterfaceInfo **interfaces;
6570 gchar **subnode_paths;
6571 gboolean has_properties_interface;
6572 gboolean has_introspectable_interface;
6576 requested_object_path = g_dbus_message_get_path (message);
6577 sender = g_dbus_message_get_sender (message);
6578 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6580 s = g_string_new (NULL);
6581 introspect_append_header (s);
6583 /* Strictly we don't need the children in dynamic mode, but we avoid the
6584 * conditionals to preserve code clarity
6586 children = es->vtable->enumerate (es->connection,
6593 requested_node = strrchr (requested_object_path, '/') + 1;
6595 /* Assert existence of object if we are not dynamic */
6596 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
6597 !_g_strv_has_string ((const gchar * const *) children, requested_node))
6602 requested_node = NULL;
6605 interfaces = es->vtable->introspect (es->connection,
6610 if (interfaces != NULL)
6612 has_properties_interface = FALSE;
6613 has_introspectable_interface = FALSE;
6615 for (n = 0; interfaces[n] != NULL; n++)
6617 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
6618 has_properties_interface = TRUE;
6619 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
6620 has_introspectable_interface = TRUE;
6622 if (!has_properties_interface)
6623 g_string_append (s, introspect_properties_interface);
6624 if (!has_introspectable_interface)
6625 g_string_append (s, introspect_introspectable_interface);
6627 for (n = 0; interfaces[n] != NULL; n++)
6629 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
6630 g_dbus_interface_info_unref (interfaces[n]);
6632 g_free (interfaces);
6635 /* then include <node> entries from the Subtree for the root */
6638 for (n = 0; children != NULL && children[n] != NULL; n++)
6639 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
6642 /* finally include nodes registered below us */
6643 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
6644 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
6645 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
6646 g_strfreev (subnode_paths);
6648 g_string_append (s, "</node>\n");
6650 reply = g_dbus_message_new_method_reply (message);
6651 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6652 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6653 g_object_unref (reply);
6658 g_string_free (s, TRUE);
6659 g_strfreev (children);
6663 /* called without lock held in the thread where the caller registered
6667 handle_subtree_method_invocation (GDBusConnection *connection,
6668 ExportedSubtree *es,
6669 GDBusMessage *message)
6672 const gchar *sender;
6673 const gchar *interface_name;
6674 const gchar *member;
6675 const gchar *signature;
6676 const gchar *requested_object_path;
6677 const gchar *requested_node;
6679 GDBusInterfaceInfo *interface_info;
6680 const GDBusInterfaceVTable *interface_vtable;
6681 gpointer interface_user_data;
6683 GDBusInterfaceInfo **interfaces;
6684 gboolean is_property_get;
6685 gboolean is_property_set;
6686 gboolean is_property_get_all;
6691 requested_object_path = g_dbus_message_get_path (message);
6692 sender = g_dbus_message_get_sender (message);
6693 interface_name = g_dbus_message_get_interface (message);
6694 member = g_dbus_message_get_member (message);
6695 signature = g_dbus_message_get_signature (message);
6696 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6698 is_property_get = FALSE;
6699 is_property_set = FALSE;
6700 is_property_get_all = FALSE;
6701 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6703 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6704 is_property_get = TRUE;
6705 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6706 is_property_set = TRUE;
6707 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6708 is_property_get_all = TRUE;
6713 requested_node = strrchr (requested_object_path, '/') + 1;
6715 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6717 /* We don't want to dispatch to unenumerated
6718 * nodes, so ensure that the child exists.
6723 children = es->vtable->enumerate (es->connection,
6728 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6729 g_strfreev (children);
6737 requested_node = NULL;
6740 /* get introspection data for the node */
6741 interfaces = es->vtable->introspect (es->connection,
6743 requested_object_path,
6747 if (interfaces == NULL)
6750 interface_info = NULL;
6751 for (n = 0; interfaces[n] != NULL; n++)
6753 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6754 interface_info = interfaces[n];
6757 /* dispatch the call if the user wants to handle it */
6758 if (interface_info != NULL)
6760 /* figure out where to dispatch the method call */
6761 interface_user_data = NULL;
6762 interface_vtable = es->vtable->dispatch (es->connection,
6767 &interface_user_data,
6769 if (interface_vtable == NULL)
6772 CONNECTION_LOCK (connection);
6773 handled = validate_and_maybe_schedule_method_call (es->connection,
6780 interface_user_data);
6781 CONNECTION_UNLOCK (connection);
6783 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6784 else if (is_property_get || is_property_set || is_property_get_all)
6786 if (is_property_get)
6787 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6788 else if (is_property_set)
6789 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6790 else if (is_property_get_all)
6791 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6793 g_assert_not_reached ();
6795 /* see if the object supports this interface at all */
6796 for (n = 0; interfaces[n] != NULL; n++)
6798 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6799 interface_info = interfaces[n];
6802 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6803 * claims it won't support the interface
6805 if (interface_info == NULL)
6807 GDBusMessage *reply;
6808 reply = g_dbus_message_new_method_error (message,
6809 "org.freedesktop.DBus.Error.InvalidArgs",
6810 _("No such interface '%s'"),
6812 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6813 g_object_unref (reply);
6818 /* figure out where to dispatch the property get/set/getall calls */
6819 interface_user_data = NULL;
6820 interface_vtable = es->vtable->dispatch (es->connection,
6825 &interface_user_data,
6827 if (interface_vtable == NULL)
6829 g_warning ("The subtree introspection function indicates that '%s' "
6830 "is a valid interface name, but calling the dispatch "
6831 "function on that interface gave us NULL", interface_name);
6835 if (is_property_get || is_property_set)
6837 CONNECTION_LOCK (connection);
6838 handled = validate_and_maybe_schedule_property_getset (es->connection,
6846 interface_user_data);
6847 CONNECTION_UNLOCK (connection);
6849 else if (is_property_get_all)
6851 CONNECTION_LOCK (connection);
6852 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6859 interface_user_data);
6860 CONNECTION_UNLOCK (connection);
6865 if (interfaces != NULL)
6867 for (n = 0; interfaces[n] != NULL; n++)
6868 g_dbus_interface_info_unref (interfaces[n]);
6869 g_free (interfaces);
6877 GDBusMessage *message;
6878 ExportedSubtree *es;
6879 } SubtreeDeferredData;
6882 subtree_deferred_data_free (SubtreeDeferredData *data)
6884 g_object_unref (data->message);
6888 /* called without lock held in the thread where the caller registered the subtree */
6890 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6892 SubtreeDeferredData *data = _data;
6897 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6898 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6899 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6900 handled = handle_subtree_introspect (data->es->connection,
6904 handled = handle_subtree_method_invocation (data->es->connection,
6910 CONNECTION_LOCK (data->es->connection);
6911 handled = handle_generic_unlocked (data->es->connection, data->message);
6912 CONNECTION_UNLOCK (data->es->connection);
6915 /* if we couldn't handle the request, just bail with the UnknownMethod error */
6918 GDBusMessage *reply;
6919 reply = g_dbus_message_new_method_error (data->message,
6920 "org.freedesktop.DBus.Error.UnknownMethod",
6921 _("Method '%s' on interface '%s' with signature '%s' does not exist"),
6922 g_dbus_message_get_member (data->message),
6923 g_dbus_message_get_interface (data->message),
6924 g_dbus_message_get_signature (data->message));
6925 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6926 g_object_unref (reply);
6932 /* called in GDBusWorker thread with connection's lock held */
6934 subtree_message_func (GDBusConnection *connection,
6935 ExportedSubtree *es,
6936 GDBusMessage *message)
6938 GSource *idle_source;
6939 SubtreeDeferredData *data;
6941 data = g_new0 (SubtreeDeferredData, 1);
6942 data->message = g_object_ref (message);
6945 /* defer this call to an idle handler in the right thread */
6946 idle_source = g_idle_source_new ();
6947 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
6948 g_source_set_callback (idle_source,
6949 process_subtree_vtable_message_in_idle_cb,
6951 (GDestroyNotify) subtree_deferred_data_free);
6952 g_source_set_name (idle_source, "[gio] process_subtree_vtable_message_in_idle_cb");
6953 g_source_attach (idle_source, es->context);
6954 g_source_unref (idle_source);
6956 /* since we own the entire subtree, handlers for objects not in the subtree have been
6957 * tried already by libdbus-1 - so we just need to ensure that we're always going
6958 * to reply to the message
6964 * g_dbus_connection_register_subtree:
6965 * @connection: a #GDBusConnection
6966 * @object_path: the object path to register the subtree at
6967 * @vtable: a #GDBusSubtreeVTable to enumerate, introspect and
6968 * dispatch nodes in the subtree
6969 * @flags: flags used to fine tune the behavior of the subtree
6970 * @user_data: data to pass to functions in @vtable
6971 * @user_data_free_func: function to call when the subtree is unregistered
6972 * @error: return location for error or %NULL
6974 * Registers a whole subtree of dynamic objects.
6976 * The @enumerate and @introspection functions in @vtable are used to
6977 * convey, to remote callers, what nodes exist in the subtree rooted
6980 * When handling remote calls into any node in the subtree, first the
6981 * @enumerate function is used to check if the node exists. If the node exists
6982 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6983 * the @introspection function is used to check if the node supports the
6984 * requested method. If so, the @dispatch function is used to determine
6985 * where to dispatch the call. The collected #GDBusInterfaceVTable and
6986 * #gpointer will be used to call into the interface vtable for processing
6989 * All calls into user-provided code will be invoked in the
6990 * [thread-default main context][g-main-context-push-thread-default]
6991 * of the thread you are calling this method from.
6993 * If an existing subtree is already registered at @object_path or
6994 * then @error is set to #G_IO_ERROR_EXISTS.
6996 * Note that it is valid to register regular objects (using
6997 * g_dbus_connection_register_object()) in a subtree registered with
6998 * g_dbus_connection_register_subtree() - if so, the subtree handler
6999 * is tried as the last resort. One way to think about a subtree
7000 * handler is to consider it a fallback handler for object paths not
7001 * registered via g_dbus_connection_register_object() or other bindings.
7003 * Note that @vtable will be copied so you cannot change it after
7006 * See this [server][gdbus-subtree-server] for an example of how to use
7009 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
7010 * that can be used with g_dbus_connection_unregister_subtree() .
7015 g_dbus_connection_register_subtree (GDBusConnection *connection,
7016 const gchar *object_path,
7017 const GDBusSubtreeVTable *vtable,
7018 GDBusSubtreeFlags flags,
7020 GDestroyNotify user_data_free_func,
7024 ExportedSubtree *es;
7026 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
7027 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
7028 g_return_val_if_fail (vtable != NULL, 0);
7029 g_return_val_if_fail (error == NULL || *error == NULL, 0);
7030 g_return_val_if_fail (check_initialized (connection), 0);
7034 CONNECTION_LOCK (connection);
7036 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
7042 _("A subtree is already exported for %s"),
7047 es = g_new0 (ExportedSubtree, 1);
7048 es->object_path = g_strdup (object_path);
7049 es->connection = connection;
7051 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
7053 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
7054 es->user_data = user_data;
7055 es->user_data_free_func = user_data_free_func;
7056 es->context = g_main_context_ref_thread_default ();
7058 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
7059 g_hash_table_insert (connection->map_id_to_es,
7060 GUINT_TO_POINTER (es->id),
7066 CONNECTION_UNLOCK (connection);
7071 /* ---------------------------------------------------------------------------------------------------- */
7074 * g_dbus_connection_unregister_subtree:
7075 * @connection: a #GDBusConnection
7076 * @registration_id: a subtree registration id obtained from
7077 * g_dbus_connection_register_subtree()
7079 * Unregisters a subtree.
7081 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise
7086 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
7087 guint registration_id)
7089 ExportedSubtree *es;
7092 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
7093 g_return_val_if_fail (check_initialized (connection), FALSE);
7097 CONNECTION_LOCK (connection);
7099 es = g_hash_table_lookup (connection->map_id_to_es,
7100 GUINT_TO_POINTER (registration_id));
7104 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
7105 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
7110 CONNECTION_UNLOCK (connection);
7115 /* ---------------------------------------------------------------------------------------------------- */
7117 /* may be called in any thread, with connection's lock held */
7119 handle_generic_ping_unlocked (GDBusConnection *connection,
7120 const gchar *object_path,
7121 GDBusMessage *message)
7123 GDBusMessage *reply;
7124 reply = g_dbus_message_new_method_reply (message);
7125 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7126 g_object_unref (reply);
7129 /* may be called in any thread, with connection's lock held */
7131 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
7132 const gchar *object_path,
7133 GDBusMessage *message)
7135 GDBusMessage *reply;
7138 if (connection->machine_id == NULL)
7143 connection->machine_id = _g_dbus_get_machine_id (&error);
7144 if (connection->machine_id == NULL)
7146 reply = g_dbus_message_new_method_error_literal (message,
7147 "org.freedesktop.DBus.Error.Failed",
7149 g_error_free (error);
7155 reply = g_dbus_message_new_method_reply (message);
7156 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
7158 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7159 g_object_unref (reply);
7162 /* may be called in any thread, with connection's lock held */
7164 handle_generic_introspect_unlocked (GDBusConnection *connection,
7165 const gchar *object_path,
7166 GDBusMessage *message)
7171 GDBusMessage *reply;
7173 /* first the header */
7174 s = g_string_new (NULL);
7175 introspect_append_header (s);
7177 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
7178 for (n = 0; registered != NULL && registered[n] != NULL; n++)
7179 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
7180 g_strfreev (registered);
7181 g_string_append (s, "</node>\n");
7183 reply = g_dbus_message_new_method_reply (message);
7184 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
7185 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7186 g_object_unref (reply);
7187 g_string_free (s, TRUE);
7190 /* may be called in any thread, with connection's lock held */
7192 handle_generic_unlocked (GDBusConnection *connection,
7193 GDBusMessage *message)
7196 const gchar *interface_name;
7197 const gchar *member;
7198 const gchar *signature;
7201 CONNECTION_ENSURE_LOCK (connection);
7205 interface_name = g_dbus_message_get_interface (message);
7206 member = g_dbus_message_get_member (message);
7207 signature = g_dbus_message_get_signature (message);
7208 path = g_dbus_message_get_path (message);
7210 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
7211 g_strcmp0 (member, "Introspect") == 0 &&
7212 g_strcmp0 (signature, "") == 0)
7214 handle_generic_introspect_unlocked (connection, path, message);
7217 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7218 g_strcmp0 (member, "Ping") == 0 &&
7219 g_strcmp0 (signature, "") == 0)
7221 handle_generic_ping_unlocked (connection, path, message);
7224 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7225 g_strcmp0 (member, "GetMachineId") == 0 &&
7226 g_strcmp0 (signature, "") == 0)
7228 handle_generic_get_machine_id_unlocked (connection, path, message);
7235 /* ---------------------------------------------------------------------------------------------------- */
7237 /* called in GDBusWorker thread with connection's lock held */
7239 distribute_method_call (GDBusConnection *connection,
7240 GDBusMessage *message)
7242 GDBusMessage *reply;
7244 ExportedSubtree *es;
7245 const gchar *object_path;
7246 const gchar *interface_name;
7247 const gchar *member;
7249 gchar *subtree_path;
7252 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
7254 interface_name = g_dbus_message_get_interface (message);
7255 member = g_dbus_message_get_member (message);
7256 path = g_dbus_message_get_path (message);
7257 subtree_path = g_strdup (path);
7258 needle = strrchr (subtree_path, '/');
7259 if (needle != NULL && needle != subtree_path)
7265 g_free (subtree_path);
7266 subtree_path = NULL;
7270 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
7272 _g_dbus_debug_print_lock ();
7273 g_print ("========================================================================\n"
7274 "GDBus-debug:Incoming:\n"
7275 " <<<< METHOD INVOCATION %s.%s()\n"
7277 " invoked by name %s\n"
7279 interface_name, member,
7281 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
7282 g_dbus_message_get_serial (message));
7283 _g_dbus_debug_print_unlock ();
7286 object_path = g_dbus_message_get_path (message);
7287 g_assert (object_path != NULL);
7289 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
7292 if (obj_message_func (connection, eo, message))
7296 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
7299 if (subtree_message_func (connection, es, message))
7303 if (subtree_path != NULL)
7305 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
7308 if (subtree_message_func (connection, es, message))
7313 if (handle_generic_unlocked (connection, message))
7316 /* if we end up here, the message has not been not handled - so return an error saying this */
7317 reply = g_dbus_message_new_method_error (message,
7318 "org.freedesktop.DBus.Error.UnknownMethod",
7319 _("No such interface '%s' on object at path %s"),
7322 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7323 g_object_unref (reply);
7326 g_free (subtree_path);
7329 /* ---------------------------------------------------------------------------------------------------- */
7331 /* Called in any user thread, with the message_bus_lock held. */
7333 message_bus_get_singleton (GBusType bus_type,
7337 const gchar *starter_bus;
7343 case G_BUS_TYPE_SESSION:
7344 ret = &the_session_bus;
7347 case G_BUS_TYPE_SYSTEM:
7348 ret = &the_system_bus;
7351 case G_BUS_TYPE_USER:
7352 ret = &the_user_bus;
7355 case G_BUS_TYPE_MACHINE:
7356 ret = &the_machine_bus;
7359 case G_BUS_TYPE_STARTER:
7360 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
7361 if (g_strcmp0 (starter_bus, "session") == 0)
7363 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
7366 else if (g_strcmp0 (starter_bus, "system") == 0)
7368 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
7373 if (starter_bus != NULL)
7377 G_IO_ERROR_INVALID_ARGUMENT,
7378 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
7379 " - unknown value '%s'"),
7384 g_set_error_literal (error,
7386 G_IO_ERROR_INVALID_ARGUMENT,
7387 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
7388 "variable is not set"));
7394 g_assert_not_reached ();
7402 /* Called in any user thread, without holding locks. */
7403 static GDBusConnection *
7404 get_uninitialized_connection (GBusType bus_type,
7405 GCancellable *cancellable,
7408 GWeakRef *singleton;
7409 GDBusConnection *ret;
7413 G_LOCK (message_bus_lock);
7414 singleton = message_bus_get_singleton (bus_type, error);
7415 if (singleton == NULL)
7418 ret = g_weak_ref_get (singleton);
7423 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
7424 if (address == NULL)
7426 ret = g_object_new (G_TYPE_DBUS_CONNECTION,
7428 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
7429 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
7430 "exit-on-close", TRUE,
7433 g_weak_ref_set (singleton, ret);
7437 g_assert (ret != NULL);
7440 G_UNLOCK (message_bus_lock);
7444 /* May be called from any thread. Must not hold message_bus_lock. */
7446 _g_bus_get_singleton_if_exists (GBusType bus_type)
7448 GWeakRef *singleton;
7449 GDBusConnection *ret = NULL;
7451 G_LOCK (message_bus_lock);
7452 singleton = message_bus_get_singleton (bus_type, NULL);
7453 if (singleton == NULL)
7456 ret = g_weak_ref_get (singleton);
7459 G_UNLOCK (message_bus_lock);
7465 * @bus_type: a #GBusType
7466 * @cancellable: (allow-none): a #GCancellable or %NULL
7467 * @error: return location for error or %NULL
7469 * Synchronously connects to the message bus specified by @bus_type.
7470 * Note that the returned object may shared with other callers,
7471 * e.g. if two separate parts of a process calls this function with
7472 * the same @bus_type, they will share the same object.
7474 * This is a synchronous failable function. See g_bus_get() and
7475 * g_bus_get_finish() for the asynchronous version.
7477 * The returned object is a singleton, that is, shared with other
7478 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7479 * event that you need a private message bus connection, use
7480 * g_dbus_address_get_for_bus_sync() and
7481 * g_dbus_connection_new_for_address().
7483 * Note that the returned #GDBusConnection object will (usually) have
7484 * the #GDBusConnection:exit-on-close property set to %TRUE.
7486 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7487 * Free with g_object_unref().
7492 g_bus_get_sync (GBusType bus_type,
7493 GCancellable *cancellable,
7496 GDBusConnection *connection;
7498 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7500 connection = get_uninitialized_connection (bus_type, cancellable, error);
7501 if (connection == NULL)
7504 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
7506 g_object_unref (connection);
7515 bus_get_async_initable_cb (GObject *source_object,
7519 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
7523 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
7527 g_assert (error != NULL);
7528 g_simple_async_result_take_error (simple, error);
7529 g_object_unref (source_object);
7533 g_simple_async_result_set_op_res_gpointer (simple,
7537 g_simple_async_result_complete_in_idle (simple);
7538 g_object_unref (simple);
7543 * @bus_type: a #GBusType
7544 * @cancellable: (allow-none): a #GCancellable or %NULL
7545 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
7546 * @user_data: the data to pass to @callback
7548 * Asynchronously connects to the message bus specified by @bus_type.
7550 * When the operation is finished, @callback will be invoked. You can
7551 * then call g_bus_get_finish() to get the result of the operation.
7553 * This is a asynchronous failable function. See g_bus_get_sync() for
7554 * the synchronous version.
7559 g_bus_get (GBusType bus_type,
7560 GCancellable *cancellable,
7561 GAsyncReadyCallback callback,
7564 GDBusConnection *connection;
7565 GSimpleAsyncResult *simple;
7568 simple = g_simple_async_result_new (NULL,
7572 g_simple_async_result_set_check_cancellable (simple, cancellable);
7575 connection = get_uninitialized_connection (bus_type, cancellable, &error);
7576 if (connection == NULL)
7578 g_assert (error != NULL);
7579 g_simple_async_result_take_error (simple, error);
7580 g_simple_async_result_complete_in_idle (simple);
7581 g_object_unref (simple);
7585 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
7588 bus_get_async_initable_cb,
7595 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
7597 * @error: return location for error or %NULL
7599 * Finishes an operation started with g_bus_get().
7601 * The returned object is a singleton, that is, shared with other
7602 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7603 * event that you need a private message bus connection, use
7604 * g_dbus_address_get_for_bus_sync() and
7605 * g_dbus_connection_new_for_address().
7607 * Note that the returned #GDBusConnection object will (usually) have
7608 * the #GDBusConnection:exit-on-close property set to %TRUE.
7610 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7611 * Free with g_object_unref().
7616 g_bus_get_finish (GAsyncResult *res,
7619 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
7621 GDBusConnection *ret;
7623 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7625 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
7629 if (g_simple_async_result_propagate_error (simple, error))
7632 object = g_simple_async_result_get_op_res_gpointer (simple);
7633 g_assert (object != NULL);
7634 ret = g_object_ref (G_DBUS_CONNECTION (object));
7640 /* ---------------------------------------------------------------------------------------------------- */