1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
18 * Author: David Zeuthen <davidz@redhat.com>
24 * - would be nice to expose GDBusAuthMechanism and an extension point
26 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
27 * the mechanism VFuncs need to be able to set an error.
29 * - Need to document other mechanisms/sources for determining the D-Bus
30 * address of a well-known bus.
32 * - e.g. on Win32 we need code like from here
34 * http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
36 * that was never copied over here because it originally was copy-paste
37 * from the GPLv2 / AFL 2.1 libdbus sources.
39 * - on OS X we need to look in launchd for the address
41 * https://bugs.freedesktop.org/show_bug.cgi?id=14259
43 * - on X11 we need to look in a X11 property on the X server
44 * - (we can also just use dbus-launch(1) from the D-Bus
47 * - (ideally) this requires D-Bus spec work because none of
48 * this has never really been specced out properly (except
51 * - Related to the above, we also need to be able to launch a message bus
52 * instance.... Since we don't want to write our own bus daemon we should
53 * launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
55 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
56 * to specify where the nonce is stored. This will allow people to use
57 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
58 * to easily achieve secure RPC via nonce-tcp.
60 * - need to expose an extension point for resolving D-Bus address and
61 * turning them into GIOStream objects. This will allow us to implement
62 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
64 * - see g_dbus_address_connect() in gdbusaddress.c
66 * - would be cute to use kernel-specific APIs to resolve fds for
67 * debug output when using G_DBUS_DEBUG=message, e.g. in addition to
69 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
71 * maybe we can show more information about what fd 21 really is.
72 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
73 * Initial experiments on Linux 2.6 suggests that the symlink looks
78 * e.g. not of much use.
80 * - GDBus High-Level docs
81 * - Proxy: properties, signals...
82 * - Connection: IOStream based, ::close, connection setup steps
83 * mainloop integration, threading
84 * - Differences from libdbus (extend "Migrating from")
85 * - the message handling thread
86 * - Using GVariant instead of GValue
87 * - Explain why the high-level API is a good thing and what
88 * kind of pitfalls it avoids
89 * - Export objects before claiming names
90 * - Talk about auto-starting services (cf. GBusNameWatcherFlags)
92 * - use abstract sockets in test code
93 * - right now it doesn't work, dbus-daemon(1) fails with
95 * /gdbus/connection/filter: Failed to start message bus: Failed to bind
96 * socket "/tmp/g-dbus-tests-pid-28531": Address already in use
97 * ** WARNING **: Error reading address from dbus daemon, 0 bytes read
107 #include "gdbusauth.h"
108 #include "gdbusutils.h"
109 #include "gdbusaddress.h"
110 #include "gdbusmessage.h"
111 #include "gdbusconnection.h"
112 #include "gdbuserror.h"
113 #include "gioenumtypes.h"
114 #include "gdbusintrospection.h"
115 #include "gdbusmethodinvocation.h"
116 #include "gdbusprivate.h"
117 #include "gdbusauthobserver.h"
118 #include "ginitable.h"
119 #include "gasyncinitable.h"
120 #include "giostream.h"
121 #include "gasyncresult.h"
122 #include "gsimpleasyncresult.h"
126 #include "gunixconnection.h"
127 #include "gunixfdmessage.h"
130 #include "glibintl.h"
133 * SECTION:gdbusconnection
134 * @short_description: D-Bus Connections
135 * @include: gio/gio.h
137 * The #GDBusConnection type is used for D-Bus connections to remote
138 * peers such as a message buses. It is a low-level API that offers a
139 * lot of flexibility. For instance, it lets you establish a connection
140 * over any transport that can by represented as an #GIOStream.
142 * This class is rarely used directly in D-Bus clients. If you are writing
143 * a D-Bus client, it is often easier to use the g_bus_own_name(),
144 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
146 * As an exception to the usual GLib rule that a particular object must not
147 * be used by two threads at the same time, #GDBusConnection's methods may be
148 * called from any thread. This is so that g_bus_get() and g_bus_get_sync()
149 * can safely return the same #GDBusConnection when called from any thread.
151 * Most of the ways to obtain a #GDBusConnection automatically initialize it
152 * (i.e. connect to D-Bus): for instance, g_dbus_connection_new() and
153 * g_bus_get(), and the synchronous versions of those methods, give you an
154 * initialized connection. Language bindings for GIO should use
155 * g_initable_new() or g_async_initable_new_async(), which also initialize the
158 * If you construct an uninitialized #GDBusConnection, such as via
159 * g_object_new(), you must initialize it via g_initable_init() or
160 * g_async_initable_init_async() before using its methods or properties.
161 * Calling methods or accessing properties on a #GDBusConnection that has not
162 * completed initialization successfully is considered to be invalid, and leads
163 * to undefined behaviour. In particular, if initialization fails with a
164 * #GError, the only valid thing you can do with that #GDBusConnection is to
165 * free it with g_object_unref().
167 * ## An example D-Bus server # {#gdbus-server}
169 * Here is an example for a D-Bus server:
170 * [gdbus-example-server.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-server.c)
172 * ## An example for exporting a subtree # {#gdbus-subtree-server}
174 * Here is an example for exporting a subtree:
175 * [gdbus-example-subtree.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-subtree.c)
177 * ## An example for file descriptor passing # {#gdbus-unix-fd-client}
179 * Here is an example for passing UNIX file descriptors:
180 * [gdbus-unix-fd-client.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-unix-fd-client.c)
182 * ## An example for exporting a GObject # {#gdbus-export}
184 * Here is an example for exporting a #GObject:
185 * [gdbus-example-export.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-export.c)
188 /* ---------------------------------------------------------------------------------------------------- */
190 typedef struct _GDBusConnectionClass GDBusConnectionClass;
193 * GDBusConnectionClass:
194 * @closed: Signal class handler for the #GDBusConnection::closed signal.
196 * Class structure for #GDBusConnection.
200 struct _GDBusConnectionClass
203 GObjectClass parent_class;
207 void (*closed) (GDBusConnection *connection,
208 gboolean remote_peer_vanished,
212 G_LOCK_DEFINE_STATIC (message_bus_lock);
214 static GWeakRef the_session_bus;
215 static GWeakRef the_system_bus;
216 static GWeakRef the_user_bus;
217 static GWeakRef the_machine_bus;
219 /* Extra pseudo-member of GDBusSendMessageFlags.
220 * Set by initable_init() to indicate that despite not being initialized yet,
221 * enough of the only-valid-after-init members are set that we can send a
222 * message, and we're being called from its thread, so no memory barrier is
223 * required before accessing them.
225 #define SEND_MESSAGE_FLAGS_INITIALIZING (1<<31)
227 /* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
228 #define CALL_FLAGS_INITIALIZING (1<<31)
230 /* ---------------------------------------------------------------------------------------------------- */
234 GDestroyNotify callback;
236 GMainContext *context;
237 } CallDestroyNotifyData;
240 call_destroy_notify_data_in_idle (gpointer user_data)
242 CallDestroyNotifyData *data = user_data;
243 data->callback (data->user_data);
248 call_destroy_notify_data_free (CallDestroyNotifyData *data)
250 if (data->context != NULL)
251 g_main_context_unref (data->context);
256 * call_destroy_notify: <internal>
257 * @context: (allow-none): A #GMainContext or %NULL.
258 * @callback: (allow-none): A #GDestroyNotify or %NULL.
259 * @user_data: Data to pass to @callback.
261 * Schedules @callback to run in @context.
264 call_destroy_notify (GMainContext *context,
265 GDestroyNotify callback,
268 GSource *idle_source;
269 CallDestroyNotifyData *data;
271 if (callback == NULL)
274 data = g_new0 (CallDestroyNotifyData, 1);
275 data->callback = callback;
276 data->user_data = user_data;
277 data->context = context;
278 if (data->context != NULL)
279 g_main_context_ref (data->context);
281 idle_source = g_idle_source_new ();
282 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
283 g_source_set_callback (idle_source,
284 call_destroy_notify_data_in_idle,
286 (GDestroyNotify) call_destroy_notify_data_free);
287 g_source_set_name (idle_source, "[gio] call_destroy_notify_data_in_idle");
288 g_source_attach (idle_source, data->context);
289 g_source_unref (idle_source);
295 /* ---------------------------------------------------------------------------------------------------- */
298 _g_strv_has_string (const gchar* const *haystack,
303 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
305 if (g_strcmp0 (haystack[n], needle) == 0)
311 /* ---------------------------------------------------------------------------------------------------- */
314 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
316 // TODO: for some reason this doesn't work on Windows
317 #define CONNECTION_ENSURE_LOCK(obj) do { \
318 if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock))) \
320 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
321 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
326 #define CONNECTION_LOCK(obj) do { \
327 g_mutex_lock (&(obj)->lock); \
330 #define CONNECTION_UNLOCK(obj) do { \
331 g_mutex_unlock (&(obj)->lock); \
334 /* Flags in connection->atomic_flags */
336 FLAG_INITIALIZED = 1 << 0,
337 FLAG_EXIT_ON_CLOSE = 1 << 1,
344 * The #GDBusConnection structure contains only private data and
345 * should only be accessed using the provided API.
349 struct _GDBusConnection
352 GObject parent_instance;
354 /* ------------------------------------------------------------------------ */
355 /* -- General object state ------------------------------------------------ */
356 /* ------------------------------------------------------------------------ */
358 /* General-purpose lock for most fields */
361 /* A lock used in the init() method of the GInitable interface - see comments
362 * in initable_init() for why a separate lock is needed.
364 * If you need both @lock and @init_lock, you must take @init_lock first.
368 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
369 * someone calls org.freedesktop.DBus.Peer.GetMachineId(). Protected by @lock.
373 /* The underlying stream used for communication
374 * Read-only after initable_init(), so it may be read if you either
375 * hold @init_lock or check for initialization first.
379 /* The object used for authentication (if any).
380 * Read-only after initable_init(), so it may be read if you either
381 * hold @init_lock or check for initialization first.
385 /* Last serial used. Protected by @lock. */
388 /* The object used to send/receive messages.
389 * Read-only after initable_init(), so it may be read if you either
390 * hold @init_lock or check for initialization first.
393 GKDBusWorker *kdbus_worker;
395 /* If connected to a message bus, this contains the unique name assigned to
396 * us by the bus (e.g. ":1.42").
397 * Read-only after initable_init(), so it may be read if you either
398 * hold @init_lock or check for initialization first.
400 gchar *bus_unique_name;
402 /* The GUID returned by the other side if we authenticed as a client or
403 * the GUID to use if authenticating as a server.
404 * Read-only after initable_init(), so it may be read if you either
405 * hold @init_lock or check for initialization first.
409 /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
410 * Inspect @initialization_error to see whether it succeeded or failed.
412 * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
414 * FLAG_CLOSED is the closed property. It may be read at any time, but
415 * may only be written while holding @lock.
417 volatile gint atomic_flags;
419 /* If the connection could not be established during initable_init(),
420 * this GError will be set.
421 * Read-only after initable_init(), so it may be read if you either
422 * hold @init_lock or check for initialization first.
424 GError *initialization_error;
426 /* The result of g_main_context_ref_thread_default() when the object
427 * was created (the GObject _init() function) - this is used for delivery
428 * of the :closed GObject signal.
430 * Only set in the GObject init function, so no locks are needed.
432 GMainContext *main_context_at_construction;
434 /* Read-only construct properties, no locks needed */
436 GDBusConnectionFlags flags;
438 /* Map used for managing method replies, protected by @lock */
439 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
441 /* Maps used for managing signal subscription, protected by @lock */
442 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
443 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
444 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
446 /* Maps used for managing exported objects and subtrees,
449 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
450 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
451 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
452 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
454 /* Map used for storing last used serials for each thread, protected by @lock */
455 GHashTable *map_thread_to_last_serial;
457 /* Structure used for message filters, protected by @lock */
460 /* Capabilities negotiated during authentication
461 * Read-only after initable_init(), so it may be read without holding a
462 * lock, if you check for initialization first.
464 GDBusCapabilityFlags capabilities;
466 /* Protected by @init_lock */
467 GDBusAuthObserver *authentication_observer;
469 /* Read-only after initable_init(), so it may be read if you either
470 * hold @init_lock or check for initialization first.
472 GCredentials *credentials;
474 /* set to TRUE when finalizing */
478 typedef struct ExportedObject ExportedObject;
479 static void exported_object_free (ExportedObject *eo);
481 typedef struct ExportedSubtree ExportedSubtree;
482 static void exported_subtree_free (ExportedSubtree *es);
500 PROP_CAPABILITY_FLAGS,
501 PROP_AUTHENTICATION_OBSERVER,
504 static void distribute_signals (GDBusConnection *connection,
505 GDBusMessage *message);
507 static void distribute_method_call (GDBusConnection *connection,
508 GDBusMessage *message);
510 static gboolean handle_generic_unlocked (GDBusConnection *connection,
511 GDBusMessage *message);
514 static void purge_all_signal_subscriptions (GDBusConnection *connection);
515 static void purge_all_filters (GDBusConnection *connection);
517 static void schedule_method_call (GDBusConnection *connection,
518 GDBusMessage *message,
519 guint registration_id,
520 guint subtree_registration_id,
521 const GDBusInterfaceInfo *interface_info,
522 const GDBusMethodInfo *method_info,
523 const GDBusPropertyInfo *property_info,
524 GVariant *parameters,
525 const GDBusInterfaceVTable *vtable,
526 GMainContext *main_context,
529 #define _G_ENSURE_LOCK(name) do { \
530 if (G_UNLIKELY (G_TRYLOCK(name))) \
532 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
533 "_G_ENSURE_LOCK: Lock '" #name "' is not locked"); \
537 static guint signals[LAST_SIGNAL] = { 0 };
539 static void initable_iface_init (GInitableIface *initable_iface);
540 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
542 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
543 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
544 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
548 * Check that all members of @connection that can only be accessed after
549 * the connection is initialized can safely be accessed. If not,
550 * log a critical warning. This function is a memory barrier.
552 * Returns: %TRUE if initialized
555 check_initialized (GDBusConnection *connection)
557 /* The access to @atomic_flags isn't conditional, so that this function
558 * provides a memory barrier for thread-safety even if checks are disabled.
559 * (If you don't want this stricter guarantee, you can call
560 * g_return_if_fail (check_initialized (c)).)
562 * This isn't strictly necessary now that we've decided use of an
563 * uninitialized GDBusConnection is undefined behaviour, but it seems
564 * better to be as deterministic as is feasible.
566 * (Anything that could suffer a crash from seeing undefined values
567 * must have a race condition - thread A initializes the connection while
568 * thread B calls a method without initialization, hoping that thread A will
569 * win the race - so its behaviour is undefined anyway.)
571 gint flags = g_atomic_int_get (&connection->atomic_flags);
573 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
575 /* We can safely access this, due to the memory barrier above */
576 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
582 MAY_BE_UNINITIALIZED = (1<<1)
583 } CheckUnclosedFlags;
586 * Check the same thing as check_initialized(), and also that the
587 * connection is not closed. If the connection is uninitialized,
588 * raise a critical warning (it's programmer error); if it's closed,
589 * raise a recoverable GError (it's a runtime error).
591 * This function is a memory barrier.
593 * Returns: %TRUE if initialized and not closed
596 check_unclosed (GDBusConnection *connection,
597 CheckUnclosedFlags check,
600 /* check_initialized() is effectively inlined, so we don't waste time
601 * doing two memory barriers
603 gint flags = g_atomic_int_get (&connection->atomic_flags);
605 if (!(check & MAY_BE_UNINITIALIZED))
607 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
608 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
611 if (flags & FLAG_CLOSED)
613 g_set_error_literal (error,
616 _("The connection is closed"));
623 static GHashTable *alive_connections = NULL;
626 g_dbus_connection_dispose (GObject *object)
628 GDBusConnection *connection = G_DBUS_CONNECTION (object);
630 G_LOCK (message_bus_lock);
631 CONNECTION_LOCK (connection);
632 if (connection->worker != NULL)
634 _g_dbus_worker_stop (connection->worker);
635 connection->worker = NULL;
636 if (alive_connections != NULL)
637 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
641 if (alive_connections != NULL)
642 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
644 CONNECTION_UNLOCK (connection);
645 G_UNLOCK (message_bus_lock);
647 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
648 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
652 g_dbus_connection_finalize (GObject *object)
654 GDBusConnection *connection = G_DBUS_CONNECTION (object);
656 connection->finalizing = TRUE;
658 purge_all_signal_subscriptions (connection);
660 purge_all_filters (connection);
661 g_ptr_array_unref (connection->filters);
663 if (connection->authentication_observer != NULL)
664 g_object_unref (connection->authentication_observer);
666 if (connection->auth != NULL)
667 g_object_unref (connection->auth);
669 if (connection->credentials)
670 g_object_unref (connection->credentials);
672 if (connection->stream != NULL)
674 g_object_unref (connection->stream);
675 connection->stream = NULL;
678 g_free (connection->address);
680 g_free (connection->guid);
681 g_free (connection->bus_unique_name);
683 if (connection->initialization_error != NULL)
684 g_error_free (connection->initialization_error);
686 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
688 g_hash_table_unref (connection->map_rule_to_signal_data);
689 g_hash_table_unref (connection->map_id_to_signal_data);
690 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
692 g_hash_table_unref (connection->map_id_to_ei);
693 g_hash_table_unref (connection->map_object_path_to_eo);
694 g_hash_table_unref (connection->map_id_to_es);
695 g_hash_table_unref (connection->map_object_path_to_es);
697 g_hash_table_unref (connection->map_thread_to_last_serial);
699 g_main_context_unref (connection->main_context_at_construction);
701 g_free (connection->machine_id);
703 g_mutex_clear (&connection->init_lock);
704 g_mutex_clear (&connection->lock);
706 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
709 /* called in any user thread, with the connection's lock not held */
711 g_dbus_connection_get_property (GObject *object,
716 GDBusConnection *connection = G_DBUS_CONNECTION (object);
721 g_value_set_object (value, g_dbus_connection_get_stream (connection));
725 g_value_set_string (value, g_dbus_connection_get_guid (connection));
728 case PROP_UNIQUE_NAME:
729 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
733 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
736 case PROP_EXIT_ON_CLOSE:
737 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
740 case PROP_CAPABILITY_FLAGS:
741 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
745 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
750 /* called in any user thread, with the connection's lock not held */
752 g_dbus_connection_set_property (GObject *object,
757 GDBusConnection *connection = G_DBUS_CONNECTION (object);
762 connection->stream = g_value_dup_object (value);
766 connection->guid = g_value_dup_string (value);
770 connection->address = g_value_dup_string (value);
774 connection->flags = g_value_get_flags (value);
777 case PROP_EXIT_ON_CLOSE:
778 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
781 case PROP_AUTHENTICATION_OBSERVER:
782 connection->authentication_observer = g_value_dup_object (value);
786 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
791 /* Base-class implementation of GDBusConnection::closed.
793 * Called in a user thread, by the main context that was thread-default when
794 * the object was constructed.
797 g_dbus_connection_real_closed (GDBusConnection *connection,
798 gboolean remote_peer_vanished,
801 gint flags = g_atomic_int_get (&connection->atomic_flags);
803 /* Because atomic int access is a memory barrier, we can safely read
804 * initialization_error without a lock, as long as we do it afterwards.
806 if (remote_peer_vanished &&
807 (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
808 (flags & FLAG_INITIALIZED) != 0 &&
809 connection->initialization_error == NULL)
813 g_printerr ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
816 g_quark_to_string (error->domain), error->code);
820 g_printerr ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
827 g_dbus_connection_class_init (GDBusConnectionClass *klass)
829 GObjectClass *gobject_class;
831 gobject_class = G_OBJECT_CLASS (klass);
833 gobject_class->finalize = g_dbus_connection_finalize;
834 gobject_class->dispose = g_dbus_connection_dispose;
835 gobject_class->set_property = g_dbus_connection_set_property;
836 gobject_class->get_property = g_dbus_connection_get_property;
838 klass->closed = g_dbus_connection_real_closed;
841 * GDBusConnection:stream:
843 * The underlying #GIOStream used for I/O.
845 * If this is passed on construction and is a #GSocketConnection,
846 * then the corresponding #GSocket will be put into non-blocking mode.
848 * While the #GDBusConnection is active, it will interact with this
849 * stream from a worker thread, so it is not safe to interact with
850 * the stream directly.
854 g_object_class_install_property (gobject_class,
856 g_param_spec_object ("stream",
858 P_("The underlying streams used for I/O"),
862 G_PARAM_CONSTRUCT_ONLY |
863 G_PARAM_STATIC_NAME |
864 G_PARAM_STATIC_BLURB |
865 G_PARAM_STATIC_NICK));
868 * GDBusConnection:address:
870 * A D-Bus address specifying potential endpoints that can be used
871 * when establishing the connection.
875 g_object_class_install_property (gobject_class,
877 g_param_spec_string ("address",
879 P_("D-Bus address specifying potential socket endpoints"),
882 G_PARAM_CONSTRUCT_ONLY |
883 G_PARAM_STATIC_NAME |
884 G_PARAM_STATIC_BLURB |
885 G_PARAM_STATIC_NICK));
888 * GDBusConnection:flags:
890 * Flags from the #GDBusConnectionFlags enumeration.
894 g_object_class_install_property (gobject_class,
896 g_param_spec_flags ("flags",
899 G_TYPE_DBUS_CONNECTION_FLAGS,
900 G_DBUS_CONNECTION_FLAGS_NONE,
902 G_PARAM_CONSTRUCT_ONLY |
903 G_PARAM_STATIC_NAME |
904 G_PARAM_STATIC_BLURB |
905 G_PARAM_STATIC_NICK));
908 * GDBusConnection:guid:
910 * The GUID of the peer performing the role of server when
913 * If you are constructing a #GDBusConnection and pass
914 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
915 * #GDBusConnection:flags property then you MUST also set this
916 * property to a valid guid.
918 * If you are constructing a #GDBusConnection and pass
919 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
920 * #GDBusConnection:flags property you will be able to read the GUID
921 * of the other peer here after the connection has been successfully
926 g_object_class_install_property (gobject_class,
928 g_param_spec_string ("guid",
930 P_("GUID of the server peer"),
934 G_PARAM_CONSTRUCT_ONLY |
935 G_PARAM_STATIC_NAME |
936 G_PARAM_STATIC_BLURB |
937 G_PARAM_STATIC_NICK));
940 * GDBusConnection:unique-name:
942 * The unique name as assigned by the message bus or %NULL if the
943 * connection is not open or not a message bus connection.
947 g_object_class_install_property (gobject_class,
949 g_param_spec_string ("unique-name",
951 P_("Unique name of bus connection"),
954 G_PARAM_STATIC_NAME |
955 G_PARAM_STATIC_BLURB |
956 G_PARAM_STATIC_NICK));
959 * GDBusConnection:closed:
961 * A boolean specifying whether the connection has been closed.
965 g_object_class_install_property (gobject_class,
967 g_param_spec_boolean ("closed",
969 P_("Whether the connection is closed"),
972 G_PARAM_STATIC_NAME |
973 G_PARAM_STATIC_BLURB |
974 G_PARAM_STATIC_NICK));
977 * GDBusConnection:exit-on-close:
979 * A boolean specifying whether the process will be terminated (by
980 * calling `raise(SIGTERM)`) if the connection is closed by the
983 * Note that #GDBusConnection objects returned by g_bus_get_finish()
984 * and g_bus_get_sync() will (usually) have this property set to %TRUE.
988 g_object_class_install_property (gobject_class,
990 g_param_spec_boolean ("exit-on-close",
992 P_("Whether the process is terminated when the connection is closed"),
996 G_PARAM_STATIC_NAME |
997 G_PARAM_STATIC_BLURB |
998 G_PARAM_STATIC_NICK));
1001 * GDBusConnection:capabilities:
1003 * Flags from the #GDBusCapabilityFlags enumeration
1004 * representing connection features negotiated with the other peer.
1008 g_object_class_install_property (gobject_class,
1009 PROP_CAPABILITY_FLAGS,
1010 g_param_spec_flags ("capabilities",
1013 G_TYPE_DBUS_CAPABILITY_FLAGS,
1014 G_DBUS_CAPABILITY_FLAGS_NONE,
1016 G_PARAM_STATIC_NAME |
1017 G_PARAM_STATIC_BLURB |
1018 G_PARAM_STATIC_NICK));
1021 * GDBusConnection:authentication-observer:
1023 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
1027 g_object_class_install_property (gobject_class,
1028 PROP_AUTHENTICATION_OBSERVER,
1029 g_param_spec_object ("authentication-observer",
1030 P_("Authentication Observer"),
1031 P_("Object used to assist in the authentication process"),
1032 G_TYPE_DBUS_AUTH_OBSERVER,
1034 G_PARAM_CONSTRUCT_ONLY |
1035 G_PARAM_STATIC_NAME |
1036 G_PARAM_STATIC_BLURB |
1037 G_PARAM_STATIC_NICK));
1040 * GDBusConnection::closed:
1041 * @connection: the #GDBusConnection emitting the signal
1042 * @remote_peer_vanished: %TRUE if @connection is closed because the
1043 * remote peer closed its end of the connection
1044 * @error: (allow-none): a #GError with more details about the event or %NULL
1046 * Emitted when the connection is closed.
1048 * The cause of this event can be
1050 * - If g_dbus_connection_close() is called. In this case
1051 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
1053 * - If the remote peer closes the connection. In this case
1054 * @remote_peer_vanished is set to %TRUE and @error is set.
1056 * - If the remote peer sends invalid or malformed data. In this
1057 * case @remote_peer_vanished is set to %FALSE and @error is set.
1059 * Upon receiving this signal, you should give up your reference to
1060 * @connection. You are guaranteed that this signal is emitted only
1065 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
1066 G_TYPE_DBUS_CONNECTION,
1068 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1079 g_dbus_connection_init (GDBusConnection *connection)
1081 g_mutex_init (&connection->lock);
1082 g_mutex_init (&connection->init_lock);
1084 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
1086 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1088 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1090 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1093 (GDestroyNotify) g_ptr_array_unref);
1095 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1098 (GDestroyNotify) exported_object_free);
1100 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1103 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1106 (GDestroyNotify) exported_subtree_free);
1108 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1111 connection->map_thread_to_last_serial = g_hash_table_new (g_direct_hash,
1114 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1116 connection->filters = g_ptr_array_new ();
1120 * g_dbus_connection_get_stream:
1121 * @connection: a #GDBusConnection
1123 * Gets the underlying stream used for IO.
1125 * While the #GDBusConnection is active, it will interact with this
1126 * stream from a worker thread, so it is not safe to interact with
1127 * the stream directly.
1129 * Returns: (transfer none): the stream used for IO
1134 g_dbus_connection_get_stream (GDBusConnection *connection)
1136 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1138 /* do not use g_return_val_if_fail(), we want the memory barrier */
1139 if (!check_initialized (connection))
1142 return connection->stream;
1146 * g_dbus_connection_start_message_processing:
1147 * @connection: a #GDBusConnection
1149 * If @connection was created with
1150 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1151 * starts processing messages. Does nothing on if @connection wasn't
1152 * created with this flag or if the method has already been called.
1157 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1159 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1161 /* do not use g_return_val_if_fail(), we want the memory barrier */
1162 if (!check_initialized (connection))
1165 g_assert (connection->worker != 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_request_name:
1599 * @connection: a #GDBusConnection
1600 * @name: well-known bus name (name to request)
1601 * @flags: a set of flags from the GBusNameOwnerFlags enumeration
1602 * @error: return location for error or %NULL
1604 * Synchronously acquires name on the bus and returns status code.
1606 * The calling thread is blocked until a reply is received.
1608 * Returns: status code or %G_BUS_REQUEST_NAME_FLAGS_ERROR
1613 GBusRequestNameReplyFlags
1614 g_dbus_request_name (GDBusConnection *connection,
1616 GBusNameOwnerFlags flags,
1620 guint32 request_name_reply;
1622 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_BUS_RELEASE_NAME_FLAGS_ERROR);
1623 g_return_val_if_fail (g_dbus_is_name (name) && !g_dbus_is_unique_name (name), G_BUS_RELEASE_NAME_FLAGS_ERROR);
1624 g_return_val_if_fail (error == NULL || *error == NULL, G_BUS_RELEASE_NAME_FLAGS_ERROR);
1626 if (connection->kdbus_worker)
1627 result = _g_kdbus_RequestName (connection->kdbus_worker, name, flags, error);
1629 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/org/freedesktop/DBus",
1630 "org.freedesktop.DBus", "RequestName",
1631 g_variant_new ("(su)", name, flags), G_VARIANT_TYPE ("(u)"),
1632 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1636 g_variant_get (result, "(u)", &request_name_reply);
1637 g_variant_unref (result);
1640 request_name_reply = G_BUS_REQUEST_NAME_FLAGS_ERROR;
1642 return (GBusRequestNameReplyFlags) request_name_reply;
1646 * g_dbus_release_name:
1647 * @connection: a #GDBusConnection
1648 * @name: well-known bus name (name to release)
1649 * @error: return location for error or %NULL
1651 * Synchronously releases name on the bus and returns status code.
1653 * The calling thread is blocked until a reply is received.
1655 * Returns: status code or %G_BUS_RELEASE_NAME_FLAGS_ERROR
1660 GBusReleaseNameReplyFlags
1661 g_dbus_release_name (GDBusConnection *connection,
1666 guint32 release_name_reply;
1668 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_BUS_RELEASE_NAME_FLAGS_ERROR);
1669 g_return_val_if_fail (g_dbus_is_name (name) && !g_dbus_is_unique_name (name), G_BUS_RELEASE_NAME_FLAGS_ERROR);
1670 g_return_val_if_fail (error == NULL || *error == NULL, G_BUS_RELEASE_NAME_FLAGS_ERROR);
1672 if (connection->kdbus_worker)
1673 result = _g_kdbus_ReleaseName (connection->kdbus_worker, name, error);
1675 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/org/freedesktop/DBus",
1676 "org.freedesktop.DBus", "ReleaseName",
1677 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(u)"),
1678 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1682 g_variant_get (result, "(u)", &release_name_reply);
1683 g_variant_unref (result);
1686 release_name_reply = G_BUS_RELEASE_NAME_FLAGS_ERROR;
1688 return (GBusReleaseNameReplyFlags) release_name_reply;
1692 * g_dbus_get_bus_id:
1693 * @connection: a #GDBusConnection
1694 * @error: return location for error or %NULL
1696 * Synchronously returns the unique ID of the bus.
1698 * The calling thread is blocked until a reply is received.
1700 * Returns: the unique ID of the bus or %NULL if @error is set.
1701 * Free with g_free().
1706 g_dbus_get_bus_id (GDBusConnection *connection,
1712 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1713 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1718 if (connection->kdbus_worker)
1720 result = _g_kdbus_GetBusId (connection->kdbus_worker, error);
1724 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1725 "org.freedesktop.DBus", "GetId",
1726 NULL, G_VARIANT_TYPE ("(s)"),
1727 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1732 g_variant_get (result, "(s)", &bus_id);
1733 g_variant_unref (result);
1742 LIST_ACTIVATABLE_NAMES,
1744 } GDBusListNameType;
1747 _g_dbus_get_list_internal (GDBusConnection *connection,
1749 GDBusListNameType list_name_type,
1761 if (list_name_type == LIST_QUEUED_OWNERS)
1763 if (connection->kdbus_worker)
1764 result = _g_kdbus_GetListQueuedOwners (connection->kdbus_worker, name, error);
1766 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1767 "org.freedesktop.DBus", "ListQueuedOwners",
1768 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(as)"),
1769 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1775 if (list_name_type == LIST_NAMES)
1776 method_name = "ListNames";
1778 method_name = "ListActivatableNames";
1780 if (connection->kdbus_worker)
1781 result = _g_kdbus_GetListNames (connection->kdbus_worker, list_name_type, error);
1783 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1784 "org.freedesktop.DBus", method_name,
1785 NULL, G_VARIANT_TYPE ("(as)"),
1786 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1791 g_variant_get (result, "(as)", &iter);
1792 n = g_variant_iter_n_children (iter);
1793 strv = g_new (gchar *, n + 1);
1796 while (g_variant_iter_loop (iter, "s", &str))
1798 strv[i] = g_strdup (str);
1803 g_variant_iter_free (iter);
1804 g_variant_unref (result);
1811 * g_dbus_get_list_names:
1812 * @connection: a #GDBusConnection
1813 * @error: return location for error or %NULL
1815 * Synchronously returns a list of all currently-owned names on the bus.
1817 * The calling thread is blocked until a reply is received.
1819 * Returns: a list of all currently-owned names on the bus or %NULL if
1820 * @error is set. Free with g_strfreev().
1825 g_dbus_get_list_names (GDBusConnection *connection,
1830 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1831 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1833 strv = _g_dbus_get_list_internal (connection, NULL, LIST_NAMES, error);
1839 * g_dbus_get_list_activatable_names:
1840 * @connection: a #GDBusConnection
1841 * @error: return location for error or %NULL
1843 * Synchronously returns a list of all names that can be activated on the bus.
1845 * The calling thread is blocked until a reply is received.
1847 * Returns: a list of all names that can be activated on the bus or %NULL if
1848 * @error is set. Free with g_strfreev().
1853 g_dbus_get_list_activatable_names (GDBusConnection *connection,
1858 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1859 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1861 strv = _g_dbus_get_list_internal (connection, NULL, LIST_ACTIVATABLE_NAMES, error);
1867 * g_dbus_get_list_queued_names:
1868 * @connection: a #GDBusConnection
1869 * @name: a unique or well-known bus name
1870 * @error: return location for error or %NULL
1872 * Synchronously returns the unique bus names of connections currently queued
1875 * If @name contains a value not compatible with the D-Bus syntax and naming
1876 * conventions for bus names, the operation returns %NULL and @error is set.
1878 * The calling thread is blocked until a reply is received.
1880 * Returns: the unique bus names of connections currently queued for the @name
1881 * or %NULL if @error is set. Free with g_strfreev().
1886 g_dbus_get_list_queued_owners (GDBusConnection *connection,
1892 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1893 g_return_val_if_fail (name == NULL || g_dbus_is_name (name), NULL);
1894 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1896 strv = _g_dbus_get_list_internal (connection, name, LIST_QUEUED_OWNERS, error);
1902 * g_dbus_get_name_owner:
1903 * @connection: a #GDBusConnection
1904 * @name: well-known bus name to get the owner of
1905 * @error: return location for error or %NULL
1907 * Synchronously returns the unique connection name of the primary owner of
1908 * the name given. If the requested name doesn't have an owner, an @error is
1911 * If @name contains a value not compatible with the D-Bus syntax and naming
1912 * conventions for bus names, the operation returns %NULL and @error is set.
1914 * The calling thread is blocked until a reply is received.
1916 * Returns: the unique connection name of the primary owner of the
1917 * name given. If the requested name doesn't have an owner, function
1918 * returns %NULL and @error is set. Free with g_free().
1923 g_dbus_get_name_owner (GDBusConnection *connection,
1930 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1931 g_return_val_if_fail (name == NULL || g_dbus_is_name (name), NULL);
1932 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1937 if (connection->kdbus_worker)
1938 result = _g_kdbus_GetNameOwner (connection->kdbus_worker, name, error);
1940 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1941 "org.freedesktop.DBus", "GetNameOwner",
1942 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(s)"),
1943 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1946 g_variant_get (result, "(s)", &name_owner);
1947 g_variant_unref (result);
1956 * g_dbus_get_connection_pid:
1957 * @connection: a #GDBusConnection
1958 * @name: a unique or well-known bus name of the connection to query
1959 * @error: return location for error or %NULL
1961 * Synchronously returns the Unix process ID of the process connected to the
1962 * bus. If unable to determine it, an @error is returned.
1964 * If @name contains a value not compatible with the D-Bus syntax and naming
1965 * conventions for bus names, the operation returns (guint32) -1 and @error
1968 * The calling thread is blocked until a reply is received.
1970 * Returns: the Unix process ID of the process connected to the bus or
1971 * (guint32) -1 if @error is set.
1976 g_dbus_get_connection_pid (GDBusConnection *connection,
1983 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), -1);
1984 g_return_val_if_fail (name == NULL || g_dbus_is_name (name), -1);
1985 g_return_val_if_fail (error == NULL || *error == NULL, -1);
1990 if (connection->kdbus_worker)
1991 result = _g_kdbus_GetConnectionUnixProcessID (connection->kdbus_worker, name, error);
1993 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1994 "org.freedesktop.DBus", "GetConnectionUnixProcessID",
1995 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(u)"),
1996 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1999 g_variant_get (result, "(u)", &pid);
2000 g_variant_unref (result);
2007 * g_dbus_get_connection_uid:
2008 * @connection: a #GDBusConnection
2009 * @name: a unique or well-known bus name of the connection to query
2010 * @error: return location for error or %NULL
2012 * Synchronously returns the Unix user ID of the process connected to the
2013 * bus. If unable to determine it, an @error is returned.
2015 * If @name contains a value not compatible with the D-Bus syntax and naming
2016 * conventions for bus names, the operation returns (guint32) -1 and @error
2019 * The calling thread is blocked until a reply is received.
2021 * Returns: the Unix user ID of the process connected to the bus or
2022 * (guint32) -1 if @error is set.
2027 g_dbus_get_connection_uid (GDBusConnection *connection,
2034 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), -1);
2035 g_return_val_if_fail (name == NULL || g_dbus_is_name (name), -1);
2036 g_return_val_if_fail (error == NULL || *error == NULL, -1);
2041 if (connection->kdbus_worker)
2042 result = _g_kdbus_GetConnectionUnixUser (connection->kdbus_worker, name, error);
2044 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
2045 "org.freedesktop.DBus", "GetConnectionUnixUser",
2046 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(u)"),
2047 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
2050 g_variant_get (result, "(u)", &uid);
2051 g_variant_unref (result);
2057 /* ---------------------------------------------------------------------------------------------------- */
2060 * g_dbus_connection_get_last_serial:
2061 * @connection: a #GDBusConnection
2063 * Retrieves the last serial number assigned to a #GDBusMessage on
2064 * the current thread. This includes messages sent via both low-level
2065 * API such as g_dbus_connection_send_message() as well as
2066 * high-level API such as g_dbus_connection_emit_signal(),
2067 * g_dbus_connection_call() or g_dbus_proxy_call().
2069 * Returns: the last used serial or zero when no message has been sent
2070 * within the current thread
2075 g_dbus_connection_get_last_serial (GDBusConnection *connection)
2079 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2081 CONNECTION_LOCK (connection);
2082 ret = GPOINTER_TO_UINT (g_hash_table_lookup (connection->map_thread_to_last_serial,
2084 CONNECTION_UNLOCK (connection);
2089 /* ---------------------------------------------------------------------------------------------------- */
2091 /* Can be called by any thread, with the connection lock held */
2093 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
2094 GDBusMessage *message,
2095 GDBusSendMessageFlags flags,
2096 volatile guint32 *out_serial,
2101 guint32 serial_to_use;
2104 CONNECTION_ENSURE_LOCK (connection);
2106 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2107 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
2109 /* TODO: check all necessary headers are present */
2114 if (out_serial != NULL)
2117 /* If we're in initable_init(), don't check for being initialized, to avoid
2118 * chicken-and-egg problems. initable_init() is responsible for setting up
2119 * our prerequisites (mainly connection->worker), and only calling us
2120 * from its own thread (so no memory barrier is needed).
2122 if (!check_unclosed (connection,
2123 (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
2127 blob = g_dbus_message_to_blob (message,
2129 connection->capabilities,
2135 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
2136 g_dbus_message_set_serial (message, ++connection->last_serial);
2138 serial_to_use = g_dbus_message_get_serial (message);
2140 g_dbus_message_lock (message);
2145 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
2148 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
2151 g_assert_not_reached ();
2156 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
2157 blob_size, serial_to_use, connection);
2158 g_printerr ("----\n");
2159 hexdump (blob, blob_size);
2160 g_printerr ("----\n");
2163 /* TODO: use connection->auth to encode the blob */
2165 if (out_serial != NULL)
2166 *out_serial = serial_to_use;
2168 /* store used serial for the current thread */
2169 /* TODO: watch the thread disposal and remove associated record
2171 * - see https://bugzilla.gnome.org/show_bug.cgi?id=676825#c7
2173 g_hash_table_replace (connection->map_thread_to_last_serial,
2175 GUINT_TO_POINTER (serial_to_use));
2177 if (connection->worker)
2178 _g_dbus_worker_send_message (connection->worker,
2183 g_kdbus_worker_send_message (connection->kdbus_worker, message, error);
2185 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
2196 * g_dbus_connection_send_message:
2197 * @connection: a #GDBusConnection
2198 * @message: a #GDBusMessage
2199 * @flags: flags affecting how the message is sent
2200 * @out_serial: (out) (allow-none): return location for serial number assigned
2201 * to @message when sending it or %NULL
2202 * @error: Return location for error or %NULL
2204 * Asynchronously sends @message to the peer represented by @connection.
2206 * Unless @flags contain the
2207 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2208 * will be assigned by @connection and set on @message via
2209 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2210 * serial number used will be written to this location prior to
2211 * submitting the message to the underlying transport.
2213 * If @connection is closed then the operation will fail with
2214 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
2215 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2217 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2218 * for an example of how to use this low-level API to send and receive
2219 * UNIX file descriptors.
2221 * Note that @message must be unlocked, unless @flags contain the
2222 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2224 * Returns: %TRUE if the message was well-formed and queued for
2225 * transmission, %FALSE if @error is set
2230 g_dbus_connection_send_message (GDBusConnection *connection,
2231 GDBusMessage *message,
2232 GDBusSendMessageFlags flags,
2233 volatile guint32 *out_serial,
2238 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2239 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
2240 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
2241 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2243 CONNECTION_LOCK (connection);
2244 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
2245 CONNECTION_UNLOCK (connection);
2249 /* ---------------------------------------------------------------------------------------------------- */
2253 volatile gint ref_count;
2254 GDBusConnection *connection;
2256 GSimpleAsyncResult *simple;
2258 GMainContext *main_context;
2260 GCancellable *cancellable;
2262 gulong cancellable_handler_id;
2264 GSource *timeout_source;
2269 /* Can be called from any thread with or without lock held */
2270 static SendMessageData *
2271 send_message_data_ref (SendMessageData *data)
2273 g_atomic_int_inc (&data->ref_count);
2277 /* Can be called from any thread with or without lock held */
2279 send_message_data_unref (SendMessageData *data)
2281 if (g_atomic_int_dec_and_test (&data->ref_count))
2283 g_assert (data->timeout_source == NULL);
2284 g_assert (data->simple == NULL);
2285 g_assert (data->cancellable_handler_id == 0);
2286 g_object_unref (data->connection);
2287 if (data->cancellable != NULL)
2288 g_object_unref (data->cancellable);
2289 g_main_context_unref (data->main_context);
2294 /* ---------------------------------------------------------------------------------------------------- */
2296 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
2298 send_message_with_reply_deliver (SendMessageData *data, gboolean remove)
2300 CONNECTION_ENSURE_LOCK (data->connection);
2302 g_assert (!data->delivered);
2304 data->delivered = TRUE;
2306 g_simple_async_result_complete_in_idle (data->simple);
2307 g_object_unref (data->simple);
2308 data->simple = NULL;
2310 if (data->timeout_source != NULL)
2312 g_source_destroy (data->timeout_source);
2313 data->timeout_source = NULL;
2315 if (data->cancellable_handler_id > 0)
2317 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
2318 data->cancellable_handler_id = 0;
2323 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
2324 GUINT_TO_POINTER (data->serial)));
2327 send_message_data_unref (data);
2330 /* ---------------------------------------------------------------------------------------------------- */
2332 /* Can be called from any thread with lock held */
2334 send_message_data_deliver_reply_unlocked (SendMessageData *data,
2335 GDBusMessage *reply)
2337 if (data->delivered)
2340 g_simple_async_result_set_op_res_gpointer (data->simple,
2341 g_object_ref (reply),
2344 send_message_with_reply_deliver (data, TRUE);
2350 /* ---------------------------------------------------------------------------------------------------- */
2352 /* Called from a user thread, lock is not held */
2354 send_message_with_reply_cancelled_idle_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_CANCELLED,
2365 _("Operation was cancelled"));
2367 send_message_with_reply_deliver (data, TRUE);
2370 CONNECTION_UNLOCK (data->connection);
2374 /* Can be called from any thread with or without lock held */
2376 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
2379 SendMessageData *data = user_data;
2380 GSource *idle_source;
2382 /* postpone cancellation to idle handler since we may be called directly
2383 * via g_cancellable_connect() (e.g. holding lock)
2385 idle_source = g_idle_source_new ();
2386 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
2387 g_source_set_callback (idle_source,
2388 send_message_with_reply_cancelled_idle_cb,
2389 send_message_data_ref (data),
2390 (GDestroyNotify) send_message_data_unref);
2391 g_source_set_name (idle_source, "[gio] send_message_with_reply_cancelled_idle_cb");
2392 g_source_attach (idle_source, data->main_context);
2393 g_source_unref (idle_source);
2396 /* ---------------------------------------------------------------------------------------------------- */
2398 /* Called from a user thread, lock is not held */
2400 send_message_with_reply_timeout_cb (gpointer user_data)
2402 SendMessageData *data = user_data;
2404 CONNECTION_LOCK (data->connection);
2405 if (data->delivered)
2408 g_simple_async_result_set_error (data->simple,
2410 G_IO_ERROR_TIMED_OUT,
2411 _("Timeout was reached"));
2413 send_message_with_reply_deliver (data, TRUE);
2416 CONNECTION_UNLOCK (data->connection);
2421 /* ---------------------------------------------------------------------------------------------------- */
2423 /* Called from a user thread, connection's lock is held */
2425 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
2426 GDBusMessage *message,
2427 GDBusSendMessageFlags flags,
2429 volatile guint32 *out_serial,
2430 GCancellable *cancellable,
2431 GAsyncReadyCallback callback,
2434 GSimpleAsyncResult *simple;
2435 SendMessageData *data;
2437 volatile guint32 serial;
2441 if (out_serial == NULL)
2442 out_serial = &serial;
2444 if (timeout_msec == -1)
2445 timeout_msec = 25 * 1000;
2447 simple = g_simple_async_result_new (G_OBJECT (connection),
2450 g_dbus_connection_send_message_with_reply);
2451 g_simple_async_result_set_check_cancellable (simple, cancellable);
2453 if (g_cancellable_is_cancelled (cancellable))
2455 g_simple_async_result_set_error (simple,
2457 G_IO_ERROR_CANCELLED,
2458 _("Operation was cancelled"));
2459 g_simple_async_result_complete_in_idle (simple);
2460 g_object_unref (simple);
2465 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
2467 g_simple_async_result_take_error (simple, error);
2468 g_simple_async_result_complete_in_idle (simple);
2469 g_object_unref (simple);
2473 data = g_new0 (SendMessageData, 1);
2474 data->ref_count = 1;
2475 data->connection = g_object_ref (connection);
2476 data->simple = simple;
2477 data->serial = *out_serial;
2478 data->main_context = g_main_context_ref_thread_default ();
2480 if (cancellable != NULL)
2482 data->cancellable = g_object_ref (cancellable);
2483 data->cancellable_handler_id = g_cancellable_connect (cancellable,
2484 G_CALLBACK (send_message_with_reply_cancelled_cb),
2485 send_message_data_ref (data),
2486 (GDestroyNotify) send_message_data_unref);
2489 if (timeout_msec != G_MAXINT)
2491 data->timeout_source = g_timeout_source_new (timeout_msec);
2492 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
2493 g_source_set_callback (data->timeout_source,
2494 send_message_with_reply_timeout_cb,
2495 send_message_data_ref (data),
2496 (GDestroyNotify) send_message_data_unref);
2497 g_source_attach (data->timeout_source, data->main_context);
2498 g_source_unref (data->timeout_source);
2501 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
2502 GUINT_TO_POINTER (*out_serial),
2510 * g_dbus_connection_send_message_with_reply:
2511 * @connection: a #GDBusConnection
2512 * @message: a #GDBusMessage
2513 * @flags: flags affecting how the message is sent
2514 * @timeout_msec: the timeout in milliseconds, -1 to use the default
2515 * timeout or %G_MAXINT for no timeout
2516 * @out_serial: (out) (allow-none): return location for serial number assigned
2517 * to @message when sending it or %NULL
2518 * @cancellable: (allow-none): a #GCancellable or %NULL
2519 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request
2520 * is satisfied or %NULL if you don't care about the result
2521 * @user_data: The data to pass to @callback
2523 * Asynchronously sends @message to the peer represented by @connection.
2525 * Unless @flags contain the
2526 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2527 * will be assigned by @connection and set on @message via
2528 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2529 * serial number used will be written to this location prior to
2530 * submitting the message to the underlying transport.
2532 * If @connection is closed then the operation will fail with
2533 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2534 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2535 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2537 * This is an asynchronous method. When the operation is finished, @callback
2538 * will be invoked in the
2539 * [thread-default main context][g-main-context-push-thread-default]
2540 * of the thread you are calling this method from. You can then call
2541 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
2542 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
2544 * Note that @message must be unlocked, unless @flags contain the
2545 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2547 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2548 * for an example of how to use this low-level API to send and receive
2549 * UNIX file descriptors.
2554 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
2555 GDBusMessage *message,
2556 GDBusSendMessageFlags flags,
2558 volatile guint32 *out_serial,
2559 GCancellable *cancellable,
2560 GAsyncReadyCallback callback,
2563 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2564 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2565 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2566 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2568 CONNECTION_LOCK (connection);
2569 g_dbus_connection_send_message_with_reply_unlocked (connection,
2577 CONNECTION_UNLOCK (connection);
2581 * g_dbus_connection_send_message_with_reply_finish:
2582 * @connection: a #GDBusConnection
2583 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
2584 * g_dbus_connection_send_message_with_reply()
2585 * @error: teturn location for error or %NULL
2587 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2589 * Note that @error is only set if a local in-process error
2590 * occurred. That is to say that the returned #GDBusMessage object may
2591 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2592 * g_dbus_message_to_gerror() to transcode this to a #GError.
2594 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2595 * for an example of how to use this low-level API to send and receive
2596 * UNIX file descriptors.
2598 * Returns: (transfer full): a locked #GDBusMessage or %NULL if @error is set
2603 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2607 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2608 GDBusMessage *reply;
2610 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2611 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2615 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
2617 if (g_simple_async_result_propagate_error (simple, error))
2620 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
2626 /* ---------------------------------------------------------------------------------------------------- */
2631 GMainContext *context;
2633 } SendMessageSyncData;
2635 /* Called from a user thread, lock is not held */
2637 send_message_with_reply_sync_cb (GDBusConnection *connection,
2641 SendMessageSyncData *data = user_data;
2642 data->res = g_object_ref (res);
2643 g_main_loop_quit (data->loop);
2647 * g_dbus_connection_send_message_with_reply_sync:
2648 * @connection: a #GDBusConnection
2649 * @message: a #GDBusMessage
2650 * @flags: flags affecting how the message is sent.
2651 * @timeout_msec: the timeout in milliseconds, -1 to use the default
2652 * timeout or %G_MAXINT for no timeout
2653 * @out_serial: (out) (allow-none): return location for serial number
2654 * assigned to @message when sending it or %NULL
2655 * @cancellable: (allow-none): a #GCancellable or %NULL
2656 * @error: return location for error or %NULL
2658 * Synchronously sends @message to the peer represented by @connection
2659 * and blocks the calling thread until a reply is received or the
2660 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2661 * for the asynchronous version of this method.
2663 * Unless @flags contain the
2664 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2665 * will be assigned by @connection and set on @message via
2666 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2667 * serial number used will be written to this location prior to
2668 * submitting the message to the underlying transport.
2670 * If @connection is closed then the operation will fail with
2671 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2672 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2673 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2675 * Note that @error is only set if a local in-process error
2676 * occurred. That is to say that the returned #GDBusMessage object may
2677 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2678 * g_dbus_message_to_gerror() to transcode this to a #GError.
2680 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2681 * for an example of how to use this low-level API to send and receive
2682 * UNIX file descriptors.
2684 * Note that @message must be unlocked, unless @flags contain the
2685 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2687 * Returns: (transfer full): a locked #GDBusMessage that is the reply
2688 * to @message or %NULL if @error is set
2693 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2694 GDBusMessage *message,
2695 GDBusSendMessageFlags flags,
2697 volatile guint32 *out_serial,
2698 GCancellable *cancellable,
2701 SendMessageSyncData *data;
2702 GDBusMessage *reply;
2704 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2705 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2706 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2707 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2708 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2710 data = g_new0 (SendMessageSyncData, 1);
2711 data->context = g_main_context_new ();
2712 data->loop = g_main_loop_new (data->context, FALSE);
2714 g_main_context_push_thread_default (data->context);
2716 g_dbus_connection_send_message_with_reply (connection,
2722 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2724 g_main_loop_run (data->loop);
2725 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2729 g_main_context_pop_thread_default (data->context);
2731 g_main_context_unref (data->context);
2732 g_main_loop_unref (data->loop);
2733 g_object_unref (data->res);
2739 /* ---------------------------------------------------------------------------------------------------- */
2743 GDBusMessageFilterFunction func;
2750 GDBusMessageFilterFunction filter_function;
2752 GDestroyNotify user_data_free_func;
2755 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2757 on_worker_message_received (GDBusWorker *worker,
2758 GDBusMessage *message,
2761 GDBusConnection *connection;
2762 FilterCallback *filters;
2767 G_LOCK (message_bus_lock);
2768 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2771 G_UNLOCK (message_bus_lock);
2774 connection = G_DBUS_CONNECTION (user_data);
2775 g_object_ref (connection);
2776 G_UNLOCK (message_bus_lock);
2778 //g_debug ("in on_worker_message_received");
2780 g_object_ref (message);
2781 g_dbus_message_lock (message);
2783 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2785 /* First collect the set of callback functions */
2786 CONNECTION_LOCK (connection);
2787 num_filters = connection->filters->len;
2788 filters = g_new0 (FilterCallback, num_filters);
2789 for (n = 0; n < num_filters; n++)
2791 FilterData *data = connection->filters->pdata[n];
2792 filters[n].func = data->filter_function;
2793 filters[n].user_data = data->user_data;
2795 CONNECTION_UNLOCK (connection);
2797 /* then call the filters in order (without holding the lock) */
2798 for (n = 0; n < num_filters; n++)
2800 message = filters[n].func (connection,
2803 filters[n].user_data);
2804 if (message == NULL)
2806 g_dbus_message_lock (message);
2809 /* Standard dispatch unless the filter ate the message - no need to
2810 * do anything if the message was altered
2812 if (message != NULL)
2814 GDBusMessageType message_type;
2816 message_type = g_dbus_message_get_message_type (message);
2817 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2819 guint32 reply_serial;
2820 SendMessageData *send_message_data;
2822 reply_serial = g_dbus_message_get_reply_serial (message);
2823 CONNECTION_LOCK (connection);
2824 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2825 GUINT_TO_POINTER (reply_serial));
2826 if (send_message_data != NULL)
2828 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2829 send_message_data_deliver_reply_unlocked (send_message_data, message);
2833 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2835 CONNECTION_UNLOCK (connection);
2837 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2839 CONNECTION_LOCK (connection);
2840 distribute_signals (connection, message);
2841 CONNECTION_UNLOCK (connection);
2843 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2845 CONNECTION_LOCK (connection);
2846 distribute_method_call (connection, message);
2847 CONNECTION_UNLOCK (connection);
2851 if (message != NULL)
2852 g_object_unref (message);
2853 g_object_unref (connection);
2857 /* Called in GDBusWorker's thread, lock is not held */
2858 static GDBusMessage *
2859 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2860 GDBusMessage *message,
2863 GDBusConnection *connection;
2864 FilterCallback *filters;
2869 G_LOCK (message_bus_lock);
2870 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2873 G_UNLOCK (message_bus_lock);
2876 connection = G_DBUS_CONNECTION (user_data);
2877 g_object_ref (connection);
2878 G_UNLOCK (message_bus_lock);
2880 //g_debug ("in on_worker_message_about_to_be_sent");
2882 /* First collect the set of callback functions */
2883 CONNECTION_LOCK (connection);
2884 num_filters = connection->filters->len;
2885 filters = g_new0 (FilterCallback, num_filters);
2886 for (n = 0; n < num_filters; n++)
2888 FilterData *data = connection->filters->pdata[n];
2889 filters[n].func = data->filter_function;
2890 filters[n].user_data = data->user_data;
2892 CONNECTION_UNLOCK (connection);
2894 /* then call the filters in order (without holding the lock) */
2895 for (n = 0; n < num_filters; n++)
2897 g_dbus_message_lock (message);
2898 message = filters[n].func (connection,
2901 filters[n].user_data);
2902 if (message == NULL)
2906 g_object_unref (connection);
2912 /* called with connection lock held, in GDBusWorker thread */
2914 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2916 SendMessageData *data = value;
2918 if (data->delivered)
2921 g_simple_async_result_set_error (data->simple,
2924 _("The connection is closed"));
2926 /* Ask send_message_with_reply_deliver not to remove the element from the
2927 * hash table - we're in the middle of a foreach; that would be unsafe.
2928 * Instead, return TRUE from this function so that it gets removed safely.
2930 send_message_with_reply_deliver (data, FALSE);
2934 /* Called in GDBusWorker's thread - we must not block - without lock held */
2936 on_worker_closed (GDBusWorker *worker,
2937 gboolean remote_peer_vanished,
2941 GDBusConnection *connection;
2943 guint old_atomic_flags;
2945 G_LOCK (message_bus_lock);
2946 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2949 G_UNLOCK (message_bus_lock);
2952 connection = G_DBUS_CONNECTION (user_data);
2953 g_object_ref (connection);
2954 G_UNLOCK (message_bus_lock);
2956 //g_debug ("in on_worker_closed: %s", error->message);
2958 CONNECTION_LOCK (connection);
2959 /* Even though this is atomic, we do it inside the lock to avoid breaking
2960 * assumptions in remove_match_rule(). We'd need the lock in a moment
2961 * anyway, so, no loss.
2963 old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
2965 if (!(old_atomic_flags & FLAG_CLOSED))
2967 g_hash_table_foreach_remove (connection->map_method_serial_to_send_message_data, cancel_method_on_close, NULL);
2968 schedule_closed_unlocked (connection, remote_peer_vanished, error);
2970 CONNECTION_UNLOCK (connection);
2972 g_object_unref (connection);
2975 /* ---------------------------------------------------------------------------------------------------- */
2977 /* Determines the biggest set of capabilities we can support on this
2980 * Called with the init_lock held.
2982 static GDBusCapabilityFlags
2983 get_offered_capabilities_max (GDBusConnection *connection)
2985 GDBusCapabilityFlags ret;
2986 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2988 if (G_IS_UNIX_CONNECTION (connection->stream))
2989 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2994 /* Called in a user thread, lock is not held */
2996 initable_init (GInitable *initable,
2997 GCancellable *cancellable,
3000 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
3003 /* This method needs to be idempotent to work with the singleton
3004 * pattern. See the docs for g_initable_init(). We implement this by
3007 * Unfortunately we can't use the main lock since the on_worker_*()
3008 * callbacks above needs the lock during initialization (for message
3009 * bus connections we do a synchronous Hello() call on the bus).
3011 g_mutex_lock (&connection->init_lock);
3015 /* Make this a no-op if we're already initialized (successfully or
3018 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
3020 ret = (connection->initialization_error == NULL);
3024 /* Because of init_lock, we can't get here twice in different threads */
3025 g_assert (connection->initialization_error == NULL);
3027 /* The user can pass multiple (but mutally exclusive) construct
3030 * - stream (of type GIOStream)
3031 * - address (of type gchar*)
3033 * At the end of the day we end up with a non-NULL GIOStream
3034 * object in connection->stream.
3036 if (connection->address != NULL)
3040 g_assert (connection->stream == NULL);
3042 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
3043 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
3045 g_set_error_literal (&connection->initialization_error,
3047 G_IO_ERROR_INVALID_ARGUMENT,
3048 _("Unsupported flags encountered when constructing a client-side connection"));
3052 ret = g_dbus_address_get_stream_internal (connection->address, TRUE,
3053 NULL, /* TODO: out_guid */
3054 cancellable, &connection->initialization_error);
3059 if (G_IS_IO_STREAM (ret))
3060 connection->stream = G_IO_STREAM (ret);
3061 else if (G_IS_KDBUS_WORKER (ret))
3062 connection->kdbus_worker = G_KDBUS_WORKER (ret);
3064 g_assert_not_reached ();
3066 else if (connection->stream != NULL)
3072 g_assert_not_reached ();
3075 /* [KDBUS] Skip authentication process for kdbus transport */
3076 if (connection->kdbus_worker)
3081 /* Authenticate the connection */
3082 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
3084 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
3085 g_assert (connection->guid != NULL);
3086 connection->auth = _g_dbus_auth_new (connection->stream);
3087 if (!_g_dbus_auth_run_server (connection->auth,
3088 connection->authentication_observer,
3090 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
3091 get_offered_capabilities_max (connection),
3092 &connection->capabilities,
3093 &connection->credentials,
3095 &connection->initialization_error))
3098 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
3100 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
3101 g_assert (connection->guid == NULL);
3102 connection->auth = _g_dbus_auth_new (connection->stream);
3103 connection->guid = _g_dbus_auth_run_client (connection->auth,
3104 connection->authentication_observer,
3105 get_offered_capabilities_max (connection),
3106 &connection->capabilities,
3108 &connection->initialization_error);
3109 if (connection->guid == NULL)
3113 if (connection->authentication_observer != NULL)
3115 g_object_unref (connection->authentication_observer);
3116 connection->authentication_observer = NULL;
3121 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
3123 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
3126 /* We want all IO operations to be non-blocking since they happen in
3127 * the worker thread which is shared by _all_ connections.
3129 if (G_IS_SOCKET_CONNECTION (connection->stream))
3131 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
3135 G_LOCK (message_bus_lock);
3136 if (alive_connections == NULL)
3137 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
3138 g_hash_table_insert (alive_connections, connection, connection);
3139 G_UNLOCK (message_bus_lock);
3141 if (!connection->kdbus_worker)
3142 connection->worker = _g_dbus_worker_new (connection->stream,
3143 connection->capabilities,
3144 ((connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) != 0),
3145 on_worker_message_received,
3146 on_worker_message_about_to_be_sent,
3150 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
3151 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3153 GVariant *hello_result;
3155 /* we could lift this restriction by adding code in gdbusprivate.c */
3156 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
3158 g_set_error_literal (&connection->initialization_error,
3161 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
3165 if (connection->kdbus_worker)
3167 hello_result = _g_kdbus_Hello (connection->kdbus_worker, &connection->initialization_error);
3171 hello_result = g_dbus_connection_call_sync (connection,
3172 "org.freedesktop.DBus", /* name */
3173 "/org/freedesktop/DBus", /* path */
3174 "org.freedesktop.DBus", /* interface */
3176 NULL, /* parameters */
3177 G_VARIANT_TYPE ("(s)"),
3178 CALL_FLAGS_INITIALIZING,
3180 NULL, /* TODO: cancellable */
3181 &connection->initialization_error);
3184 if (hello_result == NULL)
3187 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
3188 g_variant_unref (hello_result);
3189 //g_debug ("unique name is '%s'", connection->bus_unique_name);
3196 g_assert (connection->initialization_error != NULL);
3197 g_propagate_error (error, g_error_copy (connection->initialization_error));
3200 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
3201 g_mutex_unlock (&connection->init_lock);
3207 initable_iface_init (GInitableIface *initable_iface)
3209 initable_iface->init = initable_init;
3212 /* ---------------------------------------------------------------------------------------------------- */
3215 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
3220 /* ---------------------------------------------------------------------------------------------------- */
3223 * g_dbus_connection_new:
3224 * @stream: a #GIOStream
3225 * @guid: (allow-none): the GUID to use if a authenticating as a server or %NULL
3226 * @flags: flags describing how to make the connection
3227 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3228 * @cancellable: (allow-none): a #GCancellable or %NULL
3229 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
3230 * @user_data: the data to pass to @callback
3232 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
3233 * with the end represented by @stream.
3235 * If @stream is a #GSocketConnection, then the corresponding #GSocket
3236 * will be put into non-blocking mode.
3238 * The D-Bus connection will interact with @stream from a worker thread.
3239 * As a result, the caller should not interact with @stream after this
3240 * method has been called, except by calling g_object_unref() on it.
3242 * If @observer is not %NULL it may be used to control the
3243 * authentication process.
3245 * When the operation is finished, @callback will be invoked. You can
3246 * then call g_dbus_connection_new_finish() to get the result of the
3249 * This is a asynchronous failable constructor. See
3250 * g_dbus_connection_new_sync() for the synchronous
3256 g_dbus_connection_new (GIOStream *stream,
3258 GDBusConnectionFlags flags,
3259 GDBusAuthObserver *observer,
3260 GCancellable *cancellable,
3261 GAsyncReadyCallback callback,
3264 g_return_if_fail (G_IS_IO_STREAM (stream));
3265 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
3273 "authentication-observer", observer,
3278 * g_dbus_connection_new_finish:
3279 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback
3280 * passed to g_dbus_connection_new().
3281 * @error: return location for error or %NULL
3283 * Finishes an operation started with g_dbus_connection_new().
3285 * Returns: a #GDBusConnection or %NULL if @error is set. Free
3286 * with g_object_unref().
3291 g_dbus_connection_new_finish (GAsyncResult *res,
3295 GObject *source_object;
3297 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
3298 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3300 source_object = g_async_result_get_source_object (res);
3301 g_assert (source_object != NULL);
3302 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
3305 g_object_unref (source_object);
3307 return G_DBUS_CONNECTION (object);
3313 * g_dbus_connection_new_sync:
3314 * @stream: a #GIOStream
3315 * @guid: (allow-none): the GUID to use if a authenticating as a server or %NULL
3316 * @flags: flags describing how to make the connection
3317 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3318 * @cancellable: (allow-none): a #GCancellable or %NULL
3319 * @error: return location for error or %NULL
3321 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
3322 * with the end represented by @stream.
3324 * If @stream is a #GSocketConnection, then the corresponding #GSocket
3325 * will be put into non-blocking mode.
3327 * The D-Bus connection will interact with @stream from a worker thread.
3328 * As a result, the caller should not interact with @stream after this
3329 * method has been called, except by calling g_object_unref() on it.
3331 * If @observer is not %NULL it may be used to control the
3332 * authentication process.
3334 * This is a synchronous failable constructor. See
3335 * g_dbus_connection_new() for the asynchronous version.
3337 * Returns: a #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
3342 g_dbus_connection_new_sync (GIOStream *stream,
3344 GDBusConnectionFlags flags,
3345 GDBusAuthObserver *observer,
3346 GCancellable *cancellable,
3349 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
3350 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3351 return g_initable_new (G_TYPE_DBUS_CONNECTION,
3357 "authentication-observer", observer,
3361 /* ---------------------------------------------------------------------------------------------------- */
3364 * g_dbus_connection_new_for_address:
3365 * @address: a D-Bus address
3366 * @flags: flags describing how to make the connection
3367 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3368 * @cancellable: (allow-none): a #GCancellable or %NULL
3369 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
3370 * @user_data: the data to pass to @callback
3372 * Asynchronously connects and sets up a D-Bus client connection for
3373 * exchanging D-Bus messages with an endpoint specified by @address
3374 * which must be in the D-Bus address format.
3376 * This constructor can only be used to initiate client-side
3377 * connections - use g_dbus_connection_new() if you need to act as the
3378 * server. In particular, @flags cannot contain the
3379 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
3380 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
3382 * When the operation is finished, @callback will be invoked. You can
3383 * then call g_dbus_connection_new_finish() to get the result of the
3386 * If @observer is not %NULL it may be used to control the
3387 * authentication process.
3389 * This is a asynchronous failable constructor. See
3390 * g_dbus_connection_new_for_address_sync() for the synchronous
3396 g_dbus_connection_new_for_address (const gchar *address,
3397 GDBusConnectionFlags flags,
3398 GDBusAuthObserver *observer,
3399 GCancellable *cancellable,
3400 GAsyncReadyCallback callback,
3403 g_return_if_fail (address != NULL);
3404 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
3411 "authentication-observer", observer,
3416 * g_dbus_connection_new_for_address_finish:
3417 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
3418 * to g_dbus_connection_new()
3419 * @error: return location for error or %NULL
3421 * Finishes an operation started with g_dbus_connection_new_for_address().
3423 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
3429 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
3433 GObject *source_object;
3435 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
3436 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3438 source_object = g_async_result_get_source_object (res);
3439 g_assert (source_object != NULL);
3440 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
3443 g_object_unref (source_object);
3445 return G_DBUS_CONNECTION (object);
3451 * g_dbus_connection_new_for_address_sync:
3452 * @address: a D-Bus address
3453 * @flags: flags describing how to make the connection
3454 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3455 * @cancellable: (allow-none): a #GCancellable or %NULL
3456 * @error: return location for error or %NULL
3458 * Synchronously connects and sets up a D-Bus client connection for
3459 * exchanging D-Bus messages with an endpoint specified by @address
3460 * which must be in the D-Bus address format.
3462 * This constructor can only be used to initiate client-side
3463 * connections - use g_dbus_connection_new_sync() if you need to act
3464 * as the server. In particular, @flags cannot contain the
3465 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
3466 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
3468 * This is a synchronous failable constructor. See
3469 * g_dbus_connection_new_for_address() for the asynchronous version.
3471 * If @observer is not %NULL it may be used to control the
3472 * authentication process.
3474 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
3480 g_dbus_connection_new_for_address_sync (const gchar *address,
3481 GDBusConnectionFlags flags,
3482 GDBusAuthObserver *observer,
3483 GCancellable *cancellable,
3486 g_return_val_if_fail (address != NULL, NULL);
3487 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3488 return g_initable_new (G_TYPE_DBUS_CONNECTION,
3493 "authentication-observer", observer,
3497 /* ---------------------------------------------------------------------------------------------------- */
3500 * g_dbus_connection_set_exit_on_close:
3501 * @connection: a #GDBusConnection
3502 * @exit_on_close: whether the process should be terminated
3503 * when @connection is closed by the remote peer
3505 * Sets whether the process should be terminated when @connection is
3506 * closed by the remote peer. See #GDBusConnection:exit-on-close for
3509 * Note that this function should be used with care. Most modern UNIX
3510 * desktops tie the notion of a user session the session bus, and expect
3511 * all of a users applications to quit when their bus connection goes away.
3512 * If you are setting @exit_on_close to %FALSE for the shared session
3513 * bus connection, you should make sure that your application exits
3514 * when the user session ends.
3519 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
3520 gboolean exit_on_close)
3522 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3525 g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
3527 g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
3532 * g_dbus_connection_get_exit_on_close:
3533 * @connection: a #GDBusConnection
3535 * Gets whether the process is terminated when @connection is
3536 * closed by the remote peer. See
3537 * #GDBusConnection:exit-on-close for more details.
3539 * Returns: whether the process is terminated when @connection is
3540 * closed by the remote peer
3545 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
3547 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3549 if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
3556 * g_dbus_connection_get_guid:
3557 * @connection: a #GDBusConnection
3559 * The GUID of the peer performing the role of server when
3560 * authenticating. See #GDBusConnection:guid for more details.
3562 * Returns: The GUID. Do not free this string, it is owned by
3568 g_dbus_connection_get_guid (GDBusConnection *connection)
3570 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3571 return connection->guid;
3575 * g_dbus_connection_get_unique_name:
3576 * @connection: a #GDBusConnection
3578 * Gets the unique name of @connection as assigned by the message
3579 * bus. This can also be used to figure out if @connection is a
3580 * message bus connection.
3582 * Returns: the unique name or %NULL if @connection is not a message
3583 * bus connection. Do not free this string, it is owned by
3589 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3591 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3593 /* do not use g_return_val_if_fail(), we want the memory barrier */
3594 if (!check_initialized (connection))
3597 return connection->bus_unique_name;
3601 * g_dbus_connection_get_peer_credentials:
3602 * @connection: a #GDBusConnection
3604 * Gets the credentials of the authenticated peer. This will always
3605 * return %NULL unless @connection acted as a server
3606 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3607 * when set up and the client passed credentials as part of the
3608 * authentication process.
3610 * In a message bus setup, the message bus is always the server and
3611 * each application is a client. So this method will always return
3612 * %NULL for message bus clients.
3614 * Returns: (transfer none): a #GCredentials or %NULL if not available.
3615 * Do not free this object, it is owned by @connection.
3620 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3622 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3624 /* do not use g_return_val_if_fail(), we want the memory barrier */
3625 if (!check_initialized (connection))
3628 return connection->credentials;
3631 /* ---------------------------------------------------------------------------------------------------- */
3633 static guint _global_filter_id = 1;
3636 * g_dbus_connection_add_filter:
3637 * @connection: a #GDBusConnection
3638 * @filter_function: a filter function
3639 * @user_data: user data to pass to @filter_function
3640 * @user_data_free_func: function to free @user_data with when filter
3641 * is removed or %NULL
3643 * Adds a message filter. Filters are handlers that are run on all
3644 * incoming and outgoing messages, prior to standard dispatch. Filters
3645 * are run in the order that they were added. The same handler can be
3646 * added as a filter more than once, in which case it will be run more
3647 * than once. Filters added during a filter callback won't be run on
3648 * the message being processed. Filter functions are allowed to modify
3649 * and even drop messages.
3651 * Note that filters are run in a dedicated message handling thread so
3652 * they can't block and, generally, can't do anything but signal a
3653 * worker thread. Also note that filters are rarely needed - use API
3654 * such as g_dbus_connection_send_message_with_reply(),
3655 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3657 * If a filter consumes an incoming message the message is not
3658 * dispatched anywhere else - not even the standard dispatch machinery
3659 * (that API such as g_dbus_connection_signal_subscribe() and
3660 * g_dbus_connection_send_message_with_reply() relies on) will see the
3661 * message. Similary, if a filter consumes an outgoing message, the
3662 * message will not be sent to the other peer.
3664 * Returns: a filter identifier that can be used with
3665 * g_dbus_connection_remove_filter()
3670 g_dbus_connection_add_filter (GDBusConnection *connection,
3671 GDBusMessageFilterFunction filter_function,
3673 GDestroyNotify user_data_free_func)
3677 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3678 g_return_val_if_fail (filter_function != NULL, 0);
3679 g_return_val_if_fail (check_initialized (connection), 0);
3681 CONNECTION_LOCK (connection);
3682 data = g_new0 (FilterData, 1);
3683 data->id = _global_filter_id++; /* TODO: overflow etc. */
3684 data->filter_function = filter_function;
3685 data->user_data = user_data;
3686 data->user_data_free_func = user_data_free_func;
3687 g_ptr_array_add (connection->filters, data);
3688 CONNECTION_UNLOCK (connection);
3693 /* only called from finalize(), removes all filters */
3695 purge_all_filters (GDBusConnection *connection)
3698 for (n = 0; n < connection->filters->len; n++)
3700 FilterData *data = connection->filters->pdata[n];
3701 if (data->user_data_free_func != NULL)
3702 data->user_data_free_func (data->user_data);
3708 * g_dbus_connection_remove_filter:
3709 * @connection: a #GDBusConnection
3710 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3717 g_dbus_connection_remove_filter (GDBusConnection *connection,
3721 FilterData *to_destroy;
3723 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3724 g_return_if_fail (check_initialized (connection));
3726 CONNECTION_LOCK (connection);
3728 for (n = 0; n < connection->filters->len; n++)
3730 FilterData *data = connection->filters->pdata[n];
3731 if (data->id == filter_id)
3733 g_ptr_array_remove_index (connection->filters, n);
3738 CONNECTION_UNLOCK (connection);
3740 /* do free without holding lock */
3741 if (to_destroy != NULL)
3743 if (to_destroy->user_data_free_func != NULL)
3744 to_destroy->user_data_free_func (to_destroy->user_data);
3745 g_free (to_destroy);
3749 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3753 /* ---------------------------------------------------------------------------------------------------- */
3759 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3760 gchar *interface_name;
3764 GDBusSignalFlags flags;
3765 GArray *subscribers;
3770 GDBusSignalCallback callback;
3772 GDestroyNotify user_data_free_func;
3774 GMainContext *context;
3778 signal_data_free (SignalData *signal_data)
3780 g_free (signal_data->rule);
3781 g_free (signal_data->sender);
3782 g_free (signal_data->sender_unique_name);
3783 g_free (signal_data->interface_name);
3784 g_free (signal_data->member);
3785 g_free (signal_data->object_path);
3786 g_free (signal_data->arg0);
3787 g_array_free (signal_data->subscribers, TRUE);
3788 g_free (signal_data);
3792 args_to_rule (const gchar *sender,
3793 const gchar *interface_name,
3794 const gchar *member,
3795 const gchar *object_path,
3797 GDBusSignalFlags flags)
3801 rule = g_string_new ("type='signal'");
3802 if (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE)
3803 g_string_prepend_c (rule, '-');
3805 g_string_append_printf (rule, ",sender='%s'", sender);
3806 if (interface_name != NULL)
3807 g_string_append_printf (rule, ",interface='%s'", interface_name);
3809 g_string_append_printf (rule, ",member='%s'", member);
3810 if (object_path != NULL)
3811 g_string_append_printf (rule, ",path='%s'", object_path);
3815 if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3816 g_string_append_printf (rule, ",arg0path='%s'", arg0);
3817 else if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3818 g_string_append_printf (rule, ",arg0namespace='%s'", arg0);
3820 g_string_append_printf (rule, ",arg0='%s'", arg0);
3823 return g_string_free (rule, FALSE);
3826 static guint _global_subscriber_id = 1;
3827 static guint _global_registration_id = 1;
3828 static guint _global_subtree_registration_id = 1;
3830 /* ---------------------------------------------------------------------------------------------------- */
3832 /* Called in a user thread, lock is held */
3834 add_match_rule (GDBusConnection *connection,
3835 const gchar *match_rule)
3838 GDBusMessage *message;
3840 if (match_rule[0] == '-')
3843 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3844 "/org/freedesktop/DBus", /* path */
3845 "org.freedesktop.DBus", /* interface */
3847 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3849 if (!g_dbus_connection_send_message_unlocked (connection,
3851 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3855 g_critical ("Error while sending AddMatch() message: %s", error->message);
3856 g_error_free (error);
3858 g_object_unref (message);
3861 /* ---------------------------------------------------------------------------------------------------- */
3863 /* Called in a user thread, lock is held */
3865 remove_match_rule (GDBusConnection *connection,
3866 const gchar *match_rule)
3869 GDBusMessage *message;
3871 if (match_rule[0] == '-')
3874 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3875 "/org/freedesktop/DBus", /* path */
3876 "org.freedesktop.DBus", /* interface */
3878 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3881 if (!g_dbus_connection_send_message_unlocked (connection,
3883 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3887 /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
3888 * critical; but we're holding the lock, and our caller checked whether
3889 * we were already closed, so we can't get that error.
3891 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3892 g_error_free (error);
3894 g_object_unref (message);
3897 /* ---------------------------------------------------------------------------------------------------- */
3900 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3902 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3903 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3904 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3905 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3906 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3909 /* ---------------------------------------------------------------------------------------------------- */
3912 * g_dbus_connection_signal_subscribe:
3913 * @connection: a #GDBusConnection
3914 * @sender: (allow-none): sender name to match on (unique or well-known name)
3915 * or %NULL to listen from all senders
3916 * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3917 * match on all interfaces
3918 * @member: (allow-none): D-Bus signal name to match on or %NULL to match on
3920 * @object_path: (allow-none): object path to match on or %NULL to match on
3922 * @arg0: (allow-none): contents of first string argument to match on or %NULL
3923 * to match on all kinds of arguments
3924 * @flags: flags describing how to subscribe to the signal (currently unused)
3925 * @callback: callback to invoke when there is a signal matching the requested data
3926 * @user_data: user data to pass to @callback
3927 * @user_data_free_func: (allow-none): function to free @user_data with when
3928 * subscription is removed or %NULL
3930 * Subscribes to signals on @connection and invokes @callback with a whenever
3931 * the signal is received. Note that @callback will be invoked in the
3932 * [thread-default main context][g-main-context-push-thread-default]
3933 * of the thread you are calling this method from.
3935 * If @connection is not a message bus connection, @sender must be
3938 * If @sender is a well-known name note that @callback is invoked with
3939 * the unique name for the owner of @sender, not the well-known name
3940 * as one would expect. This is because the message bus rewrites the
3941 * name. As such, to avoid certain race conditions, users should be
3942 * tracking the name owner of the well-known name and use that when
3943 * processing the received signal.
3945 * If one of %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE or
3946 * %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH are given, @arg0 is
3947 * interpreted as part of a namespace or path. The first argument
3948 * of a signal is matched against that part as specified by D-Bus.
3950 * Returns: a subscription identifier that can be used with g_dbus_connection_signal_unsubscribe()
3955 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3956 const gchar *sender,
3957 const gchar *interface_name,
3958 const gchar *member,
3959 const gchar *object_path,
3961 GDBusSignalFlags flags,
3962 GDBusSignalCallback callback,
3964 GDestroyNotify user_data_free_func)
3967 SignalData *signal_data;
3968 SignalSubscriber subscriber;
3969 GPtrArray *signal_data_array;
3970 const gchar *sender_unique_name;
3972 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3973 * an OOM condition. We might want to change that but that would involve making
3974 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3975 * handle that. And there's really no sensible way of handling this short of retrying
3976 * to add the match rule... and then there's the little thing that, hey, maybe there's
3977 * a reason the bus in an OOM condition.
3979 * Doable, but not really sure it's worth it...
3982 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3983 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3984 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3985 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3986 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3987 g_return_val_if_fail (callback != NULL, 0);
3988 g_return_val_if_fail (check_initialized (connection), 0);
3989 g_return_val_if_fail (!((flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH) && (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)), 0);
3990 g_return_val_if_fail (!(arg0 == NULL && (flags & (G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH | G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE))), 0);
3992 CONNECTION_LOCK (connection);
3994 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3995 * with a '-' character to prefix the rule (which will otherwise be
3998 * This allows us to hash the rule and do our lifecycle tracking in
3999 * the usual way, but the '-' prevents the match rule from ever
4000 * actually being send to the bus (either for add or remove).
4002 rule = args_to_rule (sender, interface_name, member, object_path, arg0, flags);
4004 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
4005 sender_unique_name = sender;
4007 sender_unique_name = "";
4009 subscriber.callback = callback;
4010 subscriber.user_data = user_data;
4011 subscriber.user_data_free_func = user_data_free_func;
4012 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
4013 subscriber.context = g_main_context_ref_thread_default ();
4015 /* see if we've already have this rule */
4016 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
4017 if (signal_data != NULL)
4019 g_array_append_val (signal_data->subscribers, subscriber);
4024 signal_data = g_new0 (SignalData, 1);
4025 signal_data->rule = rule;
4026 signal_data->sender = g_strdup (sender);
4027 signal_data->sender_unique_name = g_strdup (sender_unique_name);
4028 signal_data->interface_name = g_strdup (interface_name);
4029 signal_data->member = g_strdup (member);
4030 signal_data->object_path = g_strdup (object_path);
4031 signal_data->arg0 = g_strdup (arg0);
4032 signal_data->flags = flags;
4033 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
4034 g_array_append_val (signal_data->subscribers, subscriber);
4036 g_hash_table_insert (connection->map_rule_to_signal_data,
4040 /* Add the match rule to the bus...
4042 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
4043 * always send such messages to us.
4045 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
4047 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
4048 add_match_rule (connection, signal_data->rule);
4051 if (connection->kdbus_worker)
4053 if (g_strcmp0 (signal_data->member, "NameAcquired") == 0)
4054 _g_kdbus_subscribe_name_acquired (connection->kdbus_worker, arg0);
4055 else if (g_strcmp0 (signal_data->member, "NameLost") == 0)
4056 _g_kdbus_subscribe_name_lost (connection->kdbus_worker, arg0);
4061 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
4062 signal_data->sender_unique_name);
4063 if (signal_data_array == NULL)
4065 signal_data_array = g_ptr_array_new ();
4066 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
4067 g_strdup (signal_data->sender_unique_name),
4070 g_ptr_array_add (signal_data_array, signal_data);
4073 g_hash_table_insert (connection->map_id_to_signal_data,
4074 GUINT_TO_POINTER (subscriber.id),
4077 CONNECTION_UNLOCK (connection);
4079 return subscriber.id;
4082 /* ---------------------------------------------------------------------------------------------------- */
4084 /* called in any thread */
4085 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
4087 unsubscribe_id_internal (GDBusConnection *connection,
4088 guint subscription_id,
4089 GArray *out_removed_subscribers)
4091 SignalData *signal_data;
4092 GPtrArray *signal_data_array;
4095 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
4096 GUINT_TO_POINTER (subscription_id));
4097 if (signal_data == NULL)
4099 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
4103 for (n = 0; n < signal_data->subscribers->len; n++)
4105 SignalSubscriber *subscriber;
4107 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
4108 if (subscriber->id != subscription_id)
4111 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
4112 GUINT_TO_POINTER (subscription_id)));
4113 g_array_append_val (out_removed_subscribers, *subscriber);
4114 g_array_remove_index (signal_data->subscribers, n);
4116 if (signal_data->subscribers->len == 0)
4118 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
4120 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
4121 signal_data->sender_unique_name);
4122 g_warn_if_fail (signal_data_array != NULL);
4123 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
4125 if (signal_data_array->len == 0)
4127 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
4128 signal_data->sender_unique_name));
4131 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
4132 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
4133 !is_signal_data_for_name_lost_or_acquired (signal_data) &&
4134 !g_dbus_connection_is_closed (connection) &&
4135 !connection->finalizing)
4137 /* The check for g_dbus_connection_is_closed() means that
4138 * sending the RemoveMatch message can't fail with
4139 * G_IO_ERROR_CLOSED, because we're holding the lock,
4140 * so on_worker_closed() can't happen between the check we just
4141 * did, and releasing the lock later.
4143 remove_match_rule (connection, signal_data->rule);
4147 if (connection->kdbus_worker)
4149 if (g_strcmp0 (signal_data->member, "NameAcquired") == 0)
4150 _g_kdbus_unsubscribe_name_acquired (connection->kdbus_worker);
4151 else if (g_strcmp0 (signal_data->member, "NameLost") == 0)
4152 _g_kdbus_unsubscribe_name_lost (connection->kdbus_worker);
4156 signal_data_free (signal_data);
4162 g_assert_not_reached ();
4169 * g_dbus_connection_signal_unsubscribe:
4170 * @connection: a #GDBusConnection
4171 * @subscription_id: a subscription id obtained from
4172 * g_dbus_connection_signal_subscribe()
4174 * Unsubscribes from signals.
4179 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
4180 guint subscription_id)
4182 GArray *subscribers;
4185 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4186 g_return_if_fail (check_initialized (connection));
4188 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
4190 CONNECTION_LOCK (connection);
4191 unsubscribe_id_internal (connection,
4194 CONNECTION_UNLOCK (connection);
4197 g_assert (subscribers->len == 0 || subscribers->len == 1);
4199 /* call GDestroyNotify without lock held */
4200 for (n = 0; n < subscribers->len; n++)
4202 SignalSubscriber *subscriber;
4203 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
4204 call_destroy_notify (subscriber->context,
4205 subscriber->user_data_free_func,
4206 subscriber->user_data);
4207 g_main_context_unref (subscriber->context);
4210 g_array_free (subscribers, TRUE);
4213 /* ---------------------------------------------------------------------------------------------------- */
4217 guint subscription_id;
4218 GDBusSignalCallback callback;
4220 GDBusMessage *message;
4221 GDBusConnection *connection;
4222 const gchar *sender;
4224 const gchar *interface;
4225 const gchar *member;
4228 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
4232 emit_signal_instance_in_idle_cb (gpointer data)
4234 SignalInstance *signal_instance = data;
4235 GVariant *parameters;
4236 gboolean has_subscription;
4238 parameters = g_dbus_message_get_body (signal_instance->message);
4239 if (parameters == NULL)
4241 parameters = g_variant_new ("()");
4242 g_variant_ref_sink (parameters);
4246 g_variant_ref (parameters);
4250 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
4251 signal_instance->subscription_id,
4252 signal_instance->sender,
4253 signal_instance->path,
4254 signal_instance->interface,
4255 signal_instance->member,
4256 g_variant_print (parameters, TRUE));
4259 /* Careful here, don't do the callback if we no longer has the subscription */
4260 CONNECTION_LOCK (signal_instance->connection);
4261 has_subscription = FALSE;
4262 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
4263 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
4264 has_subscription = TRUE;
4265 CONNECTION_UNLOCK (signal_instance->connection);
4267 if (has_subscription)
4268 signal_instance->callback (signal_instance->connection,
4269 signal_instance->sender,
4270 signal_instance->path,
4271 signal_instance->interface,
4272 signal_instance->member,
4274 signal_instance->user_data);
4276 g_variant_unref (parameters);
4282 signal_instance_free (SignalInstance *signal_instance)
4284 g_object_unref (signal_instance->message);
4285 g_object_unref (signal_instance->connection);
4286 g_free (signal_instance);
4290 namespace_rule_matches (const gchar *namespace,
4296 len_namespace = strlen (namespace);
4297 len_name = strlen (name);
4299 if (len_name < len_namespace)
4302 if (memcmp (namespace, name, len_namespace) != 0)
4305 return len_namespace == len_name || name[len_namespace] == '.';
4309 path_rule_matches (const gchar *path_a,
4310 const gchar *path_b)
4314 len_a = strlen (path_a);
4315 len_b = strlen (path_b);
4317 if (len_a < len_b && path_a[len_a - 1] != '/')
4320 if (len_b < len_a && path_b[len_b - 1] != '/')
4323 return memcmp (path_a, path_b, MIN (len_a, len_b)) == 0;
4326 /* called in GDBusWorker thread WITH lock held */
4328 schedule_callbacks (GDBusConnection *connection,
4329 GPtrArray *signal_data_array,
4330 GDBusMessage *message,
4331 const gchar *sender)
4334 const gchar *interface;
4335 const gchar *member;
4344 interface = g_dbus_message_get_interface (message);
4345 member = g_dbus_message_get_member (message);
4346 path = g_dbus_message_get_path (message);
4347 arg0 = g_dbus_message_get_arg0 (message);
4350 g_print ("In schedule_callbacks:\n"
4352 " interface = '%s'\n"
4363 /* TODO: if this is slow, then we can change signal_data_array into
4364 * map_object_path_to_signal_data_array or something.
4366 for (n = 0; n < signal_data_array->len; n++)
4368 SignalData *signal_data = signal_data_array->pdata[n];
4370 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
4373 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
4376 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
4379 if (signal_data->arg0 != NULL)
4384 if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
4386 if (!namespace_rule_matches (signal_data->arg0, arg0))
4389 else if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
4391 if (!path_rule_matches (signal_data->arg0, arg0))
4394 else if (!g_str_equal (signal_data->arg0, arg0))
4398 for (m = 0; m < signal_data->subscribers->len; m++)
4400 SignalSubscriber *subscriber;
4401 GSource *idle_source;
4402 SignalInstance *signal_instance;
4404 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
4406 signal_instance = g_new0 (SignalInstance, 1);
4407 signal_instance->subscription_id = subscriber->id;
4408 signal_instance->callback = subscriber->callback;
4409 signal_instance->user_data = subscriber->user_data;
4410 signal_instance->message = g_object_ref (message);
4411 signal_instance->connection = g_object_ref (connection);
4412 signal_instance->sender = sender;
4413 signal_instance->path = path;
4414 signal_instance->interface = interface;
4415 signal_instance->member = member;
4417 idle_source = g_idle_source_new ();
4418 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4419 g_source_set_callback (idle_source,
4420 emit_signal_instance_in_idle_cb,
4422 (GDestroyNotify) signal_instance_free);
4423 g_source_set_name (idle_source, "[gio] emit_signal_instance_in_idle_cb");
4424 g_source_attach (idle_source, subscriber->context);
4425 g_source_unref (idle_source);
4430 /* called in GDBusWorker thread with lock held */
4432 distribute_signals (GDBusConnection *connection,
4433 GDBusMessage *message)
4435 GPtrArray *signal_data_array;
4436 const gchar *sender;
4438 sender = g_dbus_message_get_sender (message);
4440 if (G_UNLIKELY (_g_dbus_debug_signal ()))
4442 _g_dbus_debug_print_lock ();
4443 g_print ("========================================================================\n"
4444 "GDBus-debug:Signal:\n"
4445 " <<<< RECEIVED SIGNAL %s.%s\n"
4447 " sent by name %s\n",
4448 g_dbus_message_get_interface (message),
4449 g_dbus_message_get_member (message),
4450 g_dbus_message_get_path (message),
4451 sender != NULL ? sender : "(none)");
4452 _g_dbus_debug_print_unlock ();
4455 /* collect subscribers that match on sender */
4458 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
4459 if (signal_data_array != NULL)
4460 schedule_callbacks (connection, signal_data_array, message, sender);
4463 /* collect subscribers not matching on sender */
4464 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
4465 if (signal_data_array != NULL)
4466 schedule_callbacks (connection, signal_data_array, message, sender);
4469 /* ---------------------------------------------------------------------------------------------------- */
4471 /* only called from finalize(), removes all subscriptions */
4473 purge_all_signal_subscriptions (GDBusConnection *connection)
4475 GHashTableIter iter;
4478 GArray *subscribers;
4481 ids = g_array_new (FALSE, FALSE, sizeof (guint));
4482 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
4483 while (g_hash_table_iter_next (&iter, &key, NULL))
4485 guint subscription_id = GPOINTER_TO_UINT (key);
4486 g_array_append_val (ids, subscription_id);
4489 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
4490 for (n = 0; n < ids->len; n++)
4492 guint subscription_id = g_array_index (ids, guint, n);
4493 unsubscribe_id_internal (connection,
4497 g_array_free (ids, TRUE);
4499 /* call GDestroyNotify without lock held */
4500 for (n = 0; n < subscribers->len; n++)
4502 SignalSubscriber *subscriber;
4503 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
4504 call_destroy_notify (subscriber->context,
4505 subscriber->user_data_free_func,
4506 subscriber->user_data);
4507 g_main_context_unref (subscriber->context);
4510 g_array_free (subscribers, TRUE);
4513 /* ---------------------------------------------------------------------------------------------------- */
4515 static GDBusInterfaceVTable *
4516 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
4518 /* Don't waste memory by copying padding - remember to update this
4519 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
4521 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4525 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
4530 /* ---------------------------------------------------------------------------------------------------- */
4532 static GDBusSubtreeVTable *
4533 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
4535 /* Don't waste memory by copying padding - remember to update this
4536 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
4538 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4542 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
4547 /* ---------------------------------------------------------------------------------------------------- */
4549 struct ExportedObject
4552 GDBusConnection *connection;
4554 /* maps gchar* -> ExportedInterface* */
4555 GHashTable *map_if_name_to_ei;
4558 /* only called with lock held */
4560 exported_object_free (ExportedObject *eo)
4562 g_free (eo->object_path);
4563 g_hash_table_unref (eo->map_if_name_to_ei);
4572 gchar *interface_name;
4573 GDBusInterfaceVTable *vtable;
4574 GDBusInterfaceInfo *interface_info;
4576 GMainContext *context;
4578 GDestroyNotify user_data_free_func;
4579 } ExportedInterface;
4581 /* called with lock held */
4583 exported_interface_free (ExportedInterface *ei)
4585 g_dbus_interface_info_cache_release (ei->interface_info);
4586 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
4588 call_destroy_notify (ei->context,
4589 ei->user_data_free_func,
4592 g_main_context_unref (ei->context);
4594 g_free (ei->interface_name);
4595 _g_dbus_interface_vtable_free (ei->vtable);
4599 /* ---------------------------------------------------------------------------------------------------- */
4601 /* Convenience function to check if @registration_id (if not zero) or
4602 * @subtree_registration_id (if not zero) has been unregistered. If
4603 * so, returns %TRUE.
4605 * May be called by any thread. Caller must *not* hold lock.
4608 has_object_been_unregistered (GDBusConnection *connection,
4609 guint registration_id,
4610 guint subtree_registration_id)
4614 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4618 CONNECTION_LOCK (connection);
4619 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
4620 GUINT_TO_POINTER (registration_id)) == NULL)
4624 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
4625 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
4629 CONNECTION_UNLOCK (connection);
4634 /* ---------------------------------------------------------------------------------------------------- */
4638 GDBusConnection *connection;
4639 GDBusMessage *message;
4641 const gchar *property_name;
4642 const GDBusInterfaceVTable *vtable;
4643 GDBusInterfaceInfo *interface_info;
4644 const GDBusPropertyInfo *property_info;
4645 guint registration_id;
4646 guint subtree_registration_id;
4650 property_data_free (PropertyData *data)
4652 g_object_unref (data->connection);
4653 g_object_unref (data->message);
4657 /* called in thread where object was registered - no locks held */
4659 invoke_get_property_in_idle_cb (gpointer _data)
4661 PropertyData *data = _data;
4664 GDBusMessage *reply;
4666 if (has_object_been_unregistered (data->connection,
4667 data->registration_id,
4668 data->subtree_registration_id))
4670 reply = g_dbus_message_new_method_error (data->message,
4671 "org.freedesktop.DBus.Error.UnknownMethod",
4672 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4673 g_dbus_message_get_path (data->message));
4674 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4675 g_object_unref (reply);
4680 value = data->vtable->get_property (data->connection,
4681 g_dbus_message_get_sender (data->message),
4682 g_dbus_message_get_path (data->message),
4683 data->interface_info->name,
4684 data->property_name,
4691 g_assert_no_error (error);
4693 g_variant_take_ref (value);
4694 reply = g_dbus_message_new_method_reply (data->message);
4695 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4696 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4697 g_variant_unref (value);
4698 g_object_unref (reply);
4702 gchar *dbus_error_name;
4703 g_assert (error != NULL);
4704 dbus_error_name = g_dbus_error_encode_gerror (error);
4705 reply = g_dbus_message_new_method_error_literal (data->message,
4708 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4709 g_free (dbus_error_name);
4710 g_error_free (error);
4711 g_object_unref (reply);
4718 /* called in thread where object was registered - no locks held */
4720 invoke_set_property_in_idle_cb (gpointer _data)
4722 PropertyData *data = _data;
4724 GDBusMessage *reply;
4730 g_variant_get (g_dbus_message_get_body (data->message),
4736 if (!data->vtable->set_property (data->connection,
4737 g_dbus_message_get_sender (data->message),
4738 g_dbus_message_get_path (data->message),
4739 data->interface_info->name,
4740 data->property_name,
4745 gchar *dbus_error_name;
4746 g_assert (error != NULL);
4747 dbus_error_name = g_dbus_error_encode_gerror (error);
4748 reply = g_dbus_message_new_method_error_literal (data->message,
4751 g_free (dbus_error_name);
4752 g_error_free (error);
4756 reply = g_dbus_message_new_method_reply (data->message);
4759 g_assert (reply != NULL);
4760 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4761 g_object_unref (reply);
4762 g_variant_unref (value);
4767 /* called in any thread with connection's lock held */
4769 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4770 GDBusMessage *message,
4771 guint registration_id,
4772 guint subtree_registration_id,
4774 GDBusInterfaceInfo *interface_info,
4775 const GDBusInterfaceVTable *vtable,
4776 GMainContext *main_context,
4780 const char *interface_name;
4781 const char *property_name;
4782 const GDBusPropertyInfo *property_info;
4783 GSource *idle_source;
4784 PropertyData *property_data;
4785 GDBusMessage *reply;
4790 g_variant_get (g_dbus_message_get_body (message),
4795 g_variant_get (g_dbus_message_get_body (message),
4804 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4806 property_info = NULL;
4808 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4809 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4810 if (property_info == NULL)
4812 reply = g_dbus_message_new_method_error (message,
4813 "org.freedesktop.DBus.Error.InvalidArgs",
4814 _("No such property '%s'"),
4816 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4817 g_object_unref (reply);
4822 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4824 reply = g_dbus_message_new_method_error (message,
4825 "org.freedesktop.DBus.Error.InvalidArgs",
4826 _("Property '%s' is not readable"),
4828 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4829 g_object_unref (reply);
4833 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4835 reply = g_dbus_message_new_method_error (message,
4836 "org.freedesktop.DBus.Error.InvalidArgs",
4837 _("Property '%s' is not writable"),
4839 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4840 g_object_unref (reply);
4849 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4850 * of the given value is wrong
4852 g_variant_get_child (g_dbus_message_get_body (message), 2, "v", &value);
4853 if (g_strcmp0 (g_variant_get_type_string (value), property_info->signature) != 0)
4855 reply = g_dbus_message_new_method_error (message,
4856 "org.freedesktop.DBus.Error.InvalidArgs",
4857 _("Error setting property '%s': Expected type '%s' but got '%s'"),
4858 property_name, property_info->signature,
4859 g_variant_get_type_string (value));
4860 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4861 g_variant_unref (value);
4862 g_object_unref (reply);
4867 g_variant_unref (value);
4870 /* If the vtable pointer for get_property() resp. set_property() is
4871 * NULL then dispatch the call via the method_call() handler.
4875 if (vtable->get_property == NULL)
4877 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4878 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4879 vtable, main_context, user_data);
4886 if (vtable->set_property == NULL)
4888 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4889 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4890 vtable, main_context, user_data);
4896 /* ok, got the property info - call user code in an idle handler */
4897 property_data = g_new0 (PropertyData, 1);
4898 property_data->connection = g_object_ref (connection);
4899 property_data->message = g_object_ref (message);
4900 property_data->user_data = user_data;
4901 property_data->property_name = property_name;
4902 property_data->vtable = vtable;
4903 property_data->interface_info = interface_info;
4904 property_data->property_info = property_info;
4905 property_data->registration_id = registration_id;
4906 property_data->subtree_registration_id = subtree_registration_id;
4908 idle_source = g_idle_source_new ();
4909 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4910 g_source_set_callback (idle_source,
4911 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4913 (GDestroyNotify) property_data_free);
4915 g_source_set_name (idle_source, "[gio] invoke_get_property_in_idle_cb");
4917 g_source_set_name (idle_source, "[gio] invoke_set_property_in_idle_cb");
4918 g_source_attach (idle_source, main_context);
4919 g_source_unref (idle_source);
4927 /* called in GDBusWorker thread with connection's lock held */
4929 handle_getset_property (GDBusConnection *connection,
4931 GDBusMessage *message,
4934 ExportedInterface *ei;
4936 const char *interface_name;
4937 const char *property_name;
4942 g_variant_get (g_dbus_message_get_body (message),
4947 g_variant_get (g_dbus_message_get_body (message),
4953 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4954 * no such interface registered
4956 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4959 GDBusMessage *reply;
4960 reply = g_dbus_message_new_method_error (message,
4961 "org.freedesktop.DBus.Error.InvalidArgs",
4962 _("No such interface '%s'"),
4964 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4965 g_object_unref (reply);
4970 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4983 /* ---------------------------------------------------------------------------------------------------- */
4987 GDBusConnection *connection;
4988 GDBusMessage *message;
4990 const GDBusInterfaceVTable *vtable;
4991 GDBusInterfaceInfo *interface_info;
4992 guint registration_id;
4993 guint subtree_registration_id;
4994 } PropertyGetAllData;
4997 property_get_all_data_free (PropertyData *data)
4999 g_object_unref (data->connection);
5000 g_object_unref (data->message);
5004 /* called in thread where object was registered - no locks held */
5006 invoke_get_all_properties_in_idle_cb (gpointer _data)
5008 PropertyGetAllData *data = _data;
5009 GVariantBuilder builder;
5010 GDBusMessage *reply;
5013 if (has_object_been_unregistered (data->connection,
5014 data->registration_id,
5015 data->subtree_registration_id))
5017 reply = g_dbus_message_new_method_error (data->message,
5018 "org.freedesktop.DBus.Error.UnknownMethod",
5019 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
5020 g_dbus_message_get_path (data->message));
5021 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5022 g_object_unref (reply);
5026 /* TODO: Right now we never fail this call - we just omit values if
5027 * a get_property() call is failing.
5029 * We could fail the whole call if just a single get_property() call
5030 * returns an error. We need clarification in the D-Bus spec about this.
5032 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
5033 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
5034 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
5036 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
5039 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
5042 value = data->vtable->get_property (data->connection,
5043 g_dbus_message_get_sender (data->message),
5044 g_dbus_message_get_path (data->message),
5045 data->interface_info->name,
5046 property_info->name,
5053 g_variant_take_ref (value);
5054 g_variant_builder_add (&builder,
5056 property_info->name,
5058 g_variant_unref (value);
5060 g_variant_builder_close (&builder);
5062 reply = g_dbus_message_new_method_reply (data->message);
5063 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
5064 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5065 g_object_unref (reply);
5072 interface_has_readable_properties (GDBusInterfaceInfo *interface_info)
5076 if (!interface_info->properties)
5079 for (i = 0; interface_info->properties[i]; i++)
5080 if (interface_info->properties[i]->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE)
5086 /* called in any thread with connection's lock held */
5088 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
5089 GDBusMessage *message,
5090 guint registration_id,
5091 guint subtree_registration_id,
5092 GDBusInterfaceInfo *interface_info,
5093 const GDBusInterfaceVTable *vtable,
5094 GMainContext *main_context,
5098 GSource *idle_source;
5099 PropertyGetAllData *property_get_all_data;
5106 /* If the vtable pointer for get_property() is NULL but we have a
5107 * non-zero number of readable properties, then dispatch the call via
5108 * the method_call() handler.
5110 if (vtable->get_property == NULL && interface_has_readable_properties (interface_info))
5112 schedule_method_call (connection, message, registration_id, subtree_registration_id,
5113 interface_info, NULL, NULL, g_dbus_message_get_body (message),
5114 vtable, main_context, user_data);
5119 /* ok, got the property info - call user in an idle handler */
5120 property_get_all_data = g_new0 (PropertyGetAllData, 1);
5121 property_get_all_data->connection = g_object_ref (connection);
5122 property_get_all_data->message = g_object_ref (message);
5123 property_get_all_data->user_data = user_data;
5124 property_get_all_data->vtable = vtable;
5125 property_get_all_data->interface_info = interface_info;
5126 property_get_all_data->registration_id = registration_id;
5127 property_get_all_data->subtree_registration_id = subtree_registration_id;
5129 idle_source = g_idle_source_new ();
5130 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
5131 g_source_set_callback (idle_source,
5132 invoke_get_all_properties_in_idle_cb,
5133 property_get_all_data,
5134 (GDestroyNotify) property_get_all_data_free);
5135 g_source_set_name (idle_source, "[gio] invoke_get_all_properties_in_idle_cb");
5136 g_source_attach (idle_source, main_context);
5137 g_source_unref (idle_source);
5145 /* called in GDBusWorker thread with connection's lock held */
5147 handle_get_all_properties (GDBusConnection *connection,
5149 GDBusMessage *message)
5151 ExportedInterface *ei;
5153 const char *interface_name;
5157 g_variant_get (g_dbus_message_get_body (message),
5161 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
5162 * no such interface registered
5164 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5167 GDBusMessage *reply;
5168 reply = g_dbus_message_new_method_error (message,
5169 "org.freedesktop.DBus.Error.InvalidArgs",
5170 _("No such interface"),
5172 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5173 g_object_unref (reply);
5178 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
5190 /* ---------------------------------------------------------------------------------------------------- */
5192 static const gchar introspect_header[] =
5193 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
5194 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
5195 "<!-- GDBus " PACKAGE_VERSION " -->\n"
5198 static const gchar introspect_tail[] =
5201 static const gchar introspect_properties_interface[] =
5202 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
5203 " <method name=\"Get\">\n"
5204 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5205 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
5206 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
5208 " <method name=\"GetAll\">\n"
5209 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5210 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
5212 " <method name=\"Set\">\n"
5213 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5214 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
5215 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
5217 " <signal name=\"PropertiesChanged\">\n"
5218 " <arg type=\"s\" name=\"interface_name\"/>\n"
5219 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
5220 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
5224 static const gchar introspect_introspectable_interface[] =
5225 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
5226 " <method name=\"Introspect\">\n"
5227 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
5230 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
5231 " <method name=\"Ping\"/>\n"
5232 " <method name=\"GetMachineId\">\n"
5233 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
5238 introspect_append_header (GString *s)
5240 g_string_append (s, introspect_header);
5244 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
5246 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
5252 begin = object_path + path_len;
5253 end = strchr (begin, '/');
5255 s = g_strndup (begin, end - begin);
5257 s = g_strdup (begin);
5259 if (g_hash_table_lookup (set, s) == NULL)
5260 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
5266 /* TODO: we want a nicer public interface for this */
5267 /* called in any thread with connection's lock held */
5269 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
5274 GHashTableIter hash_iter;
5275 const gchar *object_path;
5281 CONNECTION_ENSURE_LOCK (connection);
5283 path_len = strlen (path);
5287 set = g_hash_table_new (g_str_hash, g_str_equal);
5289 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
5290 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
5291 maybe_add_path (path, path_len, object_path, set);
5293 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
5294 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
5295 maybe_add_path (path, path_len, object_path, set);
5297 p = g_ptr_array_new ();
5298 keys = g_hash_table_get_keys (set);
5299 for (l = keys; l != NULL; l = l->next)
5300 g_ptr_array_add (p, l->data);
5301 g_hash_table_unref (set);
5304 g_ptr_array_add (p, NULL);
5305 ret = (gchar **) g_ptr_array_free (p, FALSE);
5309 /* called in any thread with connection's lock not held */
5311 g_dbus_connection_list_registered (GDBusConnection *connection,
5315 CONNECTION_LOCK (connection);
5316 ret = g_dbus_connection_list_registered_unlocked (connection, path);
5317 CONNECTION_UNLOCK (connection);
5321 /* called in GDBusWorker thread with connection's lock held */
5323 handle_introspect (GDBusConnection *connection,
5325 GDBusMessage *message)
5329 GDBusMessage *reply;
5330 GHashTableIter hash_iter;
5331 ExportedInterface *ei;
5334 /* first the header with the standard interfaces */
5335 s = g_string_sized_new (sizeof (introspect_header) +
5336 sizeof (introspect_properties_interface) +
5337 sizeof (introspect_introspectable_interface) +
5338 sizeof (introspect_tail));
5339 introspect_append_header (s);
5340 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
5341 "org.freedesktop.DBus.Properties"))
5342 g_string_append (s, introspect_properties_interface);
5344 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
5345 "org.freedesktop.DBus.Introspectable"))
5346 g_string_append (s, introspect_introspectable_interface);
5348 /* then include the registered interfaces */
5349 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
5350 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
5351 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
5353 /* finally include nodes registered below us */
5354 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
5355 for (n = 0; registered != NULL && registered[n] != NULL; n++)
5356 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
5357 g_strfreev (registered);
5358 g_string_append (s, introspect_tail);
5360 reply = g_dbus_message_new_method_reply (message);
5361 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5362 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5363 g_object_unref (reply);
5364 g_string_free (s, TRUE);
5369 /* called in thread where object was registered - no locks held */
5371 call_in_idle_cb (gpointer user_data)
5373 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
5374 GDBusInterfaceVTable *vtable;
5375 guint registration_id;
5376 guint subtree_registration_id;
5378 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
5379 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
5381 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
5383 subtree_registration_id))
5385 GDBusMessage *reply;
5386 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
5387 "org.freedesktop.DBus.Error.UnknownMethod",
5388 _("No such interface '%s' on object at path %s"),
5389 g_dbus_method_invocation_get_interface_name (invocation),
5390 g_dbus_method_invocation_get_object_path (invocation));
5391 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5392 g_object_unref (reply);
5396 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
5397 g_assert (vtable != NULL && vtable->method_call != NULL);
5399 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
5400 g_dbus_method_invocation_get_sender (invocation),
5401 g_dbus_method_invocation_get_object_path (invocation),
5402 g_dbus_method_invocation_get_interface_name (invocation),
5403 g_dbus_method_invocation_get_method_name (invocation),
5404 g_dbus_method_invocation_get_parameters (invocation),
5405 g_object_ref (invocation),
5406 g_dbus_method_invocation_get_user_data (invocation));
5412 /* called in GDBusWorker thread with connection's lock held */
5414 schedule_method_call (GDBusConnection *connection,
5415 GDBusMessage *message,
5416 guint registration_id,
5417 guint subtree_registration_id,
5418 const GDBusInterfaceInfo *interface_info,
5419 const GDBusMethodInfo *method_info,
5420 const GDBusPropertyInfo *property_info,
5421 GVariant *parameters,
5422 const GDBusInterfaceVTable *vtable,
5423 GMainContext *main_context,
5426 GDBusMethodInvocation *invocation;
5427 GSource *idle_source;
5429 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
5430 g_dbus_message_get_path (message),
5431 g_dbus_message_get_interface (message),
5432 g_dbus_message_get_member (message),
5440 /* TODO: would be nicer with a real MethodData like we already
5441 * have PropertyData and PropertyGetAllData... */
5442 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
5443 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
5444 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
5446 idle_source = g_idle_source_new ();
5447 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
5448 g_source_set_callback (idle_source,
5452 g_source_set_name (idle_source, "[gio] call_in_idle_cb");
5453 g_source_attach (idle_source, main_context);
5454 g_source_unref (idle_source);
5457 /* called in GDBusWorker thread with connection's lock held */
5459 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
5460 GDBusMessage *message,
5461 guint registration_id,
5462 guint subtree_registration_id,
5463 GDBusInterfaceInfo *interface_info,
5464 const GDBusInterfaceVTable *vtable,
5465 GMainContext *main_context,
5468 GDBusMethodInfo *method_info;
5469 GDBusMessage *reply;
5470 GVariant *parameters;
5472 GVariantType *in_type;
5476 /* TODO: the cost of this is O(n) - it might be worth caching the result */
5477 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
5479 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
5480 * error to the caller
5482 if (method_info == NULL)
5484 reply = g_dbus_message_new_method_error (message,
5485 "org.freedesktop.DBus.Error.UnknownMethod",
5486 _("No such method '%s'"),
5487 g_dbus_message_get_member (message));
5488 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5489 g_object_unref (reply);
5494 parameters = g_dbus_message_get_body (message);
5495 if (parameters == NULL)
5497 parameters = g_variant_new ("()");
5498 g_variant_ref_sink (parameters);
5502 g_variant_ref (parameters);
5505 /* Check that the incoming args are of the right type - if they are not, return
5506 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
5508 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
5509 if (!g_variant_is_of_type (parameters, in_type))
5513 type_string = g_variant_type_dup_string (in_type);
5515 reply = g_dbus_message_new_method_error (message,
5516 "org.freedesktop.DBus.Error.InvalidArgs",
5517 _("Type of message, '%s', does not match expected type '%s'"),
5518 g_variant_get_type_string (parameters),
5520 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5521 g_variant_type_free (in_type);
5522 g_variant_unref (parameters);
5523 g_object_unref (reply);
5524 g_free (type_string);
5528 g_variant_type_free (in_type);
5530 /* schedule the call in idle */
5531 schedule_method_call (connection, message, registration_id, subtree_registration_id,
5532 interface_info, method_info, NULL, parameters,
5533 vtable, main_context, user_data);
5534 g_variant_unref (parameters);
5541 /* ---------------------------------------------------------------------------------------------------- */
5543 /* called in GDBusWorker thread with connection's lock held */
5545 obj_message_func (GDBusConnection *connection,
5547 GDBusMessage *message)
5549 const gchar *interface_name;
5550 const gchar *member;
5551 const gchar *signature;
5556 interface_name = g_dbus_message_get_interface (message);
5557 member = g_dbus_message_get_member (message);
5558 signature = g_dbus_message_get_signature (message);
5560 /* see if we have an interface for handling this call */
5561 if (interface_name != NULL)
5563 ExportedInterface *ei;
5564 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5567 /* we do - invoke the handler in idle in the right thread */
5569 /* handle no vtable or handler being present */
5570 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
5573 handled = validate_and_maybe_schedule_method_call (connection,
5585 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5586 g_strcmp0 (member, "Introspect") == 0 &&
5587 g_strcmp0 (signature, "") == 0)
5589 handled = handle_introspect (connection, eo, message);
5592 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5593 g_strcmp0 (member, "Get") == 0 &&
5594 g_strcmp0 (signature, "ss") == 0)
5596 handled = handle_getset_property (connection, eo, message, TRUE);
5599 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5600 g_strcmp0 (member, "Set") == 0 &&
5601 g_strcmp0 (signature, "ssv") == 0)
5603 handled = handle_getset_property (connection, eo, message, FALSE);
5606 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5607 g_strcmp0 (member, "GetAll") == 0 &&
5608 g_strcmp0 (signature, "s") == 0)
5610 handled = handle_get_all_properties (connection, eo, message);
5619 * g_dbus_connection_register_object:
5620 * @connection: a #GDBusConnection
5621 * @object_path: the object path to register at
5622 * @interface_info: introspection data for the interface
5623 * @vtable: (allow-none): a #GDBusInterfaceVTable to call into or %NULL
5624 * @user_data: (allow-none): data to pass to functions in @vtable
5625 * @user_data_free_func: function to call when the object path is unregistered
5626 * @error: return location for error or %NULL
5628 * Registers callbacks for exported objects at @object_path with the
5629 * D-Bus interface that is described in @interface_info.
5631 * Calls to functions in @vtable (and @user_data_free_func) will happen
5633 * [thread-default main context][g-main-context-push-thread-default]
5634 * of the thread you are calling this method from.
5636 * Note that all #GVariant values passed to functions in @vtable will match
5637 * the signature given in @interface_info - if a remote caller passes
5638 * incorrect values, the `org.freedesktop.DBus.Error.InvalidArgs`
5639 * is returned to the remote caller.
5641 * Additionally, if the remote caller attempts to invoke methods or
5642 * access properties not mentioned in @interface_info the
5643 * `org.freedesktop.DBus.Error.UnknownMethod` resp.
5644 * `org.freedesktop.DBus.Error.InvalidArgs` errors
5645 * are returned to the caller.
5647 * It is considered a programming error if the
5648 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
5649 * #GVariant of incorrect type.
5651 * If an existing callback is already registered at @object_path and
5652 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
5654 * GDBus automatically implements the standard D-Bus interfaces
5655 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
5656 * and org.freedesktop.Peer, so you don't have to implement those for the
5657 * objects you export. You can implement org.freedesktop.DBus.Properties
5658 * yourself, e.g. to handle getting and setting of properties asynchronously.
5660 * Note that the reference count on @interface_info will be
5661 * incremented by 1 (unless allocated statically, e.g. if the
5662 * reference count is -1, see g_dbus_interface_info_ref()) for as long
5663 * as the object is exported. Also note that @vtable will be copied.
5665 * See this [server][gdbus-server] for an example of how to use this method.
5667 * Returns: 0 if @error is set, otherwise a registration id (never 0)
5668 * that can be used with g_dbus_connection_unregister_object()
5673 g_dbus_connection_register_object (GDBusConnection *connection,
5674 const gchar *object_path,
5675 GDBusInterfaceInfo *interface_info,
5676 const GDBusInterfaceVTable *vtable,
5678 GDestroyNotify user_data_free_func,
5682 ExportedInterface *ei;
5685 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5686 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5687 g_return_val_if_fail (interface_info != NULL, 0);
5688 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
5689 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5690 g_return_val_if_fail (check_initialized (connection), 0);
5694 CONNECTION_LOCK (connection);
5696 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5699 eo = g_new0 (ExportedObject, 1);
5700 eo->object_path = g_strdup (object_path);
5701 eo->connection = connection;
5702 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
5705 (GDestroyNotify) exported_interface_free);
5706 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
5709 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
5715 _("An object is already exported for the interface %s at %s"),
5716 interface_info->name,
5721 ei = g_new0 (ExportedInterface, 1);
5722 ei->id = _global_registration_id++; /* TODO: overflow etc. */
5724 ei->user_data = user_data;
5725 ei->user_data_free_func = user_data_free_func;
5726 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
5727 ei->interface_info = g_dbus_interface_info_ref (interface_info);
5728 g_dbus_interface_info_cache_build (ei->interface_info);
5729 ei->interface_name = g_strdup (interface_info->name);
5730 ei->context = g_main_context_ref_thread_default ();
5732 g_hash_table_insert (eo->map_if_name_to_ei,
5733 (gpointer) ei->interface_name,
5735 g_hash_table_insert (connection->map_id_to_ei,
5736 GUINT_TO_POINTER (ei->id),
5742 CONNECTION_UNLOCK (connection);
5748 * g_dbus_connection_unregister_object:
5749 * @connection: a #GDBusConnection
5750 * @registration_id: a registration id obtained from
5751 * g_dbus_connection_register_object()
5753 * Unregisters an object.
5755 * Returns: %TRUE if the object was unregistered, %FALSE otherwise
5760 g_dbus_connection_unregister_object (GDBusConnection *connection,
5761 guint registration_id)
5763 ExportedInterface *ei;
5767 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5768 g_return_val_if_fail (check_initialized (connection), FALSE);
5772 CONNECTION_LOCK (connection);
5774 ei = g_hash_table_lookup (connection->map_id_to_ei,
5775 GUINT_TO_POINTER (registration_id));
5781 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5782 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5783 /* unregister object path if we have no more exported interfaces */
5784 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5785 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5791 CONNECTION_UNLOCK (connection);
5796 /* ---------------------------------------------------------------------------------------------------- */
5799 * g_dbus_connection_emit_signal:
5800 * @connection: a #GDBusConnection
5801 * @destination_bus_name: (allow-none): the unique bus name for the destination
5802 * for the signal or %NULL to emit to all listeners
5803 * @object_path: path of remote object
5804 * @interface_name: D-Bus interface to emit a signal on
5805 * @signal_name: the name of the signal to emit
5806 * @parameters: (allow-none): a #GVariant tuple with parameters for the signal
5807 * or %NULL if not passing parameters
5808 * @error: Return location for error or %NULL
5812 * If the parameters GVariant is floating, it is consumed.
5814 * This can only fail if @parameters is not compatible with the D-Bus protocol.
5816 * Returns: %TRUE unless @error is set
5821 g_dbus_connection_emit_signal (GDBusConnection *connection,
5822 const gchar *destination_bus_name,
5823 const gchar *object_path,
5824 const gchar *interface_name,
5825 const gchar *signal_name,
5826 GVariant *parameters,
5829 GDBusMessage *message;
5835 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5836 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5837 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5838 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5839 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5840 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5841 g_return_val_if_fail (check_initialized (connection), FALSE);
5843 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5845 _g_dbus_debug_print_lock ();
5846 g_print ("========================================================================\n"
5847 "GDBus-debug:Emission:\n"
5848 " >>>> SIGNAL EMISSION %s.%s()\n"
5850 " destination %s\n",
5851 interface_name, signal_name,
5853 destination_bus_name != NULL ? destination_bus_name : "(none)");
5854 _g_dbus_debug_print_unlock ();
5857 message = g_dbus_message_new_signal (object_path,
5861 if (destination_bus_name != NULL)
5862 g_dbus_message_set_header (message,
5863 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5864 g_variant_new_string (destination_bus_name));
5866 if (parameters != NULL)
5867 g_dbus_message_set_body (message, parameters);
5869 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5870 g_object_unref (message);
5876 add_call_flags (GDBusMessage *message,
5877 GDBusCallFlags flags)
5879 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5880 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
5884 decode_method_reply (GDBusMessage *reply,
5885 const gchar *method_name,
5886 const GVariantType *reply_type,
5887 GUnixFDList **out_fd_list,
5893 switch (g_dbus_message_get_message_type (reply))
5895 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5896 result = g_dbus_message_get_body (reply);
5899 result = g_variant_new ("()");
5900 g_variant_ref_sink (result);
5904 g_variant_ref (result);
5907 if (!g_variant_is_of_type (result, reply_type))
5909 gchar *type_string = g_variant_type_dup_string (reply_type);
5913 G_IO_ERROR_INVALID_ARGUMENT,
5914 _("Method '%s' returned type '%s', but expected '%s'"),
5915 method_name, g_variant_get_type_string (result), type_string);
5917 g_variant_unref (result);
5918 g_free (type_string);
5925 if (out_fd_list != NULL)
5927 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5928 if (*out_fd_list != NULL)
5929 g_object_ref (*out_fd_list);
5935 case G_DBUS_MESSAGE_TYPE_ERROR:
5936 g_dbus_message_to_gerror (reply, error);
5940 g_assert_not_reached ();
5950 GSimpleAsyncResult *simple;
5951 GVariantType *reply_type;
5952 gchar *method_name; /* for error message */
5956 GUnixFDList *fd_list;
5960 call_state_free (CallState *state)
5962 g_variant_type_free (state->reply_type);
5963 g_free (state->method_name);
5965 if (state->value != NULL)
5966 g_variant_unref (state->value);
5967 if (state->fd_list != NULL)
5968 g_object_unref (state->fd_list);
5969 g_slice_free (CallState, state);
5972 /* called in any thread, with the connection's lock not held */
5974 g_dbus_connection_call_done (GObject *source,
5975 GAsyncResult *result,
5978 GSimpleAsyncResult *simple;
5979 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5980 CallState *state = user_data;
5982 GDBusMessage *reply;
5985 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5989 if (G_UNLIKELY (_g_dbus_debug_call ()))
5991 _g_dbus_debug_print_lock ();
5992 g_print ("========================================================================\n"
5993 "GDBus-debug:Call:\n"
5994 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
6000 g_print ("SUCCESS\n");
6004 g_print ("FAILED: %s\n",
6007 _g_dbus_debug_print_unlock ();
6011 state->value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
6013 simple = state->simple; /* why? because state is freed before we unref simple.. */
6016 g_simple_async_result_take_error (state->simple, error);
6017 g_simple_async_result_complete (state->simple);
6018 call_state_free (state);
6022 g_simple_async_result_set_op_res_gpointer (state->simple, state, (GDestroyNotify) call_state_free);
6023 g_simple_async_result_complete (state->simple);
6025 g_clear_object (&reply);
6026 g_object_unref (simple);
6029 /* called in any thread, with the connection's lock not held */
6031 g_dbus_connection_call_internal (GDBusConnection *connection,
6032 const gchar *bus_name,
6033 const gchar *object_path,
6034 const gchar *interface_name,
6035 const gchar *method_name,
6036 GVariant *parameters,
6037 const GVariantType *reply_type,
6038 GDBusCallFlags flags,
6040 GUnixFDList *fd_list,
6041 GCancellable *cancellable,
6042 GAsyncReadyCallback callback,
6045 GDBusMessage *message;
6048 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
6049 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
6050 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
6051 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
6052 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
6053 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
6054 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
6055 g_return_if_fail (check_initialized (connection));
6057 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
6059 g_return_if_fail (fd_list == NULL);
6062 message = g_dbus_message_new_method_call (bus_name,
6066 add_call_flags (message, flags);
6067 if (parameters != NULL)
6068 g_dbus_message_set_body (message, parameters);
6071 if (fd_list != NULL)
6072 g_dbus_message_set_unix_fd_list (message, fd_list);
6075 /* If the user has no callback then we can just send the message with
6076 * the G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set and skip all
6077 * the logic for processing the reply. If the service sends the reply
6078 * anyway then it will just be ignored.
6080 if (callback != NULL)
6084 state = g_slice_new0 (CallState);
6085 state->simple = g_simple_async_result_new (G_OBJECT (connection),
6086 callback, user_data,
6087 g_dbus_connection_call_internal);
6088 g_simple_async_result_set_check_cancellable (state->simple, cancellable);
6089 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
6091 if (reply_type == NULL)
6092 reply_type = G_VARIANT_TYPE_ANY;
6094 state->reply_type = g_variant_type_copy (reply_type);
6096 g_dbus_connection_send_message_with_reply (connection,
6098 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
6102 g_dbus_connection_call_done,
6104 serial = state->serial;
6108 GDBusMessageFlags flags;
6110 flags = g_dbus_message_get_flags (message);
6111 flags |= G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
6112 g_dbus_message_set_flags (message, flags);
6114 g_dbus_connection_send_message (connection,
6116 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
6120 if (G_UNLIKELY (_g_dbus_debug_call ()))
6122 _g_dbus_debug_print_lock ();
6123 g_print ("========================================================================\n"
6124 "GDBus-debug:Call:\n"
6125 " >>>> ASYNC %s.%s()\n"
6127 " owned by name %s (serial %d)\n",
6131 bus_name != NULL ? bus_name : "(none)",
6133 _g_dbus_debug_print_unlock ();
6136 if (message != NULL)
6137 g_object_unref (message);
6140 /* called in any thread, with the connection's lock not held */
6142 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
6143 GUnixFDList **out_fd_list,
6147 GSimpleAsyncResult *simple;
6150 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
6151 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
6152 g_dbus_connection_call_internal), NULL);
6153 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6155 simple = G_SIMPLE_ASYNC_RESULT (res);
6157 if (g_simple_async_result_propagate_error (simple, error))
6160 state = g_simple_async_result_get_op_res_gpointer (simple);
6161 if (out_fd_list != NULL)
6162 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
6163 return g_variant_ref (state->value);
6166 /* called in any user thread, with the connection's lock not held */
6168 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
6169 const gchar *bus_name,
6170 const gchar *object_path,
6171 const gchar *interface_name,
6172 const gchar *method_name,
6173 GVariant *parameters,
6174 const GVariantType *reply_type,
6175 GDBusCallFlags flags,
6177 GUnixFDList *fd_list,
6178 GUnixFDList **out_fd_list,
6179 GCancellable *cancellable,
6182 GDBusMessage *message;
6183 GDBusMessage *reply;
6185 GError *local_error;
6186 GDBusSendMessageFlags send_flags;
6192 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
6193 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
6194 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
6195 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
6196 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
6197 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
6198 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
6200 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
6202 g_return_val_if_fail (fd_list == NULL, NULL);
6204 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6206 if (!(flags & CALL_FLAGS_INITIALIZING))
6207 g_return_val_if_fail (check_initialized (connection), FALSE);
6209 if (reply_type == NULL)
6210 reply_type = G_VARIANT_TYPE_ANY;
6212 message = g_dbus_message_new_method_call (bus_name,
6216 add_call_flags (message, flags);
6217 if (parameters != NULL)
6218 g_dbus_message_set_body (message, parameters);
6221 if (fd_list != NULL)
6222 g_dbus_message_set_unix_fd_list (message, fd_list);
6225 if (G_UNLIKELY (_g_dbus_debug_call ()))
6227 _g_dbus_debug_print_lock ();
6228 g_print ("========================================================================\n"
6229 "GDBus-debug:Call:\n"
6230 " >>>> SYNC %s.%s()\n"
6232 " owned by name %s\n",
6236 bus_name != NULL ? bus_name : "(none)");
6237 _g_dbus_debug_print_unlock ();
6242 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
6244 /* translate from one flavour of flags to another... */
6245 if (flags & CALL_FLAGS_INITIALIZING)
6246 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
6248 reply = g_dbus_connection_send_message_with_reply_sync (connection,
6252 NULL, /* volatile guint32 *out_serial */
6256 if (G_UNLIKELY (_g_dbus_debug_call ()))
6258 _g_dbus_debug_print_lock ();
6259 g_print ("========================================================================\n"
6260 "GDBus-debug:Call:\n"
6261 " <<<< SYNC COMPLETE %s.%s()\n"
6267 g_print ("SUCCESS\n");
6271 g_print ("FAILED: %s\n",
6272 local_error->message);
6274 _g_dbus_debug_print_unlock ();
6280 *error = local_error;
6282 g_error_free (local_error);
6286 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
6289 if (message != NULL)
6290 g_object_unref (message);
6292 g_object_unref (reply);
6297 /* ---------------------------------------------------------------------------------------------------- */
6300 * g_dbus_connection_call:
6301 * @connection: a #GDBusConnection
6302 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6303 * @connection is not a message bus connection
6304 * @object_path: path of remote object
6305 * @interface_name: D-Bus interface to invoke method on
6306 * @method_name: the name of the method to invoke
6307 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6308 * or %NULL if not passing parameters
6309 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6310 * @flags: flags from the #GDBusCallFlags enumeration
6311 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6312 * timeout or %G_MAXINT for no timeout
6313 * @cancellable: (allow-none): a #GCancellable or %NULL
6314 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request
6315 * is satisfied or %NULL if you don't care about the result of the
6317 * @user_data: the data to pass to @callback
6319 * Asynchronously invokes the @method_name method on the
6320 * @interface_name D-Bus interface on the remote object at
6321 * @object_path owned by @bus_name.
6323 * If @connection is closed then the operation will fail with
6324 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
6325 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
6326 * not compatible with the D-Bus protocol, the operation fails with
6327 * %G_IO_ERROR_INVALID_ARGUMENT.
6329 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
6330 * error will be raised if it does not match. Said another way, if you give a @reply_type
6331 * then any non-%NULL return value will be of this type.
6333 * If the @parameters #GVariant is floating, it is consumed. This allows
6334 * convenient 'inline' use of g_variant_new(), e.g.:
6335 * |[<!-- language="C" -->
6336 * g_dbus_connection_call (connection,
6337 * "org.freedesktop.StringThings",
6338 * "/org/freedesktop/StringThings",
6339 * "org.freedesktop.StringThings",
6341 * g_variant_new ("(ss)",
6345 * G_DBUS_CALL_FLAGS_NONE,
6348 * (GAsyncReadyCallback) two_strings_done,
6352 * This is an asynchronous method. When the operation is finished,
6353 * @callback will be invoked in the
6354 * [thread-default main context][g-main-context-push-thread-default]
6355 * of the thread you are calling this method from. You can then call
6356 * g_dbus_connection_call_finish() to get the result of the operation.
6357 * See g_dbus_connection_call_sync() for the synchronous version of this
6360 * If @callback is %NULL then the D-Bus method call message will be sent with
6361 * the %G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set.
6366 g_dbus_connection_call (GDBusConnection *connection,
6367 const gchar *bus_name,
6368 const gchar *object_path,
6369 const gchar *interface_name,
6370 const gchar *method_name,
6371 GVariant *parameters,
6372 const GVariantType *reply_type,
6373 GDBusCallFlags flags,
6375 GCancellable *cancellable,
6376 GAsyncReadyCallback callback,
6379 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);
6383 * g_dbus_connection_call_finish:
6384 * @connection: a #GDBusConnection
6385 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call()
6386 * @error: return location for error or %NULL
6388 * Finishes an operation started with g_dbus_connection_call().
6390 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6391 * return values. Free with g_variant_unref().
6396 g_dbus_connection_call_finish (GDBusConnection *connection,
6400 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
6404 * g_dbus_connection_call_sync:
6405 * @connection: a #GDBusConnection
6406 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6407 * @connection is not a message bus connection
6408 * @object_path: path of remote object
6409 * @interface_name: D-Bus interface to invoke method on
6410 * @method_name: the name of the method to invoke
6411 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6412 * or %NULL if not passing parameters
6413 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6414 * @flags: flags from the #GDBusCallFlags enumeration
6415 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6416 * timeout or %G_MAXINT for no timeout
6417 * @cancellable: (allow-none): a #GCancellable or %NULL
6418 * @error: return location for error or %NULL
6420 * Synchronously invokes the @method_name method on the
6421 * @interface_name D-Bus interface on the remote object at
6422 * @object_path owned by @bus_name.
6424 * If @connection is closed then the operation will fail with
6425 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
6426 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
6427 * contains a value not compatible with the D-Bus protocol, the operation
6428 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
6430 * If @reply_type is non-%NULL then the reply will be checked for having
6431 * this type and an error will be raised if it does not match. Said
6432 * another way, if you give a @reply_type then any non-%NULL return
6433 * value will be of this type.
6435 * If the @parameters #GVariant is floating, it is consumed.
6436 * This allows convenient 'inline' use of g_variant_new(), e.g.:
6437 * |[<!-- language="C" -->
6438 * g_dbus_connection_call_sync (connection,
6439 * "org.freedesktop.StringThings",
6440 * "/org/freedesktop/StringThings",
6441 * "org.freedesktop.StringThings",
6443 * g_variant_new ("(ss)",
6447 * G_DBUS_CALL_FLAGS_NONE,
6453 * The calling thread is blocked until a reply is received. See
6454 * g_dbus_connection_call() for the asynchronous version of
6457 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6458 * return values. Free with g_variant_unref().
6463 g_dbus_connection_call_sync (GDBusConnection *connection,
6464 const gchar *bus_name,
6465 const gchar *object_path,
6466 const gchar *interface_name,
6467 const gchar *method_name,
6468 GVariant *parameters,
6469 const GVariantType *reply_type,
6470 GDBusCallFlags flags,
6472 GCancellable *cancellable,
6475 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);
6478 /* ---------------------------------------------------------------------------------------------------- */
6483 * g_dbus_connection_call_with_unix_fd_list:
6484 * @connection: a #GDBusConnection
6485 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6486 * @connection is not a message bus connection
6487 * @object_path: path of remote object
6488 * @interface_name: D-Bus interface to invoke method on
6489 * @method_name: the name of the method to invoke
6490 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6491 * or %NULL if not passing parameters
6492 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6493 * @flags: flags from the #GDBusCallFlags enumeration
6494 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6495 * timeout or %G_MAXINT for no timeout
6496 * @fd_list: (allow-none): a #GUnixFDList or %NULL
6497 * @cancellable: (allow-none): a #GCancellable or %NULL
6498 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request is
6499 * satisfied or %NULL if you don't * care about the result of the
6501 * @user_data: The data to pass to @callback.
6503 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
6505 * This method is only available on UNIX.
6510 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
6511 const gchar *bus_name,
6512 const gchar *object_path,
6513 const gchar *interface_name,
6514 const gchar *method_name,
6515 GVariant *parameters,
6516 const GVariantType *reply_type,
6517 GDBusCallFlags flags,
6519 GUnixFDList *fd_list,
6520 GCancellable *cancellable,
6521 GAsyncReadyCallback callback,
6524 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);
6528 * g_dbus_connection_call_with_unix_fd_list_finish:
6529 * @connection: a #GDBusConnection
6530 * @out_fd_list: (out) (allow-none): return location for a #GUnixFDList or %NULL
6531 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
6532 * g_dbus_connection_call_with_unix_fd_list()
6533 * @error: return location for error or %NULL
6535 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
6537 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6538 * return values. Free with g_variant_unref().
6543 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
6544 GUnixFDList **out_fd_list,
6548 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
6552 * g_dbus_connection_call_with_unix_fd_list_sync:
6553 * @connection: a #GDBusConnection
6554 * @bus_name: (allow-none): a unique or well-known bus name or %NULL
6555 * if @connection is not a message bus connection
6556 * @object_path: path of remote object
6557 * @interface_name: D-Bus interface to invoke method on
6558 * @method_name: the name of the method to invoke
6559 * @parameters: (allow-none): a #GVariant tuple with parameters for
6560 * the method or %NULL if not passing parameters
6561 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6562 * @flags: flags from the #GDBusCallFlags enumeration
6563 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6564 * timeout or %G_MAXINT for no timeout
6565 * @fd_list: (allow-none): a #GUnixFDList or %NULL
6566 * @out_fd_list: (out) (allow-none): return location for a #GUnixFDList or %NULL
6567 * @cancellable: (allow-none): a #GCancellable or %NULL
6568 * @error: return location for error or %NULL
6570 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
6572 * This method is only available on UNIX.
6574 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6575 * return values. Free with g_variant_unref().
6580 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
6581 const gchar *bus_name,
6582 const gchar *object_path,
6583 const gchar *interface_name,
6584 const gchar *method_name,
6585 GVariant *parameters,
6586 const GVariantType *reply_type,
6587 GDBusCallFlags flags,
6589 GUnixFDList *fd_list,
6590 GUnixFDList **out_fd_list,
6591 GCancellable *cancellable,
6594 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);
6597 #endif /* G_OS_UNIX */
6599 /* ---------------------------------------------------------------------------------------------------- */
6601 struct ExportedSubtree
6605 GDBusConnection *connection;
6606 GDBusSubtreeVTable *vtable;
6607 GDBusSubtreeFlags flags;
6609 GMainContext *context;
6611 GDestroyNotify user_data_free_func;
6615 exported_subtree_free (ExportedSubtree *es)
6617 call_destroy_notify (es->context,
6618 es->user_data_free_func,
6621 g_main_context_unref (es->context);
6623 _g_dbus_subtree_vtable_free (es->vtable);
6624 g_free (es->object_path);
6628 /* called without lock held in the thread where the caller registered
6632 handle_subtree_introspect (GDBusConnection *connection,
6633 ExportedSubtree *es,
6634 GDBusMessage *message)
6638 GDBusMessage *reply;
6641 const gchar *sender;
6642 const gchar *requested_object_path;
6643 const gchar *requested_node;
6644 GDBusInterfaceInfo **interfaces;
6646 gchar **subnode_paths;
6647 gboolean has_properties_interface;
6648 gboolean has_introspectable_interface;
6652 requested_object_path = g_dbus_message_get_path (message);
6653 sender = g_dbus_message_get_sender (message);
6654 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6656 s = g_string_new (NULL);
6657 introspect_append_header (s);
6659 /* Strictly we don't need the children in dynamic mode, but we avoid the
6660 * conditionals to preserve code clarity
6662 children = es->vtable->enumerate (es->connection,
6669 requested_node = strrchr (requested_object_path, '/') + 1;
6671 /* Assert existence of object if we are not dynamic */
6672 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
6673 !_g_strv_has_string ((const gchar * const *) children, requested_node))
6678 requested_node = NULL;
6681 interfaces = es->vtable->introspect (es->connection,
6686 if (interfaces != NULL)
6688 has_properties_interface = FALSE;
6689 has_introspectable_interface = FALSE;
6691 for (n = 0; interfaces[n] != NULL; n++)
6693 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
6694 has_properties_interface = TRUE;
6695 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
6696 has_introspectable_interface = TRUE;
6698 if (!has_properties_interface)
6699 g_string_append (s, introspect_properties_interface);
6700 if (!has_introspectable_interface)
6701 g_string_append (s, introspect_introspectable_interface);
6703 for (n = 0; interfaces[n] != NULL; n++)
6705 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
6706 g_dbus_interface_info_unref (interfaces[n]);
6708 g_free (interfaces);
6711 /* then include <node> entries from the Subtree for the root */
6714 for (n = 0; children != NULL && children[n] != NULL; n++)
6715 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
6718 /* finally include nodes registered below us */
6719 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
6720 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
6721 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
6722 g_strfreev (subnode_paths);
6724 g_string_append (s, "</node>\n");
6726 reply = g_dbus_message_new_method_reply (message);
6727 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6728 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6729 g_object_unref (reply);
6734 g_string_free (s, TRUE);
6735 g_strfreev (children);
6739 /* called without lock held in the thread where the caller registered
6743 handle_subtree_method_invocation (GDBusConnection *connection,
6744 ExportedSubtree *es,
6745 GDBusMessage *message)
6748 const gchar *sender;
6749 const gchar *interface_name;
6750 const gchar *member;
6751 const gchar *signature;
6752 const gchar *requested_object_path;
6753 const gchar *requested_node;
6755 GDBusInterfaceInfo *interface_info;
6756 const GDBusInterfaceVTable *interface_vtable;
6757 gpointer interface_user_data;
6759 GDBusInterfaceInfo **interfaces;
6760 gboolean is_property_get;
6761 gboolean is_property_set;
6762 gboolean is_property_get_all;
6767 requested_object_path = g_dbus_message_get_path (message);
6768 sender = g_dbus_message_get_sender (message);
6769 interface_name = g_dbus_message_get_interface (message);
6770 member = g_dbus_message_get_member (message);
6771 signature = g_dbus_message_get_signature (message);
6772 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6774 is_property_get = FALSE;
6775 is_property_set = FALSE;
6776 is_property_get_all = FALSE;
6777 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6779 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6780 is_property_get = TRUE;
6781 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6782 is_property_set = TRUE;
6783 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6784 is_property_get_all = TRUE;
6789 requested_node = strrchr (requested_object_path, '/') + 1;
6791 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6793 /* We don't want to dispatch to unenumerated
6794 * nodes, so ensure that the child exists.
6799 children = es->vtable->enumerate (es->connection,
6804 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6805 g_strfreev (children);
6813 requested_node = NULL;
6816 /* get introspection data for the node */
6817 interfaces = es->vtable->introspect (es->connection,
6819 requested_object_path,
6823 if (interfaces == NULL)
6826 interface_info = NULL;
6827 for (n = 0; interfaces[n] != NULL; n++)
6829 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6830 interface_info = interfaces[n];
6833 /* dispatch the call if the user wants to handle it */
6834 if (interface_info != NULL)
6836 /* figure out where to dispatch the method call */
6837 interface_user_data = NULL;
6838 interface_vtable = es->vtable->dispatch (es->connection,
6843 &interface_user_data,
6845 if (interface_vtable == NULL)
6848 CONNECTION_LOCK (connection);
6849 handled = validate_and_maybe_schedule_method_call (es->connection,
6856 interface_user_data);
6857 CONNECTION_UNLOCK (connection);
6859 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6860 else if (is_property_get || is_property_set || is_property_get_all)
6862 if (is_property_get)
6863 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6864 else if (is_property_set)
6865 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6866 else if (is_property_get_all)
6867 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6869 g_assert_not_reached ();
6871 /* see if the object supports this interface at all */
6872 for (n = 0; interfaces[n] != NULL; n++)
6874 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6875 interface_info = interfaces[n];
6878 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6879 * claims it won't support the interface
6881 if (interface_info == NULL)
6883 GDBusMessage *reply;
6884 reply = g_dbus_message_new_method_error (message,
6885 "org.freedesktop.DBus.Error.InvalidArgs",
6886 _("No such interface '%s'"),
6888 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6889 g_object_unref (reply);
6894 /* figure out where to dispatch the property get/set/getall calls */
6895 interface_user_data = NULL;
6896 interface_vtable = es->vtable->dispatch (es->connection,
6901 &interface_user_data,
6903 if (interface_vtable == NULL)
6905 g_warning ("The subtree introspection function indicates that '%s' "
6906 "is a valid interface name, but calling the dispatch "
6907 "function on that interface gave us NULL", interface_name);
6911 if (is_property_get || is_property_set)
6913 CONNECTION_LOCK (connection);
6914 handled = validate_and_maybe_schedule_property_getset (es->connection,
6922 interface_user_data);
6923 CONNECTION_UNLOCK (connection);
6925 else if (is_property_get_all)
6927 CONNECTION_LOCK (connection);
6928 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6935 interface_user_data);
6936 CONNECTION_UNLOCK (connection);
6941 if (interfaces != NULL)
6943 for (n = 0; interfaces[n] != NULL; n++)
6944 g_dbus_interface_info_unref (interfaces[n]);
6945 g_free (interfaces);
6953 GDBusMessage *message;
6954 ExportedSubtree *es;
6955 } SubtreeDeferredData;
6958 subtree_deferred_data_free (SubtreeDeferredData *data)
6960 g_object_unref (data->message);
6964 /* called without lock held in the thread where the caller registered the subtree */
6966 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6968 SubtreeDeferredData *data = _data;
6973 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6974 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6975 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6976 handled = handle_subtree_introspect (data->es->connection,
6980 handled = handle_subtree_method_invocation (data->es->connection,
6986 CONNECTION_LOCK (data->es->connection);
6987 handled = handle_generic_unlocked (data->es->connection, data->message);
6988 CONNECTION_UNLOCK (data->es->connection);
6991 /* if we couldn't handle the request, just bail with the UnknownMethod error */
6994 GDBusMessage *reply;
6995 reply = g_dbus_message_new_method_error (data->message,
6996 "org.freedesktop.DBus.Error.UnknownMethod",
6997 _("Method '%s' on interface '%s' with signature '%s' does not exist"),
6998 g_dbus_message_get_member (data->message),
6999 g_dbus_message_get_interface (data->message),
7000 g_dbus_message_get_signature (data->message));
7001 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7002 g_object_unref (reply);
7008 /* called in GDBusWorker thread with connection's lock held */
7010 subtree_message_func (GDBusConnection *connection,
7011 ExportedSubtree *es,
7012 GDBusMessage *message)
7014 GSource *idle_source;
7015 SubtreeDeferredData *data;
7017 data = g_new0 (SubtreeDeferredData, 1);
7018 data->message = g_object_ref (message);
7021 /* defer this call to an idle handler in the right thread */
7022 idle_source = g_idle_source_new ();
7023 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
7024 g_source_set_callback (idle_source,
7025 process_subtree_vtable_message_in_idle_cb,
7027 (GDestroyNotify) subtree_deferred_data_free);
7028 g_source_set_name (idle_source, "[gio] process_subtree_vtable_message_in_idle_cb");
7029 g_source_attach (idle_source, es->context);
7030 g_source_unref (idle_source);
7032 /* since we own the entire subtree, handlers for objects not in the subtree have been
7033 * tried already by libdbus-1 - so we just need to ensure that we're always going
7034 * to reply to the message
7040 * g_dbus_connection_register_subtree:
7041 * @connection: a #GDBusConnection
7042 * @object_path: the object path to register the subtree at
7043 * @vtable: a #GDBusSubtreeVTable to enumerate, introspect and
7044 * dispatch nodes in the subtree
7045 * @flags: flags used to fine tune the behavior of the subtree
7046 * @user_data: data to pass to functions in @vtable
7047 * @user_data_free_func: function to call when the subtree is unregistered
7048 * @error: return location for error or %NULL
7050 * Registers a whole subtree of dynamic objects.
7052 * The @enumerate and @introspection functions in @vtable are used to
7053 * convey, to remote callers, what nodes exist in the subtree rooted
7056 * When handling remote calls into any node in the subtree, first the
7057 * @enumerate function is used to check if the node exists. If the node exists
7058 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
7059 * the @introspection function is used to check if the node supports the
7060 * requested method. If so, the @dispatch function is used to determine
7061 * where to dispatch the call. The collected #GDBusInterfaceVTable and
7062 * #gpointer will be used to call into the interface vtable for processing
7065 * All calls into user-provided code will be invoked in the
7066 * [thread-default main context][g-main-context-push-thread-default]
7067 * of the thread you are calling this method from.
7069 * If an existing subtree is already registered at @object_path or
7070 * then @error is set to #G_IO_ERROR_EXISTS.
7072 * Note that it is valid to register regular objects (using
7073 * g_dbus_connection_register_object()) in a subtree registered with
7074 * g_dbus_connection_register_subtree() - if so, the subtree handler
7075 * is tried as the last resort. One way to think about a subtree
7076 * handler is to consider it a fallback handler for object paths not
7077 * registered via g_dbus_connection_register_object() or other bindings.
7079 * Note that @vtable will be copied so you cannot change it after
7082 * See this [server][gdbus-subtree-server] for an example of how to use
7085 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
7086 * that can be used with g_dbus_connection_unregister_subtree() .
7091 g_dbus_connection_register_subtree (GDBusConnection *connection,
7092 const gchar *object_path,
7093 const GDBusSubtreeVTable *vtable,
7094 GDBusSubtreeFlags flags,
7096 GDestroyNotify user_data_free_func,
7100 ExportedSubtree *es;
7102 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
7103 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
7104 g_return_val_if_fail (vtable != NULL, 0);
7105 g_return_val_if_fail (error == NULL || *error == NULL, 0);
7106 g_return_val_if_fail (check_initialized (connection), 0);
7110 CONNECTION_LOCK (connection);
7112 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
7118 _("A subtree is already exported for %s"),
7123 es = g_new0 (ExportedSubtree, 1);
7124 es->object_path = g_strdup (object_path);
7125 es->connection = connection;
7127 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
7129 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
7130 es->user_data = user_data;
7131 es->user_data_free_func = user_data_free_func;
7132 es->context = g_main_context_ref_thread_default ();
7134 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
7135 g_hash_table_insert (connection->map_id_to_es,
7136 GUINT_TO_POINTER (es->id),
7142 CONNECTION_UNLOCK (connection);
7147 /* ---------------------------------------------------------------------------------------------------- */
7150 * g_dbus_connection_unregister_subtree:
7151 * @connection: a #GDBusConnection
7152 * @registration_id: a subtree registration id obtained from
7153 * g_dbus_connection_register_subtree()
7155 * Unregisters a subtree.
7157 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise
7162 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
7163 guint registration_id)
7165 ExportedSubtree *es;
7168 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
7169 g_return_val_if_fail (check_initialized (connection), FALSE);
7173 CONNECTION_LOCK (connection);
7175 es = g_hash_table_lookup (connection->map_id_to_es,
7176 GUINT_TO_POINTER (registration_id));
7180 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
7181 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
7186 CONNECTION_UNLOCK (connection);
7191 /* ---------------------------------------------------------------------------------------------------- */
7193 /* may be called in any thread, with connection's lock held */
7195 handle_generic_ping_unlocked (GDBusConnection *connection,
7196 const gchar *object_path,
7197 GDBusMessage *message)
7199 GDBusMessage *reply;
7200 reply = g_dbus_message_new_method_reply (message);
7201 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7202 g_object_unref (reply);
7205 /* may be called in any thread, with connection's lock held */
7207 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
7208 const gchar *object_path,
7209 GDBusMessage *message)
7211 GDBusMessage *reply;
7214 if (connection->machine_id == NULL)
7219 connection->machine_id = _g_dbus_get_machine_id (&error);
7220 if (connection->machine_id == NULL)
7222 reply = g_dbus_message_new_method_error_literal (message,
7223 "org.freedesktop.DBus.Error.Failed",
7225 g_error_free (error);
7231 reply = g_dbus_message_new_method_reply (message);
7232 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
7234 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7235 g_object_unref (reply);
7238 /* may be called in any thread, with connection's lock held */
7240 handle_generic_introspect_unlocked (GDBusConnection *connection,
7241 const gchar *object_path,
7242 GDBusMessage *message)
7247 GDBusMessage *reply;
7249 /* first the header */
7250 s = g_string_new (NULL);
7251 introspect_append_header (s);
7253 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
7254 for (n = 0; registered != NULL && registered[n] != NULL; n++)
7255 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
7256 g_strfreev (registered);
7257 g_string_append (s, "</node>\n");
7259 reply = g_dbus_message_new_method_reply (message);
7260 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
7261 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7262 g_object_unref (reply);
7263 g_string_free (s, TRUE);
7266 /* may be called in any thread, with connection's lock held */
7268 handle_generic_unlocked (GDBusConnection *connection,
7269 GDBusMessage *message)
7272 const gchar *interface_name;
7273 const gchar *member;
7274 const gchar *signature;
7277 CONNECTION_ENSURE_LOCK (connection);
7281 interface_name = g_dbus_message_get_interface (message);
7282 member = g_dbus_message_get_member (message);
7283 signature = g_dbus_message_get_signature (message);
7284 path = g_dbus_message_get_path (message);
7286 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
7287 g_strcmp0 (member, "Introspect") == 0 &&
7288 g_strcmp0 (signature, "") == 0)
7290 handle_generic_introspect_unlocked (connection, path, message);
7293 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7294 g_strcmp0 (member, "Ping") == 0 &&
7295 g_strcmp0 (signature, "") == 0)
7297 handle_generic_ping_unlocked (connection, path, message);
7300 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7301 g_strcmp0 (member, "GetMachineId") == 0 &&
7302 g_strcmp0 (signature, "") == 0)
7304 handle_generic_get_machine_id_unlocked (connection, path, message);
7311 /* ---------------------------------------------------------------------------------------------------- */
7313 /* called in GDBusWorker thread with connection's lock held */
7315 distribute_method_call (GDBusConnection *connection,
7316 GDBusMessage *message)
7318 GDBusMessage *reply;
7320 ExportedSubtree *es;
7321 const gchar *object_path;
7322 const gchar *interface_name;
7323 const gchar *member;
7325 gchar *subtree_path;
7328 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
7330 interface_name = g_dbus_message_get_interface (message);
7331 member = g_dbus_message_get_member (message);
7332 path = g_dbus_message_get_path (message);
7333 subtree_path = g_strdup (path);
7334 needle = strrchr (subtree_path, '/');
7335 if (needle != NULL && needle != subtree_path)
7341 g_free (subtree_path);
7342 subtree_path = NULL;
7346 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
7348 _g_dbus_debug_print_lock ();
7349 g_print ("========================================================================\n"
7350 "GDBus-debug:Incoming:\n"
7351 " <<<< METHOD INVOCATION %s.%s()\n"
7353 " invoked by name %s\n"
7355 interface_name, member,
7357 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
7358 g_dbus_message_get_serial (message));
7359 _g_dbus_debug_print_unlock ();
7362 object_path = g_dbus_message_get_path (message);
7363 g_assert (object_path != NULL);
7365 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
7368 if (obj_message_func (connection, eo, message))
7372 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
7375 if (subtree_message_func (connection, es, message))
7379 if (subtree_path != NULL)
7381 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
7384 if (subtree_message_func (connection, es, message))
7389 if (handle_generic_unlocked (connection, message))
7392 /* if we end up here, the message has not been not handled - so return an error saying this */
7393 reply = g_dbus_message_new_method_error (message,
7394 "org.freedesktop.DBus.Error.UnknownMethod",
7395 _("No such interface '%s' on object at path %s"),
7398 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7399 g_object_unref (reply);
7402 g_free (subtree_path);
7405 /* ---------------------------------------------------------------------------------------------------- */
7407 /* Called in any user thread, with the message_bus_lock held. */
7409 message_bus_get_singleton (GBusType bus_type,
7413 const gchar *starter_bus;
7419 case G_BUS_TYPE_SESSION:
7420 ret = &the_session_bus;
7423 case G_BUS_TYPE_SYSTEM:
7424 ret = &the_system_bus;
7427 case G_BUS_TYPE_USER:
7428 ret = &the_user_bus;
7431 case G_BUS_TYPE_MACHINE:
7432 ret = &the_machine_bus;
7435 case G_BUS_TYPE_STARTER:
7436 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
7437 if (g_strcmp0 (starter_bus, "session") == 0)
7439 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
7442 else if (g_strcmp0 (starter_bus, "system") == 0)
7444 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
7449 if (starter_bus != NULL)
7453 G_IO_ERROR_INVALID_ARGUMENT,
7454 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
7455 " - unknown value '%s'"),
7460 g_set_error_literal (error,
7462 G_IO_ERROR_INVALID_ARGUMENT,
7463 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
7464 "variable is not set"));
7470 g_assert_not_reached ();
7478 /* Called in any user thread, without holding locks. */
7479 static GDBusConnection *
7480 get_uninitialized_connection (GBusType bus_type,
7481 GCancellable *cancellable,
7484 GWeakRef *singleton;
7485 GDBusConnection *ret;
7489 G_LOCK (message_bus_lock);
7490 singleton = message_bus_get_singleton (bus_type, error);
7491 if (singleton == NULL)
7494 ret = g_weak_ref_get (singleton);
7499 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
7500 if (address == NULL)
7502 ret = g_object_new (G_TYPE_DBUS_CONNECTION,
7504 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
7505 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
7506 "exit-on-close", TRUE,
7509 g_weak_ref_set (singleton, ret);
7513 g_assert (ret != NULL);
7516 G_UNLOCK (message_bus_lock);
7520 /* May be called from any thread. Must not hold message_bus_lock. */
7522 _g_bus_get_singleton_if_exists (GBusType bus_type)
7524 GWeakRef *singleton;
7525 GDBusConnection *ret = NULL;
7527 G_LOCK (message_bus_lock);
7528 singleton = message_bus_get_singleton (bus_type, NULL);
7529 if (singleton == NULL)
7532 ret = g_weak_ref_get (singleton);
7535 G_UNLOCK (message_bus_lock);
7541 * @bus_type: a #GBusType
7542 * @cancellable: (allow-none): a #GCancellable or %NULL
7543 * @error: return location for error or %NULL
7545 * Synchronously connects to the message bus specified by @bus_type.
7546 * Note that the returned object may shared with other callers,
7547 * e.g. if two separate parts of a process calls this function with
7548 * the same @bus_type, they will share the same object.
7550 * This is a synchronous failable function. See g_bus_get() and
7551 * g_bus_get_finish() for the asynchronous version.
7553 * The returned object is a singleton, that is, shared with other
7554 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7555 * event that you need a private message bus connection, use
7556 * g_dbus_address_get_for_bus_sync() and
7557 * g_dbus_connection_new_for_address().
7559 * Note that the returned #GDBusConnection object will (usually) have
7560 * the #GDBusConnection:exit-on-close property set to %TRUE.
7562 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7563 * Free with g_object_unref().
7568 g_bus_get_sync (GBusType bus_type,
7569 GCancellable *cancellable,
7572 GDBusConnection *connection;
7574 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7576 connection = get_uninitialized_connection (bus_type, cancellable, error);
7577 if (connection == NULL)
7580 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
7582 g_object_unref (connection);
7591 bus_get_async_initable_cb (GObject *source_object,
7595 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
7599 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
7603 g_assert (error != NULL);
7604 g_simple_async_result_take_error (simple, error);
7605 g_object_unref (source_object);
7609 g_simple_async_result_set_op_res_gpointer (simple,
7613 g_simple_async_result_complete_in_idle (simple);
7614 g_object_unref (simple);
7619 * @bus_type: a #GBusType
7620 * @cancellable: (allow-none): a #GCancellable or %NULL
7621 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
7622 * @user_data: the data to pass to @callback
7624 * Asynchronously connects to the message bus specified by @bus_type.
7626 * When the operation is finished, @callback will be invoked. You can
7627 * then call g_bus_get_finish() to get the result of the operation.
7629 * This is a asynchronous failable function. See g_bus_get_sync() for
7630 * the synchronous version.
7635 g_bus_get (GBusType bus_type,
7636 GCancellable *cancellable,
7637 GAsyncReadyCallback callback,
7640 GDBusConnection *connection;
7641 GSimpleAsyncResult *simple;
7644 simple = g_simple_async_result_new (NULL,
7648 g_simple_async_result_set_check_cancellable (simple, cancellable);
7651 connection = get_uninitialized_connection (bus_type, cancellable, &error);
7652 if (connection == NULL)
7654 g_assert (error != NULL);
7655 g_simple_async_result_take_error (simple, error);
7656 g_simple_async_result_complete_in_idle (simple);
7657 g_object_unref (simple);
7661 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
7664 bus_get_async_initable_cb,
7671 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
7673 * @error: return location for error or %NULL
7675 * Finishes an operation started with g_bus_get().
7677 * The returned object is a singleton, that is, shared with other
7678 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7679 * event that you need a private message bus connection, use
7680 * g_dbus_address_get_for_bus_sync() and
7681 * g_dbus_connection_new_for_address().
7683 * Note that the returned #GDBusConnection object will (usually) have
7684 * the #GDBusConnection:exit-on-close property set to %TRUE.
7686 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7687 * Free with g_object_unref().
7692 g_bus_get_finish (GAsyncResult *res,
7695 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
7697 GDBusConnection *ret;
7699 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7701 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
7705 if (g_simple_async_result_propagate_error (simple, error))
7708 object = g_simple_async_result_get_op_res_gpointer (simple);
7709 g_assert (object != NULL);
7710 ret = g_object_ref (G_DBUS_CONNECTION (object));
7716 /* ---------------------------------------------------------------------------------------------------- */