1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
18 * Author: David Zeuthen <davidz@redhat.com>
24 * - would be nice to expose GDBusAuthMechanism and an extension point
26 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
27 * the mechanism VFuncs need to be able to set an error.
29 * - Need to document other mechanisms/sources for determining the D-Bus
30 * address of a well-known bus.
32 * - e.g. on Win32 we need code like from here
34 * http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
36 * that was never copied over here because it originally was copy-paste
37 * from the GPLv2 / AFL 2.1 libdbus sources.
39 * - on OS X we need to look in launchd for the address
41 * https://bugs.freedesktop.org/show_bug.cgi?id=14259
43 * - on X11 we need to look in a X11 property on the X server
44 * - (we can also just use dbus-launch(1) from the D-Bus
47 * - (ideally) this requires D-Bus spec work because none of
48 * this has never really been specced out properly (except
51 * - Related to the above, we also need to be able to launch a message bus
52 * instance.... Since we don't want to write our own bus daemon we should
53 * launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
55 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
56 * to specify where the nonce is stored. This will allow people to use
57 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
58 * to easily achieve secure RPC via nonce-tcp.
60 * - need to expose an extension point for resolving D-Bus address and
61 * turning them into GIOStream objects. This will allow us to implement
62 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
64 * - see g_dbus_address_connect() in gdbusaddress.c
66 * - would be cute to use kernel-specific APIs to resolve fds for
67 * debug output when using G_DBUS_DEBUG=message, e.g. in addition to
69 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
71 * maybe we can show more information about what fd 21 really is.
72 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
73 * Initial experiments on Linux 2.6 suggests that the symlink looks
78 * e.g. not of much use.
80 * - GDBus High-Level docs
81 * - Proxy: properties, signals...
82 * - Connection: IOStream based, ::close, connection setup steps
83 * mainloop integration, threading
84 * - Differences from libdbus (extend "Migrating from")
85 * - the message handling thread
86 * - Using GVariant instead of GValue
87 * - Explain why the high-level API is a good thing and what
88 * kind of pitfalls it avoids
89 * - Export objects before claiming names
90 * - Talk about auto-starting services (cf. GBusNameWatcherFlags)
92 * - use abstract sockets in test code
93 * - right now it doesn't work, dbus-daemon(1) fails with
95 * /gdbus/connection/filter: Failed to start message bus: Failed to bind
96 * socket "/tmp/g-dbus-tests-pid-28531": Address already in use
97 * ** WARNING **: Error reading address from dbus daemon, 0 bytes read
107 #include "gdbusauth.h"
108 #include "gdbusutils.h"
109 #include "gdbusaddress.h"
110 #include "gdbusmessage.h"
111 #include "gdbusconnection.h"
112 #include "gdbuserror.h"
113 #include "gioenumtypes.h"
114 #include "gdbusintrospection.h"
115 #include "gdbusmethodinvocation.h"
116 #include "gdbusprivate.h"
117 #include "gdbusauthobserver.h"
118 #include "ginitable.h"
119 #include "gasyncinitable.h"
120 #include "giostream.h"
121 #include "gasyncresult.h"
122 #include "gsimpleasyncresult.h"
126 #include "gkdbusconnection.h"
127 #include "gunixconnection.h"
128 #include "gunixfdmessage.h"
131 #include "glibintl.h"
134 * SECTION:gdbusconnection
135 * @short_description: D-Bus Connections
136 * @include: gio/gio.h
138 * The #GDBusConnection type is used for D-Bus connections to remote
139 * peers such as a message buses. It is a low-level API that offers a
140 * lot of flexibility. For instance, it lets you establish a connection
141 * over any transport that can by represented as an #GIOStream.
143 * This class is rarely used directly in D-Bus clients. If you are writing
144 * a D-Bus client, it is often easier to use the g_bus_own_name(),
145 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
147 * As an exception to the usual GLib rule that a particular object must not
148 * be used by two threads at the same time, #GDBusConnection's methods may be
149 * called from any thread. This is so that g_bus_get() and g_bus_get_sync()
150 * can safely return the same #GDBusConnection when called from any thread.
152 * Most of the ways to obtain a #GDBusConnection automatically initialize it
153 * (i.e. connect to D-Bus): for instance, g_dbus_connection_new() and
154 * g_bus_get(), and the synchronous versions of those methods, give you an
155 * initialized connection. Language bindings for GIO should use
156 * g_initable_new() or g_async_initable_new_async(), which also initialize the
159 * If you construct an uninitialized #GDBusConnection, such as via
160 * g_object_new(), you must initialize it via g_initable_init() or
161 * g_async_initable_init_async() before using its methods or properties.
162 * Calling methods or accessing properties on a #GDBusConnection that has not
163 * completed initialization successfully is considered to be invalid, and leads
164 * to undefined behaviour. In particular, if initialization fails with a
165 * #GError, the only valid thing you can do with that #GDBusConnection is to
166 * free it with g_object_unref().
168 * ## An example D-Bus server # {#gdbus-server}
170 * Here is an example for a D-Bus server:
171 * [gdbus-example-server.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-server.c)
173 * ## An example for exporting a subtree # {#gdbus-subtree-server}
175 * Here is an example for exporting a subtree:
176 * [gdbus-example-subtree.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-subtree.c)
178 * ## An example for file descriptor passing # {#gdbus-unix-fd-client}
180 * Here is an example for passing UNIX file descriptors:
181 * [gdbus-unix-fd-client.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-unix-fd-client.c)
183 * ## An example for exporting a GObject # {#gdbus-export}
185 * Here is an example for exporting a #GObject:
186 * [gdbus-example-export.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-export.c)
189 /* ---------------------------------------------------------------------------------------------------- */
191 typedef struct _GDBusConnectionClass GDBusConnectionClass;
194 * GDBusConnectionClass:
195 * @closed: Signal class handler for the #GDBusConnection::closed signal.
197 * Class structure for #GDBusConnection.
201 struct _GDBusConnectionClass
204 GObjectClass parent_class;
208 void (*closed) (GDBusConnection *connection,
209 gboolean remote_peer_vanished,
213 G_LOCK_DEFINE_STATIC (message_bus_lock);
215 static GWeakRef the_session_bus;
216 static GWeakRef the_system_bus;
217 static GWeakRef the_user_bus;
218 static GWeakRef the_machine_bus;
220 /* Extra pseudo-member of GDBusSendMessageFlags.
221 * Set by initable_init() to indicate that despite not being initialized yet,
222 * enough of the only-valid-after-init members are set that we can send a
223 * message, and we're being called from its thread, so no memory barrier is
224 * required before accessing them.
226 #define SEND_MESSAGE_FLAGS_INITIALIZING (1<<31)
228 /* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
229 #define CALL_FLAGS_INITIALIZING (1<<31)
231 /* ---------------------------------------------------------------------------------------------------- */
235 GDestroyNotify callback;
237 GMainContext *context;
238 } CallDestroyNotifyData;
241 call_destroy_notify_data_in_idle (gpointer user_data)
243 CallDestroyNotifyData *data = user_data;
244 data->callback (data->user_data);
249 call_destroy_notify_data_free (CallDestroyNotifyData *data)
251 if (data->context != NULL)
252 g_main_context_unref (data->context);
257 * call_destroy_notify: <internal>
258 * @context: (allow-none): A #GMainContext or %NULL.
259 * @callback: (allow-none): A #GDestroyNotify or %NULL.
260 * @user_data: Data to pass to @callback.
262 * Schedules @callback to run in @context.
265 call_destroy_notify (GMainContext *context,
266 GDestroyNotify callback,
269 GSource *idle_source;
270 CallDestroyNotifyData *data;
272 if (callback == NULL)
275 data = g_new0 (CallDestroyNotifyData, 1);
276 data->callback = callback;
277 data->user_data = user_data;
278 data->context = context;
279 if (data->context != NULL)
280 g_main_context_ref (data->context);
282 idle_source = g_idle_source_new ();
283 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
284 g_source_set_callback (idle_source,
285 call_destroy_notify_data_in_idle,
287 (GDestroyNotify) call_destroy_notify_data_free);
288 g_source_set_name (idle_source, "[gio] call_destroy_notify_data_in_idle");
289 g_source_attach (idle_source, data->context);
290 g_source_unref (idle_source);
296 /* ---------------------------------------------------------------------------------------------------- */
299 _g_strv_has_string (const gchar* const *haystack,
304 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
306 if (g_strcmp0 (haystack[n], needle) == 0)
312 /* ---------------------------------------------------------------------------------------------------- */
315 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
317 // TODO: for some reason this doesn't work on Windows
318 #define CONNECTION_ENSURE_LOCK(obj) do { \
319 if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock))) \
321 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
322 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
327 #define CONNECTION_LOCK(obj) do { \
328 g_mutex_lock (&(obj)->lock); \
331 #define CONNECTION_UNLOCK(obj) do { \
332 g_mutex_unlock (&(obj)->lock); \
335 /* Flags in connection->atomic_flags */
337 FLAG_INITIALIZED = 1 << 0,
338 FLAG_EXIT_ON_CLOSE = 1 << 1,
345 * The #GDBusConnection structure contains only private data and
346 * should only be accessed using the provided API.
350 struct _GDBusConnection
353 GObject parent_instance;
355 /* ------------------------------------------------------------------------ */
356 /* -- General object state ------------------------------------------------ */
357 /* ------------------------------------------------------------------------ */
359 /* General-purpose lock for most fields */
362 /* A lock used in the init() method of the GInitable interface - see comments
363 * in initable_init() for why a separate lock is needed.
365 * If you need both @lock and @init_lock, you must take @init_lock first.
369 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
370 * someone calls org.freedesktop.DBus.Peer.GetMachineId(). Protected by @lock.
374 /* The underlying stream used for communication
375 * Read-only after initable_init(), so it may be read if you either
376 * hold @init_lock or check for initialization first.
380 /* The object used for authentication (if any).
381 * Read-only after initable_init(), so it may be read if you either
382 * hold @init_lock or check for initialization first.
386 /* Last serial used. Protected by @lock. */
389 /* The object used to send/receive messages.
390 * Read-only after initable_init(), so it may be read if you either
391 * hold @init_lock or check for initialization first.
395 /* If connected to a message bus, this contains the unique name assigned to
396 * us by the bus (e.g. ":1.42").
397 * Read-only after initable_init(), so it may be read if you either
398 * hold @init_lock or check for initialization first.
400 gchar *bus_unique_name;
402 /* The GUID returned by the other side if we authenticed as a client or
403 * the GUID to use if authenticating as a server.
404 * Read-only after initable_init(), so it may be read if you either
405 * hold @init_lock or check for initialization first.
409 /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
410 * Inspect @initialization_error to see whether it succeeded or failed.
412 * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
414 * FLAG_CLOSED is the closed property. It may be read at any time, but
415 * may only be written while holding @lock.
417 volatile gint atomic_flags;
419 /* If the connection could not be established during initable_init(),
420 * this GError will be set.
421 * Read-only after initable_init(), so it may be read if you either
422 * hold @init_lock or check for initialization first.
424 GError *initialization_error;
426 /* The result of g_main_context_ref_thread_default() when the object
427 * was created (the GObject _init() function) - this is used for delivery
428 * of the :closed GObject signal.
430 * Only set in the GObject init function, so no locks are needed.
432 GMainContext *main_context_at_construction;
434 /* Read-only construct properties, no locks needed */
436 GDBusConnectionFlags flags;
438 /* Map used for managing method replies, protected by @lock */
439 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
441 /* Maps used for managing signal subscription, protected by @lock */
442 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
443 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
444 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
446 /* Maps used for managing exported objects and subtrees,
449 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
450 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
451 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
452 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
454 /* Map used for storing last used serials for each thread, protected by @lock */
455 GHashTable *map_thread_to_last_serial;
457 /* Structure used for message filters, protected by @lock */
460 /* Capabilities negotiated during authentication
461 * Read-only after initable_init(), so it may be read without holding a
462 * lock, if you check for initialization first.
464 GDBusCapabilityFlags capabilities;
466 /* Protected by @init_lock */
467 GDBusAuthObserver *authentication_observer;
469 /* Read-only after initable_init(), so it may be read if you either
470 * hold @init_lock or check for initialization first.
472 GCredentials *credentials;
474 /* set to TRUE when finalizing */
478 typedef struct ExportedObject ExportedObject;
479 static void exported_object_free (ExportedObject *eo);
481 typedef struct ExportedSubtree ExportedSubtree;
482 static void exported_subtree_free (ExportedSubtree *es);
500 PROP_CAPABILITY_FLAGS,
501 PROP_AUTHENTICATION_OBSERVER,
504 static void distribute_signals (GDBusConnection *connection,
505 GDBusMessage *message);
507 static void distribute_method_call (GDBusConnection *connection,
508 GDBusMessage *message);
510 static gboolean handle_generic_unlocked (GDBusConnection *connection,
511 GDBusMessage *message);
514 static void purge_all_signal_subscriptions (GDBusConnection *connection);
515 static void purge_all_filters (GDBusConnection *connection);
517 static void schedule_method_call (GDBusConnection *connection,
518 GDBusMessage *message,
519 guint registration_id,
520 guint subtree_registration_id,
521 const GDBusInterfaceInfo *interface_info,
522 const GDBusMethodInfo *method_info,
523 const GDBusPropertyInfo *property_info,
524 GVariant *parameters,
525 const GDBusInterfaceVTable *vtable,
526 GMainContext *main_context,
529 #define _G_ENSURE_LOCK(name) do { \
530 if (G_UNLIKELY (G_TRYLOCK(name))) \
532 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
533 "_G_ENSURE_LOCK: Lock '" #name "' is not locked"); \
537 static guint signals[LAST_SIGNAL] = { 0 };
539 static void initable_iface_init (GInitableIface *initable_iface);
540 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
542 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
543 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
544 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
548 * Check that all members of @connection that can only be accessed after
549 * the connection is initialized can safely be accessed. If not,
550 * log a critical warning. This function is a memory barrier.
552 * Returns: %TRUE if initialized
555 check_initialized (GDBusConnection *connection)
557 /* The access to @atomic_flags isn't conditional, so that this function
558 * provides a memory barrier for thread-safety even if checks are disabled.
559 * (If you don't want this stricter guarantee, you can call
560 * g_return_if_fail (check_initialized (c)).)
562 * This isn't strictly necessary now that we've decided use of an
563 * uninitialized GDBusConnection is undefined behaviour, but it seems
564 * better to be as deterministic as is feasible.
566 * (Anything that could suffer a crash from seeing undefined values
567 * must have a race condition - thread A initializes the connection while
568 * thread B calls a method without initialization, hoping that thread A will
569 * win the race - so its behaviour is undefined anyway.)
571 gint flags = g_atomic_int_get (&connection->atomic_flags);
573 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
575 /* We can safely access this, due to the memory barrier above */
576 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
582 MAY_BE_UNINITIALIZED = (1<<1)
583 } CheckUnclosedFlags;
586 * Check the same thing as check_initialized(), and also that the
587 * connection is not closed. If the connection is uninitialized,
588 * raise a critical warning (it's programmer error); if it's closed,
589 * raise a recoverable GError (it's a runtime error).
591 * This function is a memory barrier.
593 * Returns: %TRUE if initialized and not closed
596 check_unclosed (GDBusConnection *connection,
597 CheckUnclosedFlags check,
600 /* check_initialized() is effectively inlined, so we don't waste time
601 * doing two memory barriers
603 gint flags = g_atomic_int_get (&connection->atomic_flags);
605 if (!(check & MAY_BE_UNINITIALIZED))
607 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
608 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
611 if (flags & FLAG_CLOSED)
613 g_set_error_literal (error,
616 _("The connection is closed"));
623 static GHashTable *alive_connections = NULL;
626 g_dbus_connection_dispose (GObject *object)
628 GDBusConnection *connection = G_DBUS_CONNECTION (object);
630 G_LOCK (message_bus_lock);
631 CONNECTION_LOCK (connection);
632 if (connection->worker != NULL)
634 _g_dbus_worker_stop (connection->worker);
635 connection->worker = NULL;
636 if (alive_connections != NULL)
637 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
641 if (alive_connections != NULL)
642 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
644 CONNECTION_UNLOCK (connection);
645 G_UNLOCK (message_bus_lock);
647 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
648 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
652 g_dbus_connection_finalize (GObject *object)
654 GDBusConnection *connection = G_DBUS_CONNECTION (object);
656 connection->finalizing = TRUE;
658 purge_all_signal_subscriptions (connection);
660 purge_all_filters (connection);
661 g_ptr_array_unref (connection->filters);
663 if (connection->authentication_observer != NULL)
664 g_object_unref (connection->authentication_observer);
666 if (connection->auth != NULL)
667 g_object_unref (connection->auth);
669 if (connection->credentials)
670 g_object_unref (connection->credentials);
672 if (connection->stream != NULL)
674 g_object_unref (connection->stream);
675 connection->stream = NULL;
678 g_free (connection->address);
680 g_free (connection->guid);
681 g_free (connection->bus_unique_name);
683 if (connection->initialization_error != NULL)
684 g_error_free (connection->initialization_error);
686 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
688 g_hash_table_unref (connection->map_rule_to_signal_data);
689 g_hash_table_unref (connection->map_id_to_signal_data);
690 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
692 g_hash_table_unref (connection->map_id_to_ei);
693 g_hash_table_unref (connection->map_object_path_to_eo);
694 g_hash_table_unref (connection->map_id_to_es);
695 g_hash_table_unref (connection->map_object_path_to_es);
697 g_hash_table_unref (connection->map_thread_to_last_serial);
699 g_main_context_unref (connection->main_context_at_construction);
701 g_free (connection->machine_id);
703 g_mutex_clear (&connection->init_lock);
704 g_mutex_clear (&connection->lock);
706 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
709 /* called in any user thread, with the connection's lock not held */
711 g_dbus_connection_get_property (GObject *object,
716 GDBusConnection *connection = G_DBUS_CONNECTION (object);
721 g_value_set_object (value, g_dbus_connection_get_stream (connection));
725 g_value_set_string (value, g_dbus_connection_get_guid (connection));
728 case PROP_UNIQUE_NAME:
729 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
733 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
736 case PROP_EXIT_ON_CLOSE:
737 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
740 case PROP_CAPABILITY_FLAGS:
741 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
745 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
750 /* called in any user thread, with the connection's lock not held */
752 g_dbus_connection_set_property (GObject *object,
757 GDBusConnection *connection = G_DBUS_CONNECTION (object);
762 connection->stream = g_value_dup_object (value);
766 connection->guid = g_value_dup_string (value);
770 connection->address = g_value_dup_string (value);
774 connection->flags = g_value_get_flags (value);
777 case PROP_EXIT_ON_CLOSE:
778 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
781 case PROP_AUTHENTICATION_OBSERVER:
782 connection->authentication_observer = g_value_dup_object (value);
786 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
791 /* Base-class implementation of GDBusConnection::closed.
793 * Called in a user thread, by the main context that was thread-default when
794 * the object was constructed.
797 g_dbus_connection_real_closed (GDBusConnection *connection,
798 gboolean remote_peer_vanished,
801 gint flags = g_atomic_int_get (&connection->atomic_flags);
803 /* Because atomic int access is a memory barrier, we can safely read
804 * initialization_error without a lock, as long as we do it afterwards.
806 if (remote_peer_vanished &&
807 (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
808 (flags & FLAG_INITIALIZED) != 0 &&
809 connection->initialization_error == NULL)
813 g_printerr ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
816 g_quark_to_string (error->domain), error->code);
820 g_printerr ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
827 g_dbus_connection_class_init (GDBusConnectionClass *klass)
829 GObjectClass *gobject_class;
831 gobject_class = G_OBJECT_CLASS (klass);
833 gobject_class->finalize = g_dbus_connection_finalize;
834 gobject_class->dispose = g_dbus_connection_dispose;
835 gobject_class->set_property = g_dbus_connection_set_property;
836 gobject_class->get_property = g_dbus_connection_get_property;
838 klass->closed = g_dbus_connection_real_closed;
841 * GDBusConnection:stream:
843 * The underlying #GIOStream used for I/O.
845 * If this is passed on construction and is a #GSocketConnection,
846 * then the corresponding #GSocket will be put into non-blocking mode.
848 * While the #GDBusConnection is active, it will interact with this
849 * stream from a worker thread, so it is not safe to interact with
850 * the stream directly.
854 g_object_class_install_property (gobject_class,
856 g_param_spec_object ("stream",
858 P_("The underlying streams used for I/O"),
862 G_PARAM_CONSTRUCT_ONLY |
863 G_PARAM_STATIC_NAME |
864 G_PARAM_STATIC_BLURB |
865 G_PARAM_STATIC_NICK));
868 * GDBusConnection:address:
870 * A D-Bus address specifying potential endpoints that can be used
871 * when establishing the connection.
875 g_object_class_install_property (gobject_class,
877 g_param_spec_string ("address",
879 P_("D-Bus address specifying potential socket endpoints"),
882 G_PARAM_CONSTRUCT_ONLY |
883 G_PARAM_STATIC_NAME |
884 G_PARAM_STATIC_BLURB |
885 G_PARAM_STATIC_NICK));
888 * GDBusConnection:flags:
890 * Flags from the #GDBusConnectionFlags enumeration.
894 g_object_class_install_property (gobject_class,
896 g_param_spec_flags ("flags",
899 G_TYPE_DBUS_CONNECTION_FLAGS,
900 G_DBUS_CONNECTION_FLAGS_NONE,
902 G_PARAM_CONSTRUCT_ONLY |
903 G_PARAM_STATIC_NAME |
904 G_PARAM_STATIC_BLURB |
905 G_PARAM_STATIC_NICK));
908 * GDBusConnection:guid:
910 * The GUID of the peer performing the role of server when
913 * If you are constructing a #GDBusConnection and pass
914 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
915 * #GDBusConnection:flags property then you MUST also set this
916 * property to a valid guid.
918 * If you are constructing a #GDBusConnection and pass
919 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
920 * #GDBusConnection:flags property you will be able to read the GUID
921 * of the other peer here after the connection has been successfully
926 g_object_class_install_property (gobject_class,
928 g_param_spec_string ("guid",
930 P_("GUID of the server peer"),
934 G_PARAM_CONSTRUCT_ONLY |
935 G_PARAM_STATIC_NAME |
936 G_PARAM_STATIC_BLURB |
937 G_PARAM_STATIC_NICK));
940 * GDBusConnection:unique-name:
942 * The unique name as assigned by the message bus or %NULL if the
943 * connection is not open or not a message bus connection.
947 g_object_class_install_property (gobject_class,
949 g_param_spec_string ("unique-name",
951 P_("Unique name of bus connection"),
954 G_PARAM_STATIC_NAME |
955 G_PARAM_STATIC_BLURB |
956 G_PARAM_STATIC_NICK));
959 * GDBusConnection:closed:
961 * A boolean specifying whether the connection has been closed.
965 g_object_class_install_property (gobject_class,
967 g_param_spec_boolean ("closed",
969 P_("Whether the connection is closed"),
972 G_PARAM_STATIC_NAME |
973 G_PARAM_STATIC_BLURB |
974 G_PARAM_STATIC_NICK));
977 * GDBusConnection:exit-on-close:
979 * A boolean specifying whether the process will be terminated (by
980 * calling `raise(SIGTERM)`) if the connection is closed by the
983 * Note that #GDBusConnection objects returned by g_bus_get_finish()
984 * and g_bus_get_sync() will (usually) have this property set to %TRUE.
988 g_object_class_install_property (gobject_class,
990 g_param_spec_boolean ("exit-on-close",
992 P_("Whether the process is terminated when the connection is closed"),
996 G_PARAM_STATIC_NAME |
997 G_PARAM_STATIC_BLURB |
998 G_PARAM_STATIC_NICK));
1001 * GDBusConnection:capabilities:
1003 * Flags from the #GDBusCapabilityFlags enumeration
1004 * representing connection features negotiated with the other peer.
1008 g_object_class_install_property (gobject_class,
1009 PROP_CAPABILITY_FLAGS,
1010 g_param_spec_flags ("capabilities",
1013 G_TYPE_DBUS_CAPABILITY_FLAGS,
1014 G_DBUS_CAPABILITY_FLAGS_NONE,
1016 G_PARAM_STATIC_NAME |
1017 G_PARAM_STATIC_BLURB |
1018 G_PARAM_STATIC_NICK));
1021 * GDBusConnection:authentication-observer:
1023 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
1027 g_object_class_install_property (gobject_class,
1028 PROP_AUTHENTICATION_OBSERVER,
1029 g_param_spec_object ("authentication-observer",
1030 P_("Authentication Observer"),
1031 P_("Object used to assist in the authentication process"),
1032 G_TYPE_DBUS_AUTH_OBSERVER,
1034 G_PARAM_CONSTRUCT_ONLY |
1035 G_PARAM_STATIC_NAME |
1036 G_PARAM_STATIC_BLURB |
1037 G_PARAM_STATIC_NICK));
1040 * GDBusConnection::closed:
1041 * @connection: the #GDBusConnection emitting the signal
1042 * @remote_peer_vanished: %TRUE if @connection is closed because the
1043 * remote peer closed its end of the connection
1044 * @error: (allow-none): a #GError with more details about the event or %NULL
1046 * Emitted when the connection is closed.
1048 * The cause of this event can be
1050 * - If g_dbus_connection_close() is called. In this case
1051 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
1053 * - If the remote peer closes the connection. In this case
1054 * @remote_peer_vanished is set to %TRUE and @error is set.
1056 * - If the remote peer sends invalid or malformed data. In this
1057 * case @remote_peer_vanished is set to %FALSE and @error is set.
1059 * Upon receiving this signal, you should give up your reference to
1060 * @connection. You are guaranteed that this signal is emitted only
1065 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
1066 G_TYPE_DBUS_CONNECTION,
1068 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1079 g_dbus_connection_init (GDBusConnection *connection)
1081 g_mutex_init (&connection->lock);
1082 g_mutex_init (&connection->init_lock);
1084 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
1086 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1088 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1090 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1093 (GDestroyNotify) g_ptr_array_unref);
1095 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1098 (GDestroyNotify) exported_object_free);
1100 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1103 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1106 (GDestroyNotify) exported_subtree_free);
1108 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1111 connection->map_thread_to_last_serial = g_hash_table_new (g_direct_hash,
1114 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1116 connection->filters = g_ptr_array_new ();
1120 * g_dbus_connection_get_stream:
1121 * @connection: a #GDBusConnection
1123 * Gets the underlying stream used for IO.
1125 * While the #GDBusConnection is active, it will interact with this
1126 * stream from a worker thread, so it is not safe to interact with
1127 * the stream directly.
1129 * Returns: (transfer none): the stream used for IO
1134 g_dbus_connection_get_stream (GDBusConnection *connection)
1136 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1138 /* do not use g_return_val_if_fail(), we want the memory barrier */
1139 if (!check_initialized (connection))
1142 return connection->stream;
1146 * g_dbus_connection_start_message_processing:
1147 * @connection: a #GDBusConnection
1149 * If @connection was created with
1150 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1151 * starts processing messages. Does nothing on if @connection wasn't
1152 * created with this flag or if the method has already been called.
1157 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1159 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1161 /* do not use g_return_val_if_fail(), we want the memory barrier */
1162 if (!check_initialized (connection))
1165 g_assert (connection->worker != NULL);
1166 _g_dbus_worker_unfreeze (connection->worker);
1170 * g_dbus_connection_is_closed:
1171 * @connection: a #GDBusConnection
1173 * Gets whether @connection is closed.
1175 * Returns: %TRUE if the connection is closed, %FALSE otherwise
1180 g_dbus_connection_is_closed (GDBusConnection *connection)
1184 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1186 flags = g_atomic_int_get (&connection->atomic_flags);
1188 return (flags & FLAG_CLOSED) ? TRUE : FALSE;
1192 * g_dbus_connection_get_capabilities:
1193 * @connection: a #GDBusConnection
1195 * Gets the capabilities negotiated with the remote peer
1197 * Returns: zero or more flags from the #GDBusCapabilityFlags enumeration
1201 GDBusCapabilityFlags
1202 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1204 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1206 /* do not use g_return_val_if_fail(), we want the memory barrier */
1207 if (!check_initialized (connection))
1208 return G_DBUS_CAPABILITY_FLAGS_NONE;
1210 return connection->capabilities;
1213 /* ---------------------------------------------------------------------------------------------------- */
1215 /* Called in a temporary thread without holding locks. */
1217 flush_in_thread_func (GSimpleAsyncResult *res,
1219 GCancellable *cancellable)
1224 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1227 g_simple_async_result_take_error (res, error);
1231 * g_dbus_connection_flush:
1232 * @connection: a #GDBusConnection
1233 * @cancellable: (allow-none): a #GCancellable or %NULL
1234 * @callback: (allow-none): a #GAsyncReadyCallback to call when the
1235 * request is satisfied or %NULL if you don't care about the result
1236 * @user_data: The data to pass to @callback
1238 * Asynchronously flushes @connection, that is, writes all queued
1239 * outgoing message to the transport and then flushes the transport
1240 * (using g_output_stream_flush_async()). This is useful in programs
1241 * that wants to emit a D-Bus signal and then exit immediately. Without
1242 * flushing the connection, there is no guaranteed that the message has
1243 * been sent to the networking buffers in the OS kernel.
1245 * This is an asynchronous method. When the operation is finished,
1246 * @callback will be invoked in the
1247 * [thread-default main context][g-main-context-push-thread-default]
1248 * of the thread you are calling this method from. You can
1249 * then call g_dbus_connection_flush_finish() to get the result of the
1250 * operation. See g_dbus_connection_flush_sync() for the synchronous
1256 g_dbus_connection_flush (GDBusConnection *connection,
1257 GCancellable *cancellable,
1258 GAsyncReadyCallback callback,
1261 GSimpleAsyncResult *simple;
1263 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1265 simple = g_simple_async_result_new (G_OBJECT (connection),
1268 g_dbus_connection_flush);
1269 g_simple_async_result_set_check_cancellable (simple, cancellable);
1270 g_simple_async_result_run_in_thread (simple,
1271 flush_in_thread_func,
1274 g_object_unref (simple);
1278 * g_dbus_connection_flush_finish:
1279 * @connection: a #GDBusConnection
1280 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1281 * to g_dbus_connection_flush()
1282 * @error: return location for error or %NULL
1284 * Finishes an operation started with g_dbus_connection_flush().
1286 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1291 g_dbus_connection_flush_finish (GDBusConnection *connection,
1295 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1300 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1301 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1302 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1304 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1306 if (g_simple_async_result_propagate_error (simple, error))
1316 * g_dbus_connection_flush_sync:
1317 * @connection: a #GDBusConnection
1318 * @cancellable: (allow-none): a #GCancellable or %NULL
1319 * @error: return location for error or %NULL
1321 * Synchronously flushes @connection. The calling thread is blocked
1322 * until this is done. See g_dbus_connection_flush() for the
1323 * asynchronous version of this method and more details about what it
1326 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1331 g_dbus_connection_flush_sync (GDBusConnection *connection,
1332 GCancellable *cancellable,
1337 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1338 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1342 /* This is only a best-effort attempt to see whether the connection is
1343 * closed, so it doesn't need the lock. If the connection closes just
1344 * after this check, but before scheduling the flush operation, the
1345 * result will be more or less the same as if the connection closed while
1346 * the flush operation was pending - it'll fail with either CLOSED or
1349 if (!check_unclosed (connection, 0, error))
1352 g_assert (connection->worker != NULL);
1354 ret = _g_dbus_worker_flush_sync (connection->worker,
1362 /* ---------------------------------------------------------------------------------------------------- */
1366 GDBusConnection *connection;
1368 gboolean remote_peer_vanished;
1372 emit_closed_data_free (EmitClosedData *data)
1374 g_object_unref (data->connection);
1375 if (data->error != NULL)
1376 g_error_free (data->error);
1380 /* Called in a user thread that has acquired the main context that was
1381 * thread-default when the object was constructed
1384 emit_closed_in_idle (gpointer user_data)
1386 EmitClosedData *data = user_data;
1389 g_object_notify (G_OBJECT (data->connection), "closed");
1390 g_signal_emit (data->connection,
1391 signals[CLOSED_SIGNAL],
1393 data->remote_peer_vanished,
1399 /* Can be called from any thread, must hold lock.
1400 * FLAG_CLOSED must already have been set.
1403 schedule_closed_unlocked (GDBusConnection *connection,
1404 gboolean remote_peer_vanished,
1407 GSource *idle_source;
1408 EmitClosedData *data;
1410 CONNECTION_ENSURE_LOCK (connection);
1412 data = g_new0 (EmitClosedData, 1);
1413 data->connection = g_object_ref (connection);
1414 data->remote_peer_vanished = remote_peer_vanished;
1415 data->error = error != NULL ? g_error_copy (error) : NULL;
1417 idle_source = g_idle_source_new ();
1418 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1419 g_source_set_callback (idle_source,
1420 emit_closed_in_idle,
1422 (GDestroyNotify) emit_closed_data_free);
1423 g_source_set_name (idle_source, "[gio] emit_closed_in_idle");
1424 g_source_attach (idle_source, connection->main_context_at_construction);
1425 g_source_unref (idle_source);
1428 /* ---------------------------------------------------------------------------------------------------- */
1431 * g_dbus_connection_close:
1432 * @connection: a #GDBusConnection
1433 * @cancellable: (allow-none): a #GCancellable or %NULL
1434 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request is
1435 * satisfied or %NULL if you don't care about the result
1436 * @user_data: The data to pass to @callback
1438 * Closes @connection. Note that this never causes the process to
1439 * exit (this might only happen if the other end of a shared message
1440 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1442 * Once the connection is closed, operations such as sending a message
1443 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1444 * will not automatically flush the connection so queued messages may
1445 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1447 * If @connection is already closed, this method fails with
1448 * %G_IO_ERROR_CLOSED.
1450 * When @connection has been closed, the #GDBusConnection::closed
1451 * signal is emitted in the
1452 * [thread-default main context][g-main-context-push-thread-default]
1453 * of the thread that @connection was constructed in.
1455 * This is an asynchronous method. When the operation is finished,
1456 * @callback will be invoked in the
1457 * [thread-default main context][g-main-context-push-thread-default]
1458 * of the thread you are calling this method from. You can
1459 * then call g_dbus_connection_close_finish() to get the result of the
1460 * operation. See g_dbus_connection_close_sync() for the synchronous
1466 g_dbus_connection_close (GDBusConnection *connection,
1467 GCancellable *cancellable,
1468 GAsyncReadyCallback callback,
1471 GSimpleAsyncResult *simple;
1473 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1475 /* do not use g_return_val_if_fail(), we want the memory barrier */
1476 if (!check_initialized (connection))
1479 g_assert (connection->worker != NULL);
1481 simple = g_simple_async_result_new (G_OBJECT (connection),
1484 g_dbus_connection_close);
1485 g_simple_async_result_set_check_cancellable (simple, cancellable);
1486 _g_dbus_worker_close (connection->worker, cancellable, simple);
1487 g_object_unref (simple);
1491 * g_dbus_connection_close_finish:
1492 * @connection: a #GDBusConnection
1493 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1494 * to g_dbus_connection_close()
1495 * @error: return location for error or %NULL
1497 * Finishes an operation started with g_dbus_connection_close().
1499 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1504 g_dbus_connection_close_finish (GDBusConnection *connection,
1508 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1513 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1514 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1515 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1517 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1519 if (g_simple_async_result_propagate_error (simple, error))
1530 GAsyncResult *result;
1533 /* Can be called by any thread, without the connection lock */
1535 sync_close_cb (GObject *source_object,
1539 SyncCloseData *data = user_data;
1541 data->result = g_object_ref (res);
1542 g_main_loop_quit (data->loop);
1546 * g_dbus_connection_close_sync:
1547 * @connection: a #GDBusConnection
1548 * @cancellable: (allow-none): a #GCancellable or %NULL
1549 * @error: return location for error or %NULL
1551 * Synchronously closees @connection. The calling thread is blocked
1552 * until this is done. See g_dbus_connection_close() for the
1553 * asynchronous version of this method and more details about what it
1556 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1561 g_dbus_connection_close_sync (GDBusConnection *connection,
1562 GCancellable *cancellable,
1567 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1568 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1572 if (check_unclosed (connection, 0, error))
1574 GMainContext *context;
1577 context = g_main_context_new ();
1578 g_main_context_push_thread_default (context);
1579 data.loop = g_main_loop_new (context, TRUE);
1582 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1583 g_main_loop_run (data.loop);
1584 ret = g_dbus_connection_close_finish (connection, data.result, error);
1586 g_object_unref (data.result);
1587 g_main_loop_unref (data.loop);
1588 g_main_context_pop_thread_default (context);
1589 g_main_context_unref (context);
1595 /* ---------------------------------------------------------------------------------------------------- */
1598 * g_dbus_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 (G_IS_KDBUS_CONNECTION (connection->stream))
1627 result = _g_kdbus_RequestName (connection, 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 (G_IS_KDBUS_CONNECTION (connection->stream))
1673 result = _g_kdbus_ReleaseName (connection, 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 (G_IS_KDBUS_CONNECTION (connection->stream))
1720 result = _g_kdbus_GetBusId (connection, 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 (G_IS_KDBUS_CONNECTION (connection->stream))
1764 result = _g_kdbus_GetListQueuedOwners (connection, 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 (G_IS_KDBUS_CONNECTION (connection->stream))
1781 result = _g_kdbus_GetListNames (connection, 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 (G_IS_KDBUS_CONNECTION (connection->stream))
1938 result = _g_kdbus_GetNameOwner (connection, 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 (G_IS_KDBUS_CONNECTION (connection->stream))
1991 result = _g_kdbus_GetConnectionUnixProcessID (connection, 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 (G_IS_KDBUS_CONNECTION (connection->stream))
2042 result = _g_kdbus_GetConnectionUnixUser (connection, 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,
2134 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
2135 serial_to_use = g_dbus_message_get_serial (message);
2137 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
2142 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
2145 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
2148 g_assert_not_reached ();
2153 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
2154 blob_size, serial_to_use, connection);
2155 g_printerr ("----\n");
2156 hexdump (blob, blob_size);
2157 g_printerr ("----\n");
2160 /* TODO: use connection->auth to encode the blob */
2162 if (out_serial != NULL)
2163 *out_serial = serial_to_use;
2165 /* store used serial for the current thread */
2166 /* TODO: watch the thread disposal and remove associated record
2168 * - see https://bugzilla.gnome.org/show_bug.cgi?id=676825#c7
2170 g_hash_table_replace (connection->map_thread_to_last_serial,
2172 GUINT_TO_POINTER (serial_to_use));
2174 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
2175 g_dbus_message_set_serial (message, serial_to_use);
2177 g_dbus_message_lock (message);
2178 _g_dbus_worker_send_message (connection->worker,
2182 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
2193 * g_dbus_connection_send_message:
2194 * @connection: a #GDBusConnection
2195 * @message: a #GDBusMessage
2196 * @flags: flags affecting how the message is sent
2197 * @out_serial: (out) (allow-none): return location for serial number assigned
2198 * to @message when sending it or %NULL
2199 * @error: Return location for error or %NULL
2201 * Asynchronously sends @message to the peer represented by @connection.
2203 * Unless @flags contain the
2204 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2205 * will be assigned by @connection and set on @message via
2206 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2207 * serial number used will be written to this location prior to
2208 * submitting the message to the underlying transport.
2210 * If @connection is closed then the operation will fail with
2211 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
2212 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2214 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2215 * for an example of how to use this low-level API to send and receive
2216 * UNIX file descriptors.
2218 * Note that @message must be unlocked, unless @flags contain the
2219 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2221 * Returns: %TRUE if the message was well-formed and queued for
2222 * transmission, %FALSE if @error is set
2227 g_dbus_connection_send_message (GDBusConnection *connection,
2228 GDBusMessage *message,
2229 GDBusSendMessageFlags flags,
2230 volatile guint32 *out_serial,
2235 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2236 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
2237 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
2238 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2240 CONNECTION_LOCK (connection);
2241 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
2242 CONNECTION_UNLOCK (connection);
2246 /* ---------------------------------------------------------------------------------------------------- */
2250 volatile gint ref_count;
2251 GDBusConnection *connection;
2253 GSimpleAsyncResult *simple;
2255 GMainContext *main_context;
2257 GCancellable *cancellable;
2259 gulong cancellable_handler_id;
2261 GSource *timeout_source;
2266 /* Can be called from any thread with or without lock held */
2267 static SendMessageData *
2268 send_message_data_ref (SendMessageData *data)
2270 g_atomic_int_inc (&data->ref_count);
2274 /* Can be called from any thread with or without lock held */
2276 send_message_data_unref (SendMessageData *data)
2278 if (g_atomic_int_dec_and_test (&data->ref_count))
2280 g_assert (data->timeout_source == NULL);
2281 g_assert (data->simple == NULL);
2282 g_assert (data->cancellable_handler_id == 0);
2283 g_object_unref (data->connection);
2284 if (data->cancellable != NULL)
2285 g_object_unref (data->cancellable);
2286 g_main_context_unref (data->main_context);
2291 /* ---------------------------------------------------------------------------------------------------- */
2293 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
2295 send_message_with_reply_deliver (SendMessageData *data, gboolean remove)
2297 CONNECTION_ENSURE_LOCK (data->connection);
2299 g_assert (!data->delivered);
2301 data->delivered = TRUE;
2303 g_simple_async_result_complete_in_idle (data->simple);
2304 g_object_unref (data->simple);
2305 data->simple = NULL;
2307 if (data->timeout_source != NULL)
2309 g_source_destroy (data->timeout_source);
2310 data->timeout_source = NULL;
2312 if (data->cancellable_handler_id > 0)
2314 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
2315 data->cancellable_handler_id = 0;
2320 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
2321 GUINT_TO_POINTER (data->serial)));
2324 send_message_data_unref (data);
2327 /* ---------------------------------------------------------------------------------------------------- */
2329 /* Can be called from any thread with lock held */
2331 send_message_data_deliver_reply_unlocked (SendMessageData *data,
2332 GDBusMessage *reply)
2334 if (data->delivered)
2337 g_simple_async_result_set_op_res_gpointer (data->simple,
2338 g_object_ref (reply),
2341 send_message_with_reply_deliver (data, TRUE);
2347 /* ---------------------------------------------------------------------------------------------------- */
2349 /* Called from a user thread, lock is not held */
2351 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
2353 SendMessageData *data = user_data;
2355 CONNECTION_LOCK (data->connection);
2356 if (data->delivered)
2359 g_simple_async_result_set_error (data->simple,
2361 G_IO_ERROR_CANCELLED,
2362 _("Operation was cancelled"));
2364 send_message_with_reply_deliver (data, TRUE);
2367 CONNECTION_UNLOCK (data->connection);
2371 /* Can be called from any thread with or without lock held */
2373 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
2376 SendMessageData *data = user_data;
2377 GSource *idle_source;
2379 /* postpone cancellation to idle handler since we may be called directly
2380 * via g_cancellable_connect() (e.g. holding lock)
2382 idle_source = g_idle_source_new ();
2383 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
2384 g_source_set_callback (idle_source,
2385 send_message_with_reply_cancelled_idle_cb,
2386 send_message_data_ref (data),
2387 (GDestroyNotify) send_message_data_unref);
2388 g_source_set_name (idle_source, "[gio] send_message_with_reply_cancelled_idle_cb");
2389 g_source_attach (idle_source, data->main_context);
2390 g_source_unref (idle_source);
2393 /* ---------------------------------------------------------------------------------------------------- */
2395 /* Called from a user thread, lock is not held */
2397 send_message_with_reply_timeout_cb (gpointer user_data)
2399 SendMessageData *data = user_data;
2401 CONNECTION_LOCK (data->connection);
2402 if (data->delivered)
2405 g_simple_async_result_set_error (data->simple,
2407 G_IO_ERROR_TIMED_OUT,
2408 _("Timeout was reached"));
2410 send_message_with_reply_deliver (data, TRUE);
2413 CONNECTION_UNLOCK (data->connection);
2418 /* ---------------------------------------------------------------------------------------------------- */
2420 /* Called from a user thread, connection's lock is held */
2422 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
2423 GDBusMessage *message,
2424 GDBusSendMessageFlags flags,
2426 volatile guint32 *out_serial,
2427 GCancellable *cancellable,
2428 GAsyncReadyCallback callback,
2431 GSimpleAsyncResult *simple;
2432 SendMessageData *data;
2434 volatile guint32 serial;
2438 if (out_serial == NULL)
2439 out_serial = &serial;
2441 if (timeout_msec == -1)
2442 timeout_msec = 25 * 1000;
2444 simple = g_simple_async_result_new (G_OBJECT (connection),
2447 g_dbus_connection_send_message_with_reply);
2448 g_simple_async_result_set_check_cancellable (simple, cancellable);
2450 if (g_cancellable_is_cancelled (cancellable))
2452 g_simple_async_result_set_error (simple,
2454 G_IO_ERROR_CANCELLED,
2455 _("Operation was cancelled"));
2456 g_simple_async_result_complete_in_idle (simple);
2457 g_object_unref (simple);
2462 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
2464 g_simple_async_result_take_error (simple, error);
2465 g_simple_async_result_complete_in_idle (simple);
2466 g_object_unref (simple);
2470 data = g_new0 (SendMessageData, 1);
2471 data->ref_count = 1;
2472 data->connection = g_object_ref (connection);
2473 data->simple = simple;
2474 data->serial = *out_serial;
2475 data->main_context = g_main_context_ref_thread_default ();
2477 if (cancellable != NULL)
2479 data->cancellable = g_object_ref (cancellable);
2480 data->cancellable_handler_id = g_cancellable_connect (cancellable,
2481 G_CALLBACK (send_message_with_reply_cancelled_cb),
2482 send_message_data_ref (data),
2483 (GDestroyNotify) send_message_data_unref);
2486 if (timeout_msec != G_MAXINT)
2488 data->timeout_source = g_timeout_source_new (timeout_msec);
2489 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
2490 g_source_set_callback (data->timeout_source,
2491 send_message_with_reply_timeout_cb,
2492 send_message_data_ref (data),
2493 (GDestroyNotify) send_message_data_unref);
2494 g_source_attach (data->timeout_source, data->main_context);
2495 g_source_unref (data->timeout_source);
2498 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
2499 GUINT_TO_POINTER (*out_serial),
2507 * g_dbus_connection_send_message_with_reply:
2508 * @connection: a #GDBusConnection
2509 * @message: a #GDBusMessage
2510 * @flags: flags affecting how the message is sent
2511 * @timeout_msec: the timeout in milliseconds, -1 to use the default
2512 * timeout or %G_MAXINT for no timeout
2513 * @out_serial: (out) (allow-none): return location for serial number assigned
2514 * to @message when sending it or %NULL
2515 * @cancellable: (allow-none): a #GCancellable or %NULL
2516 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request
2517 * is satisfied or %NULL if you don't care about the result
2518 * @user_data: The data to pass to @callback
2520 * Asynchronously sends @message to the peer represented by @connection.
2522 * Unless @flags contain the
2523 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2524 * will be assigned by @connection and set on @message via
2525 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2526 * serial number used will be written to this location prior to
2527 * submitting the message to the underlying transport.
2529 * If @connection is closed then the operation will fail with
2530 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2531 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2532 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2534 * This is an asynchronous method. When the operation is finished, @callback
2535 * will be invoked in the
2536 * [thread-default main context][g-main-context-push-thread-default]
2537 * of the thread you are calling this method from. You can then call
2538 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
2539 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
2541 * Note that @message must be unlocked, unless @flags contain the
2542 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2544 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2545 * for an example of how to use this low-level API to send and receive
2546 * UNIX file descriptors.
2551 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
2552 GDBusMessage *message,
2553 GDBusSendMessageFlags flags,
2555 volatile guint32 *out_serial,
2556 GCancellable *cancellable,
2557 GAsyncReadyCallback callback,
2560 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2561 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2562 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2563 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2565 CONNECTION_LOCK (connection);
2566 g_dbus_connection_send_message_with_reply_unlocked (connection,
2574 CONNECTION_UNLOCK (connection);
2578 * g_dbus_connection_send_message_with_reply_finish:
2579 * @connection: a #GDBusConnection
2580 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
2581 * g_dbus_connection_send_message_with_reply()
2582 * @error: teturn location for error or %NULL
2584 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2586 * Note that @error is only set if a local in-process error
2587 * occurred. That is to say that the returned #GDBusMessage object may
2588 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2589 * g_dbus_message_to_gerror() to transcode this to a #GError.
2591 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2592 * for an example of how to use this low-level API to send and receive
2593 * UNIX file descriptors.
2595 * Returns: (transfer full): a locked #GDBusMessage or %NULL if @error is set
2600 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2604 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2605 GDBusMessage *reply;
2607 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2608 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2612 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
2614 if (g_simple_async_result_propagate_error (simple, error))
2617 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
2623 /* ---------------------------------------------------------------------------------------------------- */
2628 GMainContext *context;
2630 } SendMessageSyncData;
2632 /* Called from a user thread, lock is not held */
2634 send_message_with_reply_sync_cb (GDBusConnection *connection,
2638 SendMessageSyncData *data = user_data;
2639 data->res = g_object_ref (res);
2640 g_main_loop_quit (data->loop);
2644 * g_dbus_connection_send_message_with_reply_sync:
2645 * @connection: a #GDBusConnection
2646 * @message: a #GDBusMessage
2647 * @flags: flags affecting how the message is sent.
2648 * @timeout_msec: the timeout in milliseconds, -1 to use the default
2649 * timeout or %G_MAXINT for no timeout
2650 * @out_serial: (out) (allow-none): return location for serial number
2651 * assigned to @message when sending it or %NULL
2652 * @cancellable: (allow-none): a #GCancellable or %NULL
2653 * @error: return location for error or %NULL
2655 * Synchronously sends @message to the peer represented by @connection
2656 * and blocks the calling thread until a reply is received or the
2657 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2658 * for the asynchronous version of this method.
2660 * Unless @flags contain the
2661 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2662 * will be assigned by @connection and set on @message via
2663 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2664 * serial number used will be written to this location prior to
2665 * submitting the message to the underlying transport.
2667 * If @connection is closed then the operation will fail with
2668 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2669 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2670 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2672 * Note that @error is only set if a local in-process error
2673 * occurred. That is to say that the returned #GDBusMessage object may
2674 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2675 * g_dbus_message_to_gerror() to transcode this to a #GError.
2677 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2678 * for an example of how to use this low-level API to send and receive
2679 * UNIX file descriptors.
2681 * Note that @message must be unlocked, unless @flags contain the
2682 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2684 * Returns: (transfer full): a locked #GDBusMessage that is the reply
2685 * to @message or %NULL if @error is set
2690 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2691 GDBusMessage *message,
2692 GDBusSendMessageFlags flags,
2694 volatile guint32 *out_serial,
2695 GCancellable *cancellable,
2698 SendMessageSyncData *data;
2699 GDBusMessage *reply;
2701 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2702 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2703 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2704 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2705 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2707 data = g_new0 (SendMessageSyncData, 1);
2708 data->context = g_main_context_new ();
2709 data->loop = g_main_loop_new (data->context, FALSE);
2711 g_main_context_push_thread_default (data->context);
2713 g_dbus_connection_send_message_with_reply (connection,
2719 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2721 g_main_loop_run (data->loop);
2722 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2726 g_main_context_pop_thread_default (data->context);
2728 g_main_context_unref (data->context);
2729 g_main_loop_unref (data->loop);
2730 g_object_unref (data->res);
2736 /* ---------------------------------------------------------------------------------------------------- */
2740 GDBusMessageFilterFunction func;
2747 GDBusMessageFilterFunction filter_function;
2749 GDestroyNotify user_data_free_func;
2752 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2754 on_worker_message_received (GDBusWorker *worker,
2755 GDBusMessage *message,
2758 GDBusConnection *connection;
2759 FilterCallback *filters;
2764 G_LOCK (message_bus_lock);
2765 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2768 G_UNLOCK (message_bus_lock);
2771 connection = G_DBUS_CONNECTION (user_data);
2772 g_object_ref (connection);
2773 G_UNLOCK (message_bus_lock);
2775 //g_debug ("in on_worker_message_received");
2777 g_object_ref (message);
2778 g_dbus_message_lock (message);
2780 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2782 /* First collect the set of callback functions */
2783 CONNECTION_LOCK (connection);
2784 num_filters = connection->filters->len;
2785 filters = g_new0 (FilterCallback, num_filters);
2786 for (n = 0; n < num_filters; n++)
2788 FilterData *data = connection->filters->pdata[n];
2789 filters[n].func = data->filter_function;
2790 filters[n].user_data = data->user_data;
2792 CONNECTION_UNLOCK (connection);
2794 /* then call the filters in order (without holding the lock) */
2795 for (n = 0; n < num_filters; n++)
2797 message = filters[n].func (connection,
2800 filters[n].user_data);
2801 if (message == NULL)
2803 g_dbus_message_lock (message);
2806 /* Standard dispatch unless the filter ate the message - no need to
2807 * do anything if the message was altered
2809 if (message != NULL)
2811 GDBusMessageType message_type;
2813 message_type = g_dbus_message_get_message_type (message);
2814 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2816 guint32 reply_serial;
2817 SendMessageData *send_message_data;
2819 reply_serial = g_dbus_message_get_reply_serial (message);
2820 CONNECTION_LOCK (connection);
2821 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2822 GUINT_TO_POINTER (reply_serial));
2823 if (send_message_data != NULL)
2825 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2826 send_message_data_deliver_reply_unlocked (send_message_data, message);
2830 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2832 CONNECTION_UNLOCK (connection);
2834 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2836 CONNECTION_LOCK (connection);
2837 distribute_signals (connection, message);
2838 CONNECTION_UNLOCK (connection);
2840 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2842 CONNECTION_LOCK (connection);
2843 distribute_method_call (connection, message);
2844 CONNECTION_UNLOCK (connection);
2848 if (message != NULL)
2849 g_object_unref (message);
2850 g_object_unref (connection);
2854 /* Called in GDBusWorker's thread, lock is not held */
2855 static GDBusMessage *
2856 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2857 GDBusMessage *message,
2860 GDBusConnection *connection;
2861 FilterCallback *filters;
2866 G_LOCK (message_bus_lock);
2867 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2870 G_UNLOCK (message_bus_lock);
2873 connection = G_DBUS_CONNECTION (user_data);
2874 g_object_ref (connection);
2875 G_UNLOCK (message_bus_lock);
2877 //g_debug ("in on_worker_message_about_to_be_sent");
2879 /* First collect the set of callback functions */
2880 CONNECTION_LOCK (connection);
2881 num_filters = connection->filters->len;
2882 filters = g_new0 (FilterCallback, num_filters);
2883 for (n = 0; n < num_filters; n++)
2885 FilterData *data = connection->filters->pdata[n];
2886 filters[n].func = data->filter_function;
2887 filters[n].user_data = data->user_data;
2889 CONNECTION_UNLOCK (connection);
2891 /* then call the filters in order (without holding the lock) */
2892 for (n = 0; n < num_filters; n++)
2894 g_dbus_message_lock (message);
2895 message = filters[n].func (connection,
2898 filters[n].user_data);
2899 if (message == NULL)
2903 g_object_unref (connection);
2909 /* called with connection lock held, in GDBusWorker thread */
2911 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2913 SendMessageData *data = value;
2915 if (data->delivered)
2918 g_simple_async_result_set_error (data->simple,
2921 _("The connection is closed"));
2923 /* Ask send_message_with_reply_deliver not to remove the element from the
2924 * hash table - we're in the middle of a foreach; that would be unsafe.
2925 * Instead, return TRUE from this function so that it gets removed safely.
2927 send_message_with_reply_deliver (data, FALSE);
2931 /* Called in GDBusWorker's thread - we must not block - without lock held */
2933 on_worker_closed (GDBusWorker *worker,
2934 gboolean remote_peer_vanished,
2938 GDBusConnection *connection;
2940 guint old_atomic_flags;
2942 G_LOCK (message_bus_lock);
2943 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2946 G_UNLOCK (message_bus_lock);
2949 connection = G_DBUS_CONNECTION (user_data);
2950 g_object_ref (connection);
2951 G_UNLOCK (message_bus_lock);
2953 //g_debug ("in on_worker_closed: %s", error->message);
2955 CONNECTION_LOCK (connection);
2956 /* Even though this is atomic, we do it inside the lock to avoid breaking
2957 * assumptions in remove_match_rule(). We'd need the lock in a moment
2958 * anyway, so, no loss.
2960 old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
2962 if (!(old_atomic_flags & FLAG_CLOSED))
2964 g_hash_table_foreach_remove (connection->map_method_serial_to_send_message_data, cancel_method_on_close, NULL);
2965 schedule_closed_unlocked (connection, remote_peer_vanished, error);
2967 CONNECTION_UNLOCK (connection);
2969 g_object_unref (connection);
2972 /* ---------------------------------------------------------------------------------------------------- */
2974 /* Determines the biggest set of capabilities we can support on this
2977 * Called with the init_lock held.
2979 static GDBusCapabilityFlags
2980 get_offered_capabilities_max (GDBusConnection *connection)
2982 GDBusCapabilityFlags ret;
2983 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2985 if (G_IS_UNIX_CONNECTION (connection->stream))
2986 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2991 /* Called in a user thread, lock is not held */
2993 initable_init (GInitable *initable,
2994 GCancellable *cancellable,
2997 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
3000 /* This method needs to be idempotent to work with the singleton
3001 * pattern. See the docs for g_initable_init(). We implement this by
3004 * Unfortunately we can't use the main lock since the on_worker_*()
3005 * callbacks above needs the lock during initialization (for message
3006 * bus connections we do a synchronous Hello() call on the bus).
3008 g_mutex_lock (&connection->init_lock);
3012 /* Make this a no-op if we're already initialized (successfully or
3015 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
3017 ret = (connection->initialization_error == NULL);
3021 /* Because of init_lock, we can't get here twice in different threads */
3022 g_assert (connection->initialization_error == NULL);
3024 /* The user can pass multiple (but mutally exclusive) construct
3027 * - stream (of type GIOStream)
3028 * - address (of type gchar*)
3030 * At the end of the day we end up with a non-NULL GIOStream
3031 * object in connection->stream.
3033 if (connection->address != NULL)
3035 g_assert (connection->stream == NULL);
3037 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
3038 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
3040 g_set_error_literal (&connection->initialization_error,
3042 G_IO_ERROR_INVALID_ARGUMENT,
3043 _("Unsupported flags encountered when constructing a client-side connection"));
3047 connection->stream = g_dbus_address_get_stream_sync (connection->address,
3048 NULL, /* TODO: out_guid */
3050 &connection->initialization_error);
3051 if (connection->stream == NULL)
3054 else if (connection->stream != NULL)
3060 g_assert_not_reached ();
3063 /* [KDBUS] Skip authentication process for kdbus transport */
3064 if (G_IS_KDBUS_CONNECTION (connection->stream))
3069 /* Authenticate the connection */
3070 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
3072 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
3073 g_assert (connection->guid != NULL);
3074 connection->auth = _g_dbus_auth_new (connection->stream);
3075 if (!_g_dbus_auth_run_server (connection->auth,
3076 connection->authentication_observer,
3078 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
3079 get_offered_capabilities_max (connection),
3080 &connection->capabilities,
3081 &connection->credentials,
3083 &connection->initialization_error))
3086 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
3088 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
3089 g_assert (connection->guid == NULL);
3090 connection->auth = _g_dbus_auth_new (connection->stream);
3091 connection->guid = _g_dbus_auth_run_client (connection->auth,
3092 connection->authentication_observer,
3093 get_offered_capabilities_max (connection),
3094 &connection->capabilities,
3096 &connection->initialization_error);
3097 if (connection->guid == NULL)
3101 if (connection->authentication_observer != NULL)
3103 g_object_unref (connection->authentication_observer);
3104 connection->authentication_observer = NULL;
3109 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
3111 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
3114 /* We want all IO operations to be non-blocking since they happen in
3115 * the worker thread which is shared by _all_ connections.
3117 if (G_IS_SOCKET_CONNECTION (connection->stream))
3119 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
3123 G_LOCK (message_bus_lock);
3124 if (alive_connections == NULL)
3125 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
3126 g_hash_table_insert (alive_connections, connection, connection);
3127 G_UNLOCK (message_bus_lock);
3129 connection->worker = _g_dbus_worker_new (connection->stream,
3130 connection->capabilities,
3131 ((connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) != 0),
3132 on_worker_message_received,
3133 on_worker_message_about_to_be_sent,
3137 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
3138 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3140 GVariant *hello_result;
3142 /* we could lift this restriction by adding code in gdbusprivate.c */
3143 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
3145 g_set_error_literal (&connection->initialization_error,
3148 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
3152 if (G_IS_KDBUS_CONNECTION (connection->stream))
3154 hello_result = _g_kdbus_Hello (connection->stream, &connection->initialization_error);
3158 hello_result = g_dbus_connection_call_sync (connection,
3159 "org.freedesktop.DBus", /* name */
3160 "/org/freedesktop/DBus", /* path */
3161 "org.freedesktop.DBus", /* interface */
3163 NULL, /* parameters */
3164 G_VARIANT_TYPE ("(s)"),
3165 CALL_FLAGS_INITIALIZING,
3167 NULL, /* TODO: cancellable */
3168 &connection->initialization_error);
3171 if (hello_result == NULL)
3174 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
3175 g_variant_unref (hello_result);
3176 //g_debug ("unique name is '%s'", connection->bus_unique_name);
3183 g_assert (connection->initialization_error != NULL);
3184 g_propagate_error (error, g_error_copy (connection->initialization_error));
3187 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
3188 g_mutex_unlock (&connection->init_lock);
3194 initable_iface_init (GInitableIface *initable_iface)
3196 initable_iface->init = initable_init;
3199 /* ---------------------------------------------------------------------------------------------------- */
3202 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
3207 /* ---------------------------------------------------------------------------------------------------- */
3210 * g_dbus_connection_new:
3211 * @stream: a #GIOStream
3212 * @guid: (allow-none): the GUID to use if a authenticating as a server or %NULL
3213 * @flags: flags describing how to make the connection
3214 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3215 * @cancellable: (allow-none): a #GCancellable or %NULL
3216 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
3217 * @user_data: the data to pass to @callback
3219 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
3220 * with the end represented by @stream.
3222 * If @stream is a #GSocketConnection, then the corresponding #GSocket
3223 * will be put into non-blocking mode.
3225 * The D-Bus connection will interact with @stream from a worker thread.
3226 * As a result, the caller should not interact with @stream after this
3227 * method has been called, except by calling g_object_unref() on it.
3229 * If @observer is not %NULL it may be used to control the
3230 * authentication process.
3232 * When the operation is finished, @callback will be invoked. You can
3233 * then call g_dbus_connection_new_finish() to get the result of the
3236 * This is a asynchronous failable constructor. See
3237 * g_dbus_connection_new_sync() for the synchronous
3243 g_dbus_connection_new (GIOStream *stream,
3245 GDBusConnectionFlags flags,
3246 GDBusAuthObserver *observer,
3247 GCancellable *cancellable,
3248 GAsyncReadyCallback callback,
3251 g_return_if_fail (G_IS_IO_STREAM (stream));
3252 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
3260 "authentication-observer", observer,
3265 * g_dbus_connection_new_finish:
3266 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback
3267 * passed to g_dbus_connection_new().
3268 * @error: return location for error or %NULL
3270 * Finishes an operation started with g_dbus_connection_new().
3272 * Returns: a #GDBusConnection or %NULL if @error is set. Free
3273 * with g_object_unref().
3278 g_dbus_connection_new_finish (GAsyncResult *res,
3282 GObject *source_object;
3284 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
3285 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3287 source_object = g_async_result_get_source_object (res);
3288 g_assert (source_object != NULL);
3289 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
3292 g_object_unref (source_object);
3294 return G_DBUS_CONNECTION (object);
3300 * g_dbus_connection_new_sync:
3301 * @stream: a #GIOStream
3302 * @guid: (allow-none): the GUID to use if a authenticating as a server or %NULL
3303 * @flags: flags describing how to make the connection
3304 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3305 * @cancellable: (allow-none): a #GCancellable or %NULL
3306 * @error: return location for error or %NULL
3308 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
3309 * with the end represented by @stream.
3311 * If @stream is a #GSocketConnection, then the corresponding #GSocket
3312 * will be put into non-blocking mode.
3314 * The D-Bus connection will interact with @stream from a worker thread.
3315 * As a result, the caller should not interact with @stream after this
3316 * method has been called, except by calling g_object_unref() on it.
3318 * If @observer is not %NULL it may be used to control the
3319 * authentication process.
3321 * This is a synchronous failable constructor. See
3322 * g_dbus_connection_new() for the asynchronous version.
3324 * Returns: a #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
3329 g_dbus_connection_new_sync (GIOStream *stream,
3331 GDBusConnectionFlags flags,
3332 GDBusAuthObserver *observer,
3333 GCancellable *cancellable,
3336 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
3337 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3338 return g_initable_new (G_TYPE_DBUS_CONNECTION,
3344 "authentication-observer", observer,
3348 /* ---------------------------------------------------------------------------------------------------- */
3351 * g_dbus_connection_new_for_address:
3352 * @address: a D-Bus address
3353 * @flags: flags describing how to make the connection
3354 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3355 * @cancellable: (allow-none): a #GCancellable or %NULL
3356 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
3357 * @user_data: the data to pass to @callback
3359 * Asynchronously connects and sets up a D-Bus client connection for
3360 * exchanging D-Bus messages with an endpoint specified by @address
3361 * which must be in the D-Bus address format.
3363 * This constructor can only be used to initiate client-side
3364 * connections - use g_dbus_connection_new() if you need to act as the
3365 * server. In particular, @flags cannot contain the
3366 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
3367 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
3369 * When the operation is finished, @callback will be invoked. You can
3370 * then call g_dbus_connection_new_finish() to get the result of the
3373 * If @observer is not %NULL it may be used to control the
3374 * authentication process.
3376 * This is a asynchronous failable constructor. See
3377 * g_dbus_connection_new_for_address_sync() for the synchronous
3383 g_dbus_connection_new_for_address (const gchar *address,
3384 GDBusConnectionFlags flags,
3385 GDBusAuthObserver *observer,
3386 GCancellable *cancellable,
3387 GAsyncReadyCallback callback,
3390 g_return_if_fail (address != NULL);
3391 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
3398 "authentication-observer", observer,
3403 * g_dbus_connection_new_for_address_finish:
3404 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
3405 * to g_dbus_connection_new()
3406 * @error: return location for error or %NULL
3408 * Finishes an operation started with g_dbus_connection_new_for_address().
3410 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
3416 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
3420 GObject *source_object;
3422 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
3423 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3425 source_object = g_async_result_get_source_object (res);
3426 g_assert (source_object != NULL);
3427 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
3430 g_object_unref (source_object);
3432 return G_DBUS_CONNECTION (object);
3438 * g_dbus_connection_new_for_address_sync:
3439 * @address: a D-Bus address
3440 * @flags: flags describing how to make the connection
3441 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3442 * @cancellable: (allow-none): a #GCancellable or %NULL
3443 * @error: return location for error or %NULL
3445 * Synchronously connects and sets up a D-Bus client connection for
3446 * exchanging D-Bus messages with an endpoint specified by @address
3447 * which must be in the D-Bus address format.
3449 * This constructor can only be used to initiate client-side
3450 * connections - use g_dbus_connection_new_sync() if you need to act
3451 * as the server. In particular, @flags cannot contain the
3452 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
3453 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
3455 * This is a synchronous failable constructor. See
3456 * g_dbus_connection_new_for_address() for the asynchronous version.
3458 * If @observer is not %NULL it may be used to control the
3459 * authentication process.
3461 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
3467 g_dbus_connection_new_for_address_sync (const gchar *address,
3468 GDBusConnectionFlags flags,
3469 GDBusAuthObserver *observer,
3470 GCancellable *cancellable,
3473 g_return_val_if_fail (address != NULL, NULL);
3474 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3475 return g_initable_new (G_TYPE_DBUS_CONNECTION,
3480 "authentication-observer", observer,
3484 /* ---------------------------------------------------------------------------------------------------- */
3487 * g_dbus_connection_set_exit_on_close:
3488 * @connection: a #GDBusConnection
3489 * @exit_on_close: whether the process should be terminated
3490 * when @connection is closed by the remote peer
3492 * Sets whether the process should be terminated when @connection is
3493 * closed by the remote peer. See #GDBusConnection:exit-on-close for
3496 * Note that this function should be used with care. Most modern UNIX
3497 * desktops tie the notion of a user session the session bus, and expect
3498 * all of a users applications to quit when their bus connection goes away.
3499 * If you are setting @exit_on_close to %FALSE for the shared session
3500 * bus connection, you should make sure that your application exits
3501 * when the user session ends.
3506 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
3507 gboolean exit_on_close)
3509 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3512 g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
3514 g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
3519 * g_dbus_connection_get_exit_on_close:
3520 * @connection: a #GDBusConnection
3522 * Gets whether the process is terminated when @connection is
3523 * closed by the remote peer. See
3524 * #GDBusConnection:exit-on-close for more details.
3526 * Returns: whether the process is terminated when @connection is
3527 * closed by the remote peer
3532 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
3534 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3536 if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
3543 * g_dbus_connection_get_guid:
3544 * @connection: a #GDBusConnection
3546 * The GUID of the peer performing the role of server when
3547 * authenticating. See #GDBusConnection:guid for more details.
3549 * Returns: The GUID. Do not free this string, it is owned by
3555 g_dbus_connection_get_guid (GDBusConnection *connection)
3557 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3558 return connection->guid;
3562 * g_dbus_connection_get_unique_name:
3563 * @connection: a #GDBusConnection
3565 * Gets the unique name of @connection as assigned by the message
3566 * bus. This can also be used to figure out if @connection is a
3567 * message bus connection.
3569 * Returns: the unique name or %NULL if @connection is not a message
3570 * bus connection. Do not free this string, it is owned by
3576 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3578 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3580 /* do not use g_return_val_if_fail(), we want the memory barrier */
3581 if (!check_initialized (connection))
3584 return connection->bus_unique_name;
3588 * g_dbus_connection_get_peer_credentials:
3589 * @connection: a #GDBusConnection
3591 * Gets the credentials of the authenticated peer. This will always
3592 * return %NULL unless @connection acted as a server
3593 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3594 * when set up and the client passed credentials as part of the
3595 * authentication process.
3597 * In a message bus setup, the message bus is always the server and
3598 * each application is a client. So this method will always return
3599 * %NULL for message bus clients.
3601 * Returns: (transfer none): a #GCredentials or %NULL if not available.
3602 * Do not free this object, it is owned by @connection.
3607 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3609 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3611 /* do not use g_return_val_if_fail(), we want the memory barrier */
3612 if (!check_initialized (connection))
3615 return connection->credentials;
3618 /* ---------------------------------------------------------------------------------------------------- */
3620 static guint _global_filter_id = 1;
3623 * g_dbus_connection_add_filter:
3624 * @connection: a #GDBusConnection
3625 * @filter_function: a filter function
3626 * @user_data: user data to pass to @filter_function
3627 * @user_data_free_func: function to free @user_data with when filter
3628 * is removed or %NULL
3630 * Adds a message filter. Filters are handlers that are run on all
3631 * incoming and outgoing messages, prior to standard dispatch. Filters
3632 * are run in the order that they were added. The same handler can be
3633 * added as a filter more than once, in which case it will be run more
3634 * than once. Filters added during a filter callback won't be run on
3635 * the message being processed. Filter functions are allowed to modify
3636 * and even drop messages.
3638 * Note that filters are run in a dedicated message handling thread so
3639 * they can't block and, generally, can't do anything but signal a
3640 * worker thread. Also note that filters are rarely needed - use API
3641 * such as g_dbus_connection_send_message_with_reply(),
3642 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3644 * If a filter consumes an incoming message the message is not
3645 * dispatched anywhere else - not even the standard dispatch machinery
3646 * (that API such as g_dbus_connection_signal_subscribe() and
3647 * g_dbus_connection_send_message_with_reply() relies on) will see the
3648 * message. Similary, if a filter consumes an outgoing message, the
3649 * message will not be sent to the other peer.
3651 * Returns: a filter identifier that can be used with
3652 * g_dbus_connection_remove_filter()
3657 g_dbus_connection_add_filter (GDBusConnection *connection,
3658 GDBusMessageFilterFunction filter_function,
3660 GDestroyNotify user_data_free_func)
3664 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3665 g_return_val_if_fail (filter_function != NULL, 0);
3666 g_return_val_if_fail (check_initialized (connection), 0);
3668 CONNECTION_LOCK (connection);
3669 data = g_new0 (FilterData, 1);
3670 data->id = _global_filter_id++; /* TODO: overflow etc. */
3671 data->filter_function = filter_function;
3672 data->user_data = user_data;
3673 data->user_data_free_func = user_data_free_func;
3674 g_ptr_array_add (connection->filters, data);
3675 CONNECTION_UNLOCK (connection);
3680 /* only called from finalize(), removes all filters */
3682 purge_all_filters (GDBusConnection *connection)
3685 for (n = 0; n < connection->filters->len; n++)
3687 FilterData *data = connection->filters->pdata[n];
3688 if (data->user_data_free_func != NULL)
3689 data->user_data_free_func (data->user_data);
3695 * g_dbus_connection_remove_filter:
3696 * @connection: a #GDBusConnection
3697 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3704 g_dbus_connection_remove_filter (GDBusConnection *connection,
3708 FilterData *to_destroy;
3710 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3711 g_return_if_fail (check_initialized (connection));
3713 CONNECTION_LOCK (connection);
3715 for (n = 0; n < connection->filters->len; n++)
3717 FilterData *data = connection->filters->pdata[n];
3718 if (data->id == filter_id)
3720 g_ptr_array_remove_index (connection->filters, n);
3725 CONNECTION_UNLOCK (connection);
3727 /* do free without holding lock */
3728 if (to_destroy != NULL)
3730 if (to_destroy->user_data_free_func != NULL)
3731 to_destroy->user_data_free_func (to_destroy->user_data);
3732 g_free (to_destroy);
3736 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3740 /* ---------------------------------------------------------------------------------------------------- */
3746 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3747 gchar *interface_name;
3751 GDBusSignalFlags flags;
3752 GArray *subscribers;
3757 GDBusSignalCallback callback;
3759 GDestroyNotify user_data_free_func;
3761 GMainContext *context;
3765 signal_data_free (SignalData *signal_data)
3767 g_free (signal_data->rule);
3768 g_free (signal_data->sender);
3769 g_free (signal_data->sender_unique_name);
3770 g_free (signal_data->interface_name);
3771 g_free (signal_data->member);
3772 g_free (signal_data->object_path);
3773 g_free (signal_data->arg0);
3774 g_array_free (signal_data->subscribers, TRUE);
3775 g_free (signal_data);
3779 args_to_rule (const gchar *sender,
3780 const gchar *interface_name,
3781 const gchar *member,
3782 const gchar *object_path,
3784 GDBusSignalFlags flags)
3788 rule = g_string_new ("type='signal'");
3789 if (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE)
3790 g_string_prepend_c (rule, '-');
3792 g_string_append_printf (rule, ",sender='%s'", sender);
3793 if (interface_name != NULL)
3794 g_string_append_printf (rule, ",interface='%s'", interface_name);
3796 g_string_append_printf (rule, ",member='%s'", member);
3797 if (object_path != NULL)
3798 g_string_append_printf (rule, ",path='%s'", object_path);
3802 if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3803 g_string_append_printf (rule, ",arg0path='%s'", arg0);
3804 else if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3805 g_string_append_printf (rule, ",arg0namespace='%s'", arg0);
3807 g_string_append_printf (rule, ",arg0='%s'", arg0);
3810 return g_string_free (rule, FALSE);
3813 static guint _global_subscriber_id = 1;
3814 static guint _global_registration_id = 1;
3815 static guint _global_subtree_registration_id = 1;
3817 /* ---------------------------------------------------------------------------------------------------- */
3819 /* Called in a user thread, lock is held */
3821 add_match_rule (GDBusConnection *connection,
3822 const gchar *match_rule)
3825 GDBusMessage *message;
3827 if (match_rule[0] == '-')
3830 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3831 "/org/freedesktop/DBus", /* path */
3832 "org.freedesktop.DBus", /* interface */
3834 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3836 if (!g_dbus_connection_send_message_unlocked (connection,
3838 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3842 g_critical ("Error while sending AddMatch() message: %s", error->message);
3843 g_error_free (error);
3845 g_object_unref (message);
3848 /* ---------------------------------------------------------------------------------------------------- */
3850 /* Called in a user thread, lock is held */
3852 remove_match_rule (GDBusConnection *connection,
3853 const gchar *match_rule)
3856 GDBusMessage *message;
3858 if (match_rule[0] == '-')
3861 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3862 "/org/freedesktop/DBus", /* path */
3863 "org.freedesktop.DBus", /* interface */
3865 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3868 if (!g_dbus_connection_send_message_unlocked (connection,
3870 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3874 /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
3875 * critical; but we're holding the lock, and our caller checked whether
3876 * we were already closed, so we can't get that error.
3878 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3879 g_error_free (error);
3881 g_object_unref (message);
3884 /* ---------------------------------------------------------------------------------------------------- */
3887 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3889 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3890 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3891 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3892 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3893 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3896 /* ---------------------------------------------------------------------------------------------------- */
3899 * g_dbus_connection_signal_subscribe:
3900 * @connection: a #GDBusConnection
3901 * @sender: (allow-none): sender name to match on (unique or well-known name)
3902 * or %NULL to listen from all senders
3903 * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3904 * match on all interfaces
3905 * @member: (allow-none): D-Bus signal name to match on or %NULL to match on
3907 * @object_path: (allow-none): object path to match on or %NULL to match on
3909 * @arg0: (allow-none): contents of first string argument to match on or %NULL
3910 * to match on all kinds of arguments
3911 * @flags: flags describing how to subscribe to the signal (currently unused)
3912 * @callback: callback to invoke when there is a signal matching the requested data
3913 * @user_data: user data to pass to @callback
3914 * @user_data_free_func: (allow-none): function to free @user_data with when
3915 * subscription is removed or %NULL
3917 * Subscribes to signals on @connection and invokes @callback with a whenever
3918 * the signal is received. Note that @callback will be invoked in the
3919 * [thread-default main context][g-main-context-push-thread-default]
3920 * of the thread you are calling this method from.
3922 * If @connection is not a message bus connection, @sender must be
3925 * If @sender is a well-known name note that @callback is invoked with
3926 * the unique name for the owner of @sender, not the well-known name
3927 * as one would expect. This is because the message bus rewrites the
3928 * name. As such, to avoid certain race conditions, users should be
3929 * tracking the name owner of the well-known name and use that when
3930 * processing the received signal.
3932 * If one of %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE or
3933 * %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH are given, @arg0 is
3934 * interpreted as part of a namespace or path. The first argument
3935 * of a signal is matched against that part as specified by D-Bus.
3937 * Returns: a subscription identifier that can be used with g_dbus_connection_signal_unsubscribe()
3942 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3943 const gchar *sender,
3944 const gchar *interface_name,
3945 const gchar *member,
3946 const gchar *object_path,
3948 GDBusSignalFlags flags,
3949 GDBusSignalCallback callback,
3951 GDestroyNotify user_data_free_func)
3954 SignalData *signal_data;
3955 SignalSubscriber subscriber;
3956 GPtrArray *signal_data_array;
3957 const gchar *sender_unique_name;
3959 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3960 * an OOM condition. We might want to change that but that would involve making
3961 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3962 * handle that. And there's really no sensible way of handling this short of retrying
3963 * to add the match rule... and then there's the little thing that, hey, maybe there's
3964 * a reason the bus in an OOM condition.
3966 * Doable, but not really sure it's worth it...
3969 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3970 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3971 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3972 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3973 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3974 g_return_val_if_fail (callback != NULL, 0);
3975 g_return_val_if_fail (check_initialized (connection), 0);
3976 g_return_val_if_fail (!((flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH) && (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)), 0);
3977 g_return_val_if_fail (!(arg0 == NULL && (flags & (G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH | G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE))), 0);
3979 CONNECTION_LOCK (connection);
3981 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3982 * with a '-' character to prefix the rule (which will otherwise be
3985 * This allows us to hash the rule and do our lifecycle tracking in
3986 * the usual way, but the '-' prevents the match rule from ever
3987 * actually being send to the bus (either for add or remove).
3989 rule = args_to_rule (sender, interface_name, member, object_path, arg0, flags);
3991 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3992 sender_unique_name = sender;
3994 sender_unique_name = "";
3996 subscriber.callback = callback;
3997 subscriber.user_data = user_data;
3998 subscriber.user_data_free_func = user_data_free_func;
3999 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
4000 subscriber.context = g_main_context_ref_thread_default ();
4002 /* see if we've already have this rule */
4003 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
4004 if (signal_data != NULL)
4006 g_array_append_val (signal_data->subscribers, subscriber);
4011 signal_data = g_new0 (SignalData, 1);
4012 signal_data->rule = rule;
4013 signal_data->sender = g_strdup (sender);
4014 signal_data->sender_unique_name = g_strdup (sender_unique_name);
4015 signal_data->interface_name = g_strdup (interface_name);
4016 signal_data->member = g_strdup (member);
4017 signal_data->object_path = g_strdup (object_path);
4018 signal_data->arg0 = g_strdup (arg0);
4019 signal_data->flags = flags;
4020 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
4021 g_array_append_val (signal_data->subscribers, subscriber);
4023 g_hash_table_insert (connection->map_rule_to_signal_data,
4027 /* Add the match rule to the bus...
4029 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
4030 * always send such messages to us.
4032 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
4034 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
4035 add_match_rule (connection, signal_data->rule);
4038 if (G_IS_KDBUS_CONNECTION (connection->stream))
4040 if (g_strcmp0 (signal_data->member, "NameAcquired") == 0)
4041 _g_kdbus_subscribe_name_acquired (connection, arg0);
4042 else if (g_strcmp0 (signal_data->member, "NameLost") == 0)
4043 _g_kdbus_subscribe_name_lost (connection, arg0);
4048 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
4049 signal_data->sender_unique_name);
4050 if (signal_data_array == NULL)
4052 signal_data_array = g_ptr_array_new ();
4053 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
4054 g_strdup (signal_data->sender_unique_name),
4057 g_ptr_array_add (signal_data_array, signal_data);
4060 g_hash_table_insert (connection->map_id_to_signal_data,
4061 GUINT_TO_POINTER (subscriber.id),
4064 CONNECTION_UNLOCK (connection);
4066 return subscriber.id;
4069 /* ---------------------------------------------------------------------------------------------------- */
4071 /* called in any thread */
4072 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
4074 unsubscribe_id_internal (GDBusConnection *connection,
4075 guint subscription_id,
4076 GArray *out_removed_subscribers)
4078 SignalData *signal_data;
4079 GPtrArray *signal_data_array;
4082 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
4083 GUINT_TO_POINTER (subscription_id));
4084 if (signal_data == NULL)
4086 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
4090 for (n = 0; n < signal_data->subscribers->len; n++)
4092 SignalSubscriber *subscriber;
4094 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
4095 if (subscriber->id != subscription_id)
4098 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
4099 GUINT_TO_POINTER (subscription_id)));
4100 g_array_append_val (out_removed_subscribers, *subscriber);
4101 g_array_remove_index (signal_data->subscribers, n);
4103 if (signal_data->subscribers->len == 0)
4105 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
4107 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
4108 signal_data->sender_unique_name);
4109 g_warn_if_fail (signal_data_array != NULL);
4110 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
4112 if (signal_data_array->len == 0)
4114 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
4115 signal_data->sender_unique_name));
4118 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
4119 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
4120 !is_signal_data_for_name_lost_or_acquired (signal_data) &&
4121 !g_dbus_connection_is_closed (connection) &&
4122 !connection->finalizing)
4124 /* The check for g_dbus_connection_is_closed() means that
4125 * sending the RemoveMatch message can't fail with
4126 * G_IO_ERROR_CLOSED, because we're holding the lock,
4127 * so on_worker_closed() can't happen between the check we just
4128 * did, and releasing the lock later.
4130 remove_match_rule (connection, signal_data->rule);
4134 if (G_IS_KDBUS_CONNECTION (connection->stream))
4136 if (g_strcmp0 (signal_data->member, "NameAcquired") == 0)
4137 _g_kdbus_unsubscribe_name_acquired (connection);
4138 else if (g_strcmp0 (signal_data->member, "NameLost") == 0)
4139 _g_kdbus_unsubscribe_name_lost (connection);
4143 signal_data_free (signal_data);
4149 g_assert_not_reached ();
4156 * g_dbus_connection_signal_unsubscribe:
4157 * @connection: a #GDBusConnection
4158 * @subscription_id: a subscription id obtained from
4159 * g_dbus_connection_signal_subscribe()
4161 * Unsubscribes from signals.
4166 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
4167 guint subscription_id)
4169 GArray *subscribers;
4172 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4173 g_return_if_fail (check_initialized (connection));
4175 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
4177 CONNECTION_LOCK (connection);
4178 unsubscribe_id_internal (connection,
4181 CONNECTION_UNLOCK (connection);
4184 g_assert (subscribers->len == 0 || subscribers->len == 1);
4186 /* call GDestroyNotify without lock held */
4187 for (n = 0; n < subscribers->len; n++)
4189 SignalSubscriber *subscriber;
4190 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
4191 call_destroy_notify (subscriber->context,
4192 subscriber->user_data_free_func,
4193 subscriber->user_data);
4194 g_main_context_unref (subscriber->context);
4197 g_array_free (subscribers, TRUE);
4200 /* ---------------------------------------------------------------------------------------------------- */
4204 guint subscription_id;
4205 GDBusSignalCallback callback;
4207 GDBusMessage *message;
4208 GDBusConnection *connection;
4209 const gchar *sender;
4211 const gchar *interface;
4212 const gchar *member;
4215 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
4219 emit_signal_instance_in_idle_cb (gpointer data)
4221 SignalInstance *signal_instance = data;
4222 GVariant *parameters;
4223 gboolean has_subscription;
4225 parameters = g_dbus_message_get_body (signal_instance->message);
4226 if (parameters == NULL)
4228 parameters = g_variant_new ("()");
4229 g_variant_ref_sink (parameters);
4233 g_variant_ref (parameters);
4237 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
4238 signal_instance->subscription_id,
4239 signal_instance->sender,
4240 signal_instance->path,
4241 signal_instance->interface,
4242 signal_instance->member,
4243 g_variant_print (parameters, TRUE));
4246 /* Careful here, don't do the callback if we no longer has the subscription */
4247 CONNECTION_LOCK (signal_instance->connection);
4248 has_subscription = FALSE;
4249 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
4250 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
4251 has_subscription = TRUE;
4252 CONNECTION_UNLOCK (signal_instance->connection);
4254 if (has_subscription)
4255 signal_instance->callback (signal_instance->connection,
4256 signal_instance->sender,
4257 signal_instance->path,
4258 signal_instance->interface,
4259 signal_instance->member,
4261 signal_instance->user_data);
4263 g_variant_unref (parameters);
4269 signal_instance_free (SignalInstance *signal_instance)
4271 g_object_unref (signal_instance->message);
4272 g_object_unref (signal_instance->connection);
4273 g_free (signal_instance);
4277 namespace_rule_matches (const gchar *namespace,
4283 len_namespace = strlen (namespace);
4284 len_name = strlen (name);
4286 if (len_name < len_namespace)
4289 if (memcmp (namespace, name, len_namespace) != 0)
4292 return len_namespace == len_name || name[len_namespace] == '.';
4296 path_rule_matches (const gchar *path_a,
4297 const gchar *path_b)
4301 len_a = strlen (path_a);
4302 len_b = strlen (path_b);
4304 if (len_a < len_b && path_a[len_a - 1] != '/')
4307 if (len_b < len_a && path_b[len_b - 1] != '/')
4310 return memcmp (path_a, path_b, MIN (len_a, len_b)) == 0;
4313 /* called in GDBusWorker thread WITH lock held */
4315 schedule_callbacks (GDBusConnection *connection,
4316 GPtrArray *signal_data_array,
4317 GDBusMessage *message,
4318 const gchar *sender)
4321 const gchar *interface;
4322 const gchar *member;
4331 interface = g_dbus_message_get_interface (message);
4332 member = g_dbus_message_get_member (message);
4333 path = g_dbus_message_get_path (message);
4334 arg0 = g_dbus_message_get_arg0 (message);
4337 g_print ("In schedule_callbacks:\n"
4339 " interface = '%s'\n"
4350 /* TODO: if this is slow, then we can change signal_data_array into
4351 * map_object_path_to_signal_data_array or something.
4353 for (n = 0; n < signal_data_array->len; n++)
4355 SignalData *signal_data = signal_data_array->pdata[n];
4357 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
4360 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
4363 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
4366 if (signal_data->arg0 != NULL)
4371 if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
4373 if (!namespace_rule_matches (signal_data->arg0, arg0))
4376 else if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
4378 if (!path_rule_matches (signal_data->arg0, arg0))
4381 else if (!g_str_equal (signal_data->arg0, arg0))
4385 for (m = 0; m < signal_data->subscribers->len; m++)
4387 SignalSubscriber *subscriber;
4388 GSource *idle_source;
4389 SignalInstance *signal_instance;
4391 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
4393 signal_instance = g_new0 (SignalInstance, 1);
4394 signal_instance->subscription_id = subscriber->id;
4395 signal_instance->callback = subscriber->callback;
4396 signal_instance->user_data = subscriber->user_data;
4397 signal_instance->message = g_object_ref (message);
4398 signal_instance->connection = g_object_ref (connection);
4399 signal_instance->sender = sender;
4400 signal_instance->path = path;
4401 signal_instance->interface = interface;
4402 signal_instance->member = member;
4404 idle_source = g_idle_source_new ();
4405 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4406 g_source_set_callback (idle_source,
4407 emit_signal_instance_in_idle_cb,
4409 (GDestroyNotify) signal_instance_free);
4410 g_source_set_name (idle_source, "[gio] emit_signal_instance_in_idle_cb");
4411 g_source_attach (idle_source, subscriber->context);
4412 g_source_unref (idle_source);
4417 /* called in GDBusWorker thread with lock held */
4419 distribute_signals (GDBusConnection *connection,
4420 GDBusMessage *message)
4422 GPtrArray *signal_data_array;
4423 const gchar *sender;
4425 sender = g_dbus_message_get_sender (message);
4427 if (G_UNLIKELY (_g_dbus_debug_signal ()))
4429 _g_dbus_debug_print_lock ();
4430 g_print ("========================================================================\n"
4431 "GDBus-debug:Signal:\n"
4432 " <<<< RECEIVED SIGNAL %s.%s\n"
4434 " sent by name %s\n",
4435 g_dbus_message_get_interface (message),
4436 g_dbus_message_get_member (message),
4437 g_dbus_message_get_path (message),
4438 sender != NULL ? sender : "(none)");
4439 _g_dbus_debug_print_unlock ();
4442 /* collect subscribers that match on sender */
4445 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
4446 if (signal_data_array != NULL)
4447 schedule_callbacks (connection, signal_data_array, message, sender);
4450 /* collect subscribers not matching on sender */
4451 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
4452 if (signal_data_array != NULL)
4453 schedule_callbacks (connection, signal_data_array, message, sender);
4456 /* ---------------------------------------------------------------------------------------------------- */
4458 /* only called from finalize(), removes all subscriptions */
4460 purge_all_signal_subscriptions (GDBusConnection *connection)
4462 GHashTableIter iter;
4465 GArray *subscribers;
4468 ids = g_array_new (FALSE, FALSE, sizeof (guint));
4469 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
4470 while (g_hash_table_iter_next (&iter, &key, NULL))
4472 guint subscription_id = GPOINTER_TO_UINT (key);
4473 g_array_append_val (ids, subscription_id);
4476 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
4477 for (n = 0; n < ids->len; n++)
4479 guint subscription_id = g_array_index (ids, guint, n);
4480 unsubscribe_id_internal (connection,
4484 g_array_free (ids, TRUE);
4486 /* call GDestroyNotify without lock held */
4487 for (n = 0; n < subscribers->len; n++)
4489 SignalSubscriber *subscriber;
4490 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
4491 call_destroy_notify (subscriber->context,
4492 subscriber->user_data_free_func,
4493 subscriber->user_data);
4494 g_main_context_unref (subscriber->context);
4497 g_array_free (subscribers, TRUE);
4500 /* ---------------------------------------------------------------------------------------------------- */
4502 static GDBusInterfaceVTable *
4503 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
4505 /* Don't waste memory by copying padding - remember to update this
4506 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
4508 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4512 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
4517 /* ---------------------------------------------------------------------------------------------------- */
4519 static GDBusSubtreeVTable *
4520 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
4522 /* Don't waste memory by copying padding - remember to update this
4523 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
4525 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4529 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
4534 /* ---------------------------------------------------------------------------------------------------- */
4536 struct ExportedObject
4539 GDBusConnection *connection;
4541 /* maps gchar* -> ExportedInterface* */
4542 GHashTable *map_if_name_to_ei;
4545 /* only called with lock held */
4547 exported_object_free (ExportedObject *eo)
4549 g_free (eo->object_path);
4550 g_hash_table_unref (eo->map_if_name_to_ei);
4559 gchar *interface_name;
4560 GDBusInterfaceVTable *vtable;
4561 GDBusInterfaceInfo *interface_info;
4563 GMainContext *context;
4565 GDestroyNotify user_data_free_func;
4566 } ExportedInterface;
4568 /* called with lock held */
4570 exported_interface_free (ExportedInterface *ei)
4572 g_dbus_interface_info_cache_release (ei->interface_info);
4573 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
4575 call_destroy_notify (ei->context,
4576 ei->user_data_free_func,
4579 g_main_context_unref (ei->context);
4581 g_free (ei->interface_name);
4582 _g_dbus_interface_vtable_free (ei->vtable);
4586 /* ---------------------------------------------------------------------------------------------------- */
4588 /* Convenience function to check if @registration_id (if not zero) or
4589 * @subtree_registration_id (if not zero) has been unregistered. If
4590 * so, returns %TRUE.
4592 * May be called by any thread. Caller must *not* hold lock.
4595 has_object_been_unregistered (GDBusConnection *connection,
4596 guint registration_id,
4597 guint subtree_registration_id)
4601 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4605 CONNECTION_LOCK (connection);
4606 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
4607 GUINT_TO_POINTER (registration_id)) == NULL)
4611 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
4612 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
4616 CONNECTION_UNLOCK (connection);
4621 /* ---------------------------------------------------------------------------------------------------- */
4625 GDBusConnection *connection;
4626 GDBusMessage *message;
4628 const gchar *property_name;
4629 const GDBusInterfaceVTable *vtable;
4630 GDBusInterfaceInfo *interface_info;
4631 const GDBusPropertyInfo *property_info;
4632 guint registration_id;
4633 guint subtree_registration_id;
4637 property_data_free (PropertyData *data)
4639 g_object_unref (data->connection);
4640 g_object_unref (data->message);
4644 /* called in thread where object was registered - no locks held */
4646 invoke_get_property_in_idle_cb (gpointer _data)
4648 PropertyData *data = _data;
4651 GDBusMessage *reply;
4653 if (has_object_been_unregistered (data->connection,
4654 data->registration_id,
4655 data->subtree_registration_id))
4657 reply = g_dbus_message_new_method_error (data->message,
4658 "org.freedesktop.DBus.Error.UnknownMethod",
4659 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4660 g_dbus_message_get_path (data->message));
4661 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4662 g_object_unref (reply);
4667 value = data->vtable->get_property (data->connection,
4668 g_dbus_message_get_sender (data->message),
4669 g_dbus_message_get_path (data->message),
4670 data->interface_info->name,
4671 data->property_name,
4678 g_assert_no_error (error);
4680 g_variant_take_ref (value);
4681 reply = g_dbus_message_new_method_reply (data->message);
4682 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4683 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4684 g_variant_unref (value);
4685 g_object_unref (reply);
4689 gchar *dbus_error_name;
4690 g_assert (error != NULL);
4691 dbus_error_name = g_dbus_error_encode_gerror (error);
4692 reply = g_dbus_message_new_method_error_literal (data->message,
4695 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4696 g_free (dbus_error_name);
4697 g_error_free (error);
4698 g_object_unref (reply);
4705 /* called in thread where object was registered - no locks held */
4707 invoke_set_property_in_idle_cb (gpointer _data)
4709 PropertyData *data = _data;
4711 GDBusMessage *reply;
4717 g_variant_get (g_dbus_message_get_body (data->message),
4723 if (!data->vtable->set_property (data->connection,
4724 g_dbus_message_get_sender (data->message),
4725 g_dbus_message_get_path (data->message),
4726 data->interface_info->name,
4727 data->property_name,
4732 gchar *dbus_error_name;
4733 g_assert (error != NULL);
4734 dbus_error_name = g_dbus_error_encode_gerror (error);
4735 reply = g_dbus_message_new_method_error_literal (data->message,
4738 g_free (dbus_error_name);
4739 g_error_free (error);
4743 reply = g_dbus_message_new_method_reply (data->message);
4746 g_assert (reply != NULL);
4747 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4748 g_object_unref (reply);
4749 g_variant_unref (value);
4754 /* called in any thread with connection's lock held */
4756 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4757 GDBusMessage *message,
4758 guint registration_id,
4759 guint subtree_registration_id,
4761 GDBusInterfaceInfo *interface_info,
4762 const GDBusInterfaceVTable *vtable,
4763 GMainContext *main_context,
4767 const char *interface_name;
4768 const char *property_name;
4769 const GDBusPropertyInfo *property_info;
4770 GSource *idle_source;
4771 PropertyData *property_data;
4772 GDBusMessage *reply;
4777 g_variant_get (g_dbus_message_get_body (message),
4782 g_variant_get (g_dbus_message_get_body (message),
4791 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4793 property_info = NULL;
4795 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4796 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4797 if (property_info == NULL)
4799 reply = g_dbus_message_new_method_error (message,
4800 "org.freedesktop.DBus.Error.InvalidArgs",
4801 _("No such property '%s'"),
4803 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4804 g_object_unref (reply);
4809 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4811 reply = g_dbus_message_new_method_error (message,
4812 "org.freedesktop.DBus.Error.InvalidArgs",
4813 _("Property '%s' is not readable"),
4815 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4816 g_object_unref (reply);
4820 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4822 reply = g_dbus_message_new_method_error (message,
4823 "org.freedesktop.DBus.Error.InvalidArgs",
4824 _("Property '%s' is not writable"),
4826 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4827 g_object_unref (reply);
4836 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4837 * of the given value is wrong
4839 g_variant_get_child (g_dbus_message_get_body (message), 2, "v", &value);
4840 if (g_strcmp0 (g_variant_get_type_string (value), property_info->signature) != 0)
4842 reply = g_dbus_message_new_method_error (message,
4843 "org.freedesktop.DBus.Error.InvalidArgs",
4844 _("Error setting property '%s': Expected type '%s' but got '%s'"),
4845 property_name, property_info->signature,
4846 g_variant_get_type_string (value));
4847 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4848 g_variant_unref (value);
4849 g_object_unref (reply);
4854 g_variant_unref (value);
4857 /* If the vtable pointer for get_property() resp. set_property() is
4858 * NULL then dispatch the call via the method_call() handler.
4862 if (vtable->get_property == NULL)
4864 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4865 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4866 vtable, main_context, user_data);
4873 if (vtable->set_property == NULL)
4875 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4876 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4877 vtable, main_context, user_data);
4883 /* ok, got the property info - call user code in an idle handler */
4884 property_data = g_new0 (PropertyData, 1);
4885 property_data->connection = g_object_ref (connection);
4886 property_data->message = g_object_ref (message);
4887 property_data->user_data = user_data;
4888 property_data->property_name = property_name;
4889 property_data->vtable = vtable;
4890 property_data->interface_info = interface_info;
4891 property_data->property_info = property_info;
4892 property_data->registration_id = registration_id;
4893 property_data->subtree_registration_id = subtree_registration_id;
4895 idle_source = g_idle_source_new ();
4896 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4897 g_source_set_callback (idle_source,
4898 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4900 (GDestroyNotify) property_data_free);
4902 g_source_set_name (idle_source, "[gio] invoke_get_property_in_idle_cb");
4904 g_source_set_name (idle_source, "[gio] invoke_set_property_in_idle_cb");
4905 g_source_attach (idle_source, main_context);
4906 g_source_unref (idle_source);
4914 /* called in GDBusWorker thread with connection's lock held */
4916 handle_getset_property (GDBusConnection *connection,
4918 GDBusMessage *message,
4921 ExportedInterface *ei;
4923 const char *interface_name;
4924 const char *property_name;
4929 g_variant_get (g_dbus_message_get_body (message),
4934 g_variant_get (g_dbus_message_get_body (message),
4940 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4941 * no such interface registered
4943 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4946 GDBusMessage *reply;
4947 reply = g_dbus_message_new_method_error (message,
4948 "org.freedesktop.DBus.Error.InvalidArgs",
4949 _("No such interface '%s'"),
4951 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4952 g_object_unref (reply);
4957 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4970 /* ---------------------------------------------------------------------------------------------------- */
4974 GDBusConnection *connection;
4975 GDBusMessage *message;
4977 const GDBusInterfaceVTable *vtable;
4978 GDBusInterfaceInfo *interface_info;
4979 guint registration_id;
4980 guint subtree_registration_id;
4981 } PropertyGetAllData;
4984 property_get_all_data_free (PropertyData *data)
4986 g_object_unref (data->connection);
4987 g_object_unref (data->message);
4991 /* called in thread where object was registered - no locks held */
4993 invoke_get_all_properties_in_idle_cb (gpointer _data)
4995 PropertyGetAllData *data = _data;
4996 GVariantBuilder builder;
4997 GDBusMessage *reply;
5000 if (has_object_been_unregistered (data->connection,
5001 data->registration_id,
5002 data->subtree_registration_id))
5004 reply = g_dbus_message_new_method_error (data->message,
5005 "org.freedesktop.DBus.Error.UnknownMethod",
5006 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
5007 g_dbus_message_get_path (data->message));
5008 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5009 g_object_unref (reply);
5013 /* TODO: Right now we never fail this call - we just omit values if
5014 * a get_property() call is failing.
5016 * We could fail the whole call if just a single get_property() call
5017 * returns an error. We need clarification in the D-Bus spec about this.
5019 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
5020 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
5021 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
5023 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
5026 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
5029 value = data->vtable->get_property (data->connection,
5030 g_dbus_message_get_sender (data->message),
5031 g_dbus_message_get_path (data->message),
5032 data->interface_info->name,
5033 property_info->name,
5040 g_variant_take_ref (value);
5041 g_variant_builder_add (&builder,
5043 property_info->name,
5045 g_variant_unref (value);
5047 g_variant_builder_close (&builder);
5049 reply = g_dbus_message_new_method_reply (data->message);
5050 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
5051 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5052 g_object_unref (reply);
5059 interface_has_readable_properties (GDBusInterfaceInfo *interface_info)
5063 if (!interface_info->properties)
5066 for (i = 0; interface_info->properties[i]; i++)
5067 if (interface_info->properties[i]->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE)
5073 /* called in any thread with connection's lock held */
5075 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
5076 GDBusMessage *message,
5077 guint registration_id,
5078 guint subtree_registration_id,
5079 GDBusInterfaceInfo *interface_info,
5080 const GDBusInterfaceVTable *vtable,
5081 GMainContext *main_context,
5085 GSource *idle_source;
5086 PropertyGetAllData *property_get_all_data;
5093 /* If the vtable pointer for get_property() is NULL but we have a
5094 * non-zero number of readable properties, then dispatch the call via
5095 * the method_call() handler.
5097 if (vtable->get_property == NULL && interface_has_readable_properties (interface_info))
5099 schedule_method_call (connection, message, registration_id, subtree_registration_id,
5100 interface_info, NULL, NULL, g_dbus_message_get_body (message),
5101 vtable, main_context, user_data);
5106 /* ok, got the property info - call user in an idle handler */
5107 property_get_all_data = g_new0 (PropertyGetAllData, 1);
5108 property_get_all_data->connection = g_object_ref (connection);
5109 property_get_all_data->message = g_object_ref (message);
5110 property_get_all_data->user_data = user_data;
5111 property_get_all_data->vtable = vtable;
5112 property_get_all_data->interface_info = interface_info;
5113 property_get_all_data->registration_id = registration_id;
5114 property_get_all_data->subtree_registration_id = subtree_registration_id;
5116 idle_source = g_idle_source_new ();
5117 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
5118 g_source_set_callback (idle_source,
5119 invoke_get_all_properties_in_idle_cb,
5120 property_get_all_data,
5121 (GDestroyNotify) property_get_all_data_free);
5122 g_source_set_name (idle_source, "[gio] invoke_get_all_properties_in_idle_cb");
5123 g_source_attach (idle_source, main_context);
5124 g_source_unref (idle_source);
5132 /* called in GDBusWorker thread with connection's lock held */
5134 handle_get_all_properties (GDBusConnection *connection,
5136 GDBusMessage *message)
5138 ExportedInterface *ei;
5140 const char *interface_name;
5144 g_variant_get (g_dbus_message_get_body (message),
5148 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
5149 * no such interface registered
5151 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5154 GDBusMessage *reply;
5155 reply = g_dbus_message_new_method_error (message,
5156 "org.freedesktop.DBus.Error.InvalidArgs",
5157 _("No such interface"),
5159 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5160 g_object_unref (reply);
5165 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
5177 /* ---------------------------------------------------------------------------------------------------- */
5179 static const gchar introspect_header[] =
5180 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
5181 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
5182 "<!-- GDBus " PACKAGE_VERSION " -->\n"
5185 static const gchar introspect_tail[] =
5188 static const gchar introspect_properties_interface[] =
5189 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
5190 " <method name=\"Get\">\n"
5191 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5192 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
5193 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
5195 " <method name=\"GetAll\">\n"
5196 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5197 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
5199 " <method name=\"Set\">\n"
5200 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5201 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
5202 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
5204 " <signal name=\"PropertiesChanged\">\n"
5205 " <arg type=\"s\" name=\"interface_name\"/>\n"
5206 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
5207 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
5211 static const gchar introspect_introspectable_interface[] =
5212 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
5213 " <method name=\"Introspect\">\n"
5214 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
5217 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
5218 " <method name=\"Ping\"/>\n"
5219 " <method name=\"GetMachineId\">\n"
5220 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
5225 introspect_append_header (GString *s)
5227 g_string_append (s, introspect_header);
5231 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
5233 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
5239 begin = object_path + path_len;
5240 end = strchr (begin, '/');
5242 s = g_strndup (begin, end - begin);
5244 s = g_strdup (begin);
5246 if (g_hash_table_lookup (set, s) == NULL)
5247 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
5253 /* TODO: we want a nicer public interface for this */
5254 /* called in any thread with connection's lock held */
5256 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
5261 GHashTableIter hash_iter;
5262 const gchar *object_path;
5268 CONNECTION_ENSURE_LOCK (connection);
5270 path_len = strlen (path);
5274 set = g_hash_table_new (g_str_hash, g_str_equal);
5276 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
5277 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
5278 maybe_add_path (path, path_len, object_path, set);
5280 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
5281 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
5282 maybe_add_path (path, path_len, object_path, set);
5284 p = g_ptr_array_new ();
5285 keys = g_hash_table_get_keys (set);
5286 for (l = keys; l != NULL; l = l->next)
5287 g_ptr_array_add (p, l->data);
5288 g_hash_table_unref (set);
5291 g_ptr_array_add (p, NULL);
5292 ret = (gchar **) g_ptr_array_free (p, FALSE);
5296 /* called in any thread with connection's lock not held */
5298 g_dbus_connection_list_registered (GDBusConnection *connection,
5302 CONNECTION_LOCK (connection);
5303 ret = g_dbus_connection_list_registered_unlocked (connection, path);
5304 CONNECTION_UNLOCK (connection);
5308 /* called in GDBusWorker thread with connection's lock held */
5310 handle_introspect (GDBusConnection *connection,
5312 GDBusMessage *message)
5316 GDBusMessage *reply;
5317 GHashTableIter hash_iter;
5318 ExportedInterface *ei;
5321 /* first the header with the standard interfaces */
5322 s = g_string_sized_new (sizeof (introspect_header) +
5323 sizeof (introspect_properties_interface) +
5324 sizeof (introspect_introspectable_interface) +
5325 sizeof (introspect_tail));
5326 introspect_append_header (s);
5327 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
5328 "org.freedesktop.DBus.Properties"))
5329 g_string_append (s, introspect_properties_interface);
5331 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
5332 "org.freedesktop.DBus.Introspectable"))
5333 g_string_append (s, introspect_introspectable_interface);
5335 /* then include the registered interfaces */
5336 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
5337 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
5338 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
5340 /* finally include nodes registered below us */
5341 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
5342 for (n = 0; registered != NULL && registered[n] != NULL; n++)
5343 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
5344 g_strfreev (registered);
5345 g_string_append (s, introspect_tail);
5347 reply = g_dbus_message_new_method_reply (message);
5348 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5349 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5350 g_object_unref (reply);
5351 g_string_free (s, TRUE);
5356 /* called in thread where object was registered - no locks held */
5358 call_in_idle_cb (gpointer user_data)
5360 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
5361 GDBusInterfaceVTable *vtable;
5362 guint registration_id;
5363 guint subtree_registration_id;
5365 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
5366 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
5368 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
5370 subtree_registration_id))
5372 GDBusMessage *reply;
5373 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
5374 "org.freedesktop.DBus.Error.UnknownMethod",
5375 _("No such interface '%s' on object at path %s"),
5376 g_dbus_method_invocation_get_interface_name (invocation),
5377 g_dbus_method_invocation_get_object_path (invocation));
5378 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5379 g_object_unref (reply);
5383 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
5384 g_assert (vtable != NULL && vtable->method_call != NULL);
5386 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
5387 g_dbus_method_invocation_get_sender (invocation),
5388 g_dbus_method_invocation_get_object_path (invocation),
5389 g_dbus_method_invocation_get_interface_name (invocation),
5390 g_dbus_method_invocation_get_method_name (invocation),
5391 g_dbus_method_invocation_get_parameters (invocation),
5392 g_object_ref (invocation),
5393 g_dbus_method_invocation_get_user_data (invocation));
5399 /* called in GDBusWorker thread with connection's lock held */
5401 schedule_method_call (GDBusConnection *connection,
5402 GDBusMessage *message,
5403 guint registration_id,
5404 guint subtree_registration_id,
5405 const GDBusInterfaceInfo *interface_info,
5406 const GDBusMethodInfo *method_info,
5407 const GDBusPropertyInfo *property_info,
5408 GVariant *parameters,
5409 const GDBusInterfaceVTable *vtable,
5410 GMainContext *main_context,
5413 GDBusMethodInvocation *invocation;
5414 GSource *idle_source;
5416 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
5417 g_dbus_message_get_path (message),
5418 g_dbus_message_get_interface (message),
5419 g_dbus_message_get_member (message),
5427 /* TODO: would be nicer with a real MethodData like we already
5428 * have PropertyData and PropertyGetAllData... */
5429 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
5430 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
5431 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
5433 idle_source = g_idle_source_new ();
5434 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
5435 g_source_set_callback (idle_source,
5439 g_source_set_name (idle_source, "[gio] call_in_idle_cb");
5440 g_source_attach (idle_source, main_context);
5441 g_source_unref (idle_source);
5444 /* called in GDBusWorker thread with connection's lock held */
5446 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
5447 GDBusMessage *message,
5448 guint registration_id,
5449 guint subtree_registration_id,
5450 GDBusInterfaceInfo *interface_info,
5451 const GDBusInterfaceVTable *vtable,
5452 GMainContext *main_context,
5455 GDBusMethodInfo *method_info;
5456 GDBusMessage *reply;
5457 GVariant *parameters;
5459 GVariantType *in_type;
5463 /* TODO: the cost of this is O(n) - it might be worth caching the result */
5464 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
5466 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
5467 * error to the caller
5469 if (method_info == NULL)
5471 reply = g_dbus_message_new_method_error (message,
5472 "org.freedesktop.DBus.Error.UnknownMethod",
5473 _("No such method '%s'"),
5474 g_dbus_message_get_member (message));
5475 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5476 g_object_unref (reply);
5481 parameters = g_dbus_message_get_body (message);
5482 if (parameters == NULL)
5484 parameters = g_variant_new ("()");
5485 g_variant_ref_sink (parameters);
5489 g_variant_ref (parameters);
5492 /* Check that the incoming args are of the right type - if they are not, return
5493 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
5495 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
5496 if (!g_variant_is_of_type (parameters, in_type))
5500 type_string = g_variant_type_dup_string (in_type);
5502 reply = g_dbus_message_new_method_error (message,
5503 "org.freedesktop.DBus.Error.InvalidArgs",
5504 _("Type of message, '%s', does not match expected type '%s'"),
5505 g_variant_get_type_string (parameters),
5507 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5508 g_variant_type_free (in_type);
5509 g_variant_unref (parameters);
5510 g_object_unref (reply);
5511 g_free (type_string);
5515 g_variant_type_free (in_type);
5517 /* schedule the call in idle */
5518 schedule_method_call (connection, message, registration_id, subtree_registration_id,
5519 interface_info, method_info, NULL, parameters,
5520 vtable, main_context, user_data);
5521 g_variant_unref (parameters);
5528 /* ---------------------------------------------------------------------------------------------------- */
5530 /* called in GDBusWorker thread with connection's lock held */
5532 obj_message_func (GDBusConnection *connection,
5534 GDBusMessage *message)
5536 const gchar *interface_name;
5537 const gchar *member;
5538 const gchar *signature;
5543 interface_name = g_dbus_message_get_interface (message);
5544 member = g_dbus_message_get_member (message);
5545 signature = g_dbus_message_get_signature (message);
5547 /* see if we have an interface for handling this call */
5548 if (interface_name != NULL)
5550 ExportedInterface *ei;
5551 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5554 /* we do - invoke the handler in idle in the right thread */
5556 /* handle no vtable or handler being present */
5557 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
5560 handled = validate_and_maybe_schedule_method_call (connection,
5572 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5573 g_strcmp0 (member, "Introspect") == 0 &&
5574 g_strcmp0 (signature, "") == 0)
5576 handled = handle_introspect (connection, eo, message);
5579 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5580 g_strcmp0 (member, "Get") == 0 &&
5581 g_strcmp0 (signature, "ss") == 0)
5583 handled = handle_getset_property (connection, eo, message, TRUE);
5586 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5587 g_strcmp0 (member, "Set") == 0 &&
5588 g_strcmp0 (signature, "ssv") == 0)
5590 handled = handle_getset_property (connection, eo, message, FALSE);
5593 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5594 g_strcmp0 (member, "GetAll") == 0 &&
5595 g_strcmp0 (signature, "s") == 0)
5597 handled = handle_get_all_properties (connection, eo, message);
5606 * g_dbus_connection_register_object:
5607 * @connection: a #GDBusConnection
5608 * @object_path: the object path to register at
5609 * @interface_info: introspection data for the interface
5610 * @vtable: (allow-none): a #GDBusInterfaceVTable to call into or %NULL
5611 * @user_data: (allow-none): data to pass to functions in @vtable
5612 * @user_data_free_func: function to call when the object path is unregistered
5613 * @error: return location for error or %NULL
5615 * Registers callbacks for exported objects at @object_path with the
5616 * D-Bus interface that is described in @interface_info.
5618 * Calls to functions in @vtable (and @user_data_free_func) will happen
5620 * [thread-default main context][g-main-context-push-thread-default]
5621 * of the thread you are calling this method from.
5623 * Note that all #GVariant values passed to functions in @vtable will match
5624 * the signature given in @interface_info - if a remote caller passes
5625 * incorrect values, the `org.freedesktop.DBus.Error.InvalidArgs`
5626 * is returned to the remote caller.
5628 * Additionally, if the remote caller attempts to invoke methods or
5629 * access properties not mentioned in @interface_info the
5630 * `org.freedesktop.DBus.Error.UnknownMethod` resp.
5631 * `org.freedesktop.DBus.Error.InvalidArgs` errors
5632 * are returned to the caller.
5634 * It is considered a programming error if the
5635 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
5636 * #GVariant of incorrect type.
5638 * If an existing callback is already registered at @object_path and
5639 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
5641 * GDBus automatically implements the standard D-Bus interfaces
5642 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
5643 * and org.freedesktop.Peer, so you don't have to implement those for the
5644 * objects you export. You can implement org.freedesktop.DBus.Properties
5645 * yourself, e.g. to handle getting and setting of properties asynchronously.
5647 * Note that the reference count on @interface_info will be
5648 * incremented by 1 (unless allocated statically, e.g. if the
5649 * reference count is -1, see g_dbus_interface_info_ref()) for as long
5650 * as the object is exported. Also note that @vtable will be copied.
5652 * See this [server][gdbus-server] for an example of how to use this method.
5654 * Returns: 0 if @error is set, otherwise a registration id (never 0)
5655 * that can be used with g_dbus_connection_unregister_object()
5660 g_dbus_connection_register_object (GDBusConnection *connection,
5661 const gchar *object_path,
5662 GDBusInterfaceInfo *interface_info,
5663 const GDBusInterfaceVTable *vtable,
5665 GDestroyNotify user_data_free_func,
5669 ExportedInterface *ei;
5672 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5673 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5674 g_return_val_if_fail (interface_info != NULL, 0);
5675 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
5676 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5677 g_return_val_if_fail (check_initialized (connection), 0);
5681 CONNECTION_LOCK (connection);
5683 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5686 eo = g_new0 (ExportedObject, 1);
5687 eo->object_path = g_strdup (object_path);
5688 eo->connection = connection;
5689 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
5692 (GDestroyNotify) exported_interface_free);
5693 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
5696 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
5702 _("An object is already exported for the interface %s at %s"),
5703 interface_info->name,
5708 ei = g_new0 (ExportedInterface, 1);
5709 ei->id = _global_registration_id++; /* TODO: overflow etc. */
5711 ei->user_data = user_data;
5712 ei->user_data_free_func = user_data_free_func;
5713 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
5714 ei->interface_info = g_dbus_interface_info_ref (interface_info);
5715 g_dbus_interface_info_cache_build (ei->interface_info);
5716 ei->interface_name = g_strdup (interface_info->name);
5717 ei->context = g_main_context_ref_thread_default ();
5719 g_hash_table_insert (eo->map_if_name_to_ei,
5720 (gpointer) ei->interface_name,
5722 g_hash_table_insert (connection->map_id_to_ei,
5723 GUINT_TO_POINTER (ei->id),
5729 CONNECTION_UNLOCK (connection);
5735 * g_dbus_connection_unregister_object:
5736 * @connection: a #GDBusConnection
5737 * @registration_id: a registration id obtained from
5738 * g_dbus_connection_register_object()
5740 * Unregisters an object.
5742 * Returns: %TRUE if the object was unregistered, %FALSE otherwise
5747 g_dbus_connection_unregister_object (GDBusConnection *connection,
5748 guint registration_id)
5750 ExportedInterface *ei;
5754 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5755 g_return_val_if_fail (check_initialized (connection), FALSE);
5759 CONNECTION_LOCK (connection);
5761 ei = g_hash_table_lookup (connection->map_id_to_ei,
5762 GUINT_TO_POINTER (registration_id));
5768 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5769 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5770 /* unregister object path if we have no more exported interfaces */
5771 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5772 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5778 CONNECTION_UNLOCK (connection);
5783 /* ---------------------------------------------------------------------------------------------------- */
5786 * g_dbus_connection_emit_signal:
5787 * @connection: a #GDBusConnection
5788 * @destination_bus_name: (allow-none): the unique bus name for the destination
5789 * for the signal or %NULL to emit to all listeners
5790 * @object_path: path of remote object
5791 * @interface_name: D-Bus interface to emit a signal on
5792 * @signal_name: the name of the signal to emit
5793 * @parameters: (allow-none): a #GVariant tuple with parameters for the signal
5794 * or %NULL if not passing parameters
5795 * @error: Return location for error or %NULL
5799 * If the parameters GVariant is floating, it is consumed.
5801 * This can only fail if @parameters is not compatible with the D-Bus protocol.
5803 * Returns: %TRUE unless @error is set
5808 g_dbus_connection_emit_signal (GDBusConnection *connection,
5809 const gchar *destination_bus_name,
5810 const gchar *object_path,
5811 const gchar *interface_name,
5812 const gchar *signal_name,
5813 GVariant *parameters,
5816 GDBusMessage *message;
5822 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5823 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5824 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5825 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5826 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5827 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5828 g_return_val_if_fail (check_initialized (connection), FALSE);
5830 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5832 _g_dbus_debug_print_lock ();
5833 g_print ("========================================================================\n"
5834 "GDBus-debug:Emission:\n"
5835 " >>>> SIGNAL EMISSION %s.%s()\n"
5837 " destination %s\n",
5838 interface_name, signal_name,
5840 destination_bus_name != NULL ? destination_bus_name : "(none)");
5841 _g_dbus_debug_print_unlock ();
5844 message = g_dbus_message_new_signal (object_path,
5848 if (destination_bus_name != NULL)
5849 g_dbus_message_set_header (message,
5850 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5851 g_variant_new_string (destination_bus_name));
5853 if (parameters != NULL)
5854 g_dbus_message_set_body (message, parameters);
5856 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5857 g_object_unref (message);
5863 add_call_flags (GDBusMessage *message,
5864 GDBusCallFlags flags)
5866 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5867 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
5871 decode_method_reply (GDBusMessage *reply,
5872 const gchar *method_name,
5873 const GVariantType *reply_type,
5874 GUnixFDList **out_fd_list,
5880 switch (g_dbus_message_get_message_type (reply))
5882 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5883 result = g_dbus_message_get_body (reply);
5886 result = g_variant_new ("()");
5887 g_variant_ref_sink (result);
5891 g_variant_ref (result);
5894 if (!g_variant_is_of_type (result, reply_type))
5896 gchar *type_string = g_variant_type_dup_string (reply_type);
5900 G_IO_ERROR_INVALID_ARGUMENT,
5901 _("Method '%s' returned type '%s', but expected '%s'"),
5902 method_name, g_variant_get_type_string (result), type_string);
5904 g_variant_unref (result);
5905 g_free (type_string);
5912 if (out_fd_list != NULL)
5914 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5915 if (*out_fd_list != NULL)
5916 g_object_ref (*out_fd_list);
5922 case G_DBUS_MESSAGE_TYPE_ERROR:
5923 g_dbus_message_to_gerror (reply, error);
5927 g_assert_not_reached ();
5937 GSimpleAsyncResult *simple;
5938 GVariantType *reply_type;
5939 gchar *method_name; /* for error message */
5943 GUnixFDList *fd_list;
5947 call_state_free (CallState *state)
5949 g_variant_type_free (state->reply_type);
5950 g_free (state->method_name);
5952 if (state->value != NULL)
5953 g_variant_unref (state->value);
5954 if (state->fd_list != NULL)
5955 g_object_unref (state->fd_list);
5956 g_slice_free (CallState, state);
5959 /* called in any thread, with the connection's lock not held */
5961 g_dbus_connection_call_done (GObject *source,
5962 GAsyncResult *result,
5965 GSimpleAsyncResult *simple;
5966 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5967 CallState *state = user_data;
5969 GDBusMessage *reply;
5972 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5976 if (G_UNLIKELY (_g_dbus_debug_call ()))
5978 _g_dbus_debug_print_lock ();
5979 g_print ("========================================================================\n"
5980 "GDBus-debug:Call:\n"
5981 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5987 g_print ("SUCCESS\n");
5991 g_print ("FAILED: %s\n",
5994 _g_dbus_debug_print_unlock ();
5998 state->value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
6000 simple = state->simple; /* why? because state is freed before we unref simple.. */
6003 g_simple_async_result_take_error (state->simple, error);
6004 g_simple_async_result_complete (state->simple);
6005 call_state_free (state);
6009 g_simple_async_result_set_op_res_gpointer (state->simple, state, (GDestroyNotify) call_state_free);
6010 g_simple_async_result_complete (state->simple);
6012 g_clear_object (&reply);
6013 g_object_unref (simple);
6016 /* called in any thread, with the connection's lock not held */
6018 g_dbus_connection_call_internal (GDBusConnection *connection,
6019 const gchar *bus_name,
6020 const gchar *object_path,
6021 const gchar *interface_name,
6022 const gchar *method_name,
6023 GVariant *parameters,
6024 const GVariantType *reply_type,
6025 GDBusCallFlags flags,
6027 GUnixFDList *fd_list,
6028 GCancellable *cancellable,
6029 GAsyncReadyCallback callback,
6032 GDBusMessage *message;
6035 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
6036 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
6037 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
6038 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
6039 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
6040 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
6041 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
6042 g_return_if_fail (check_initialized (connection));
6044 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
6046 g_return_if_fail (fd_list == NULL);
6049 message = g_dbus_message_new_method_call (bus_name,
6053 add_call_flags (message, flags);
6054 if (parameters != NULL)
6055 g_dbus_message_set_body (message, parameters);
6058 if (fd_list != NULL)
6059 g_dbus_message_set_unix_fd_list (message, fd_list);
6062 /* If the user has no callback then we can just send the message with
6063 * the G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set and skip all
6064 * the logic for processing the reply. If the service sends the reply
6065 * anyway then it will just be ignored.
6067 if (callback != NULL)
6071 state = g_slice_new0 (CallState);
6072 state->simple = g_simple_async_result_new (G_OBJECT (connection),
6073 callback, user_data,
6074 g_dbus_connection_call_internal);
6075 g_simple_async_result_set_check_cancellable (state->simple, cancellable);
6076 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
6078 if (reply_type == NULL)
6079 reply_type = G_VARIANT_TYPE_ANY;
6081 state->reply_type = g_variant_type_copy (reply_type);
6083 g_dbus_connection_send_message_with_reply (connection,
6085 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
6089 g_dbus_connection_call_done,
6091 serial = state->serial;
6095 GDBusMessageFlags flags;
6097 flags = g_dbus_message_get_flags (message);
6098 flags |= G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
6099 g_dbus_message_set_flags (message, flags);
6101 g_dbus_connection_send_message (connection,
6103 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
6107 if (G_UNLIKELY (_g_dbus_debug_call ()))
6109 _g_dbus_debug_print_lock ();
6110 g_print ("========================================================================\n"
6111 "GDBus-debug:Call:\n"
6112 " >>>> ASYNC %s.%s()\n"
6114 " owned by name %s (serial %d)\n",
6118 bus_name != NULL ? bus_name : "(none)",
6120 _g_dbus_debug_print_unlock ();
6123 if (message != NULL)
6124 g_object_unref (message);
6127 /* called in any thread, with the connection's lock not held */
6129 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
6130 GUnixFDList **out_fd_list,
6134 GSimpleAsyncResult *simple;
6137 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
6138 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
6139 g_dbus_connection_call_internal), NULL);
6140 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6142 simple = G_SIMPLE_ASYNC_RESULT (res);
6144 if (g_simple_async_result_propagate_error (simple, error))
6147 state = g_simple_async_result_get_op_res_gpointer (simple);
6148 if (out_fd_list != NULL)
6149 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
6150 return g_variant_ref (state->value);
6153 /* called in any user thread, with the connection's lock not held */
6155 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
6156 const gchar *bus_name,
6157 const gchar *object_path,
6158 const gchar *interface_name,
6159 const gchar *method_name,
6160 GVariant *parameters,
6161 const GVariantType *reply_type,
6162 GDBusCallFlags flags,
6164 GUnixFDList *fd_list,
6165 GUnixFDList **out_fd_list,
6166 GCancellable *cancellable,
6169 GDBusMessage *message;
6170 GDBusMessage *reply;
6172 GError *local_error;
6173 GDBusSendMessageFlags send_flags;
6179 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
6180 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
6181 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
6182 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
6183 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
6184 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
6185 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
6187 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
6189 g_return_val_if_fail (fd_list == NULL, NULL);
6191 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6193 if (!(flags & CALL_FLAGS_INITIALIZING))
6194 g_return_val_if_fail (check_initialized (connection), FALSE);
6196 if (reply_type == NULL)
6197 reply_type = G_VARIANT_TYPE_ANY;
6199 message = g_dbus_message_new_method_call (bus_name,
6203 add_call_flags (message, flags);
6204 if (parameters != NULL)
6205 g_dbus_message_set_body (message, parameters);
6208 if (fd_list != NULL)
6209 g_dbus_message_set_unix_fd_list (message, fd_list);
6212 if (G_UNLIKELY (_g_dbus_debug_call ()))
6214 _g_dbus_debug_print_lock ();
6215 g_print ("========================================================================\n"
6216 "GDBus-debug:Call:\n"
6217 " >>>> SYNC %s.%s()\n"
6219 " owned by name %s\n",
6223 bus_name != NULL ? bus_name : "(none)");
6224 _g_dbus_debug_print_unlock ();
6229 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
6231 /* translate from one flavour of flags to another... */
6232 if (flags & CALL_FLAGS_INITIALIZING)
6233 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
6235 reply = g_dbus_connection_send_message_with_reply_sync (connection,
6239 NULL, /* volatile guint32 *out_serial */
6243 if (G_UNLIKELY (_g_dbus_debug_call ()))
6245 _g_dbus_debug_print_lock ();
6246 g_print ("========================================================================\n"
6247 "GDBus-debug:Call:\n"
6248 " <<<< SYNC COMPLETE %s.%s()\n"
6254 g_print ("SUCCESS\n");
6258 g_print ("FAILED: %s\n",
6259 local_error->message);
6261 _g_dbus_debug_print_unlock ();
6267 *error = local_error;
6269 g_error_free (local_error);
6273 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
6276 if (message != NULL)
6277 g_object_unref (message);
6279 g_object_unref (reply);
6284 /* ---------------------------------------------------------------------------------------------------- */
6287 * g_dbus_connection_call:
6288 * @connection: a #GDBusConnection
6289 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6290 * @connection is not a message bus connection
6291 * @object_path: path of remote object
6292 * @interface_name: D-Bus interface to invoke method on
6293 * @method_name: the name of the method to invoke
6294 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6295 * or %NULL if not passing parameters
6296 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6297 * @flags: flags from the #GDBusCallFlags enumeration
6298 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6299 * timeout or %G_MAXINT for no timeout
6300 * @cancellable: (allow-none): a #GCancellable or %NULL
6301 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request
6302 * is satisfied or %NULL if you don't care about the result of the
6304 * @user_data: the data to pass to @callback
6306 * Asynchronously invokes the @method_name method on the
6307 * @interface_name D-Bus interface on the remote object at
6308 * @object_path owned by @bus_name.
6310 * If @connection is closed then the operation will fail with
6311 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
6312 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
6313 * not compatible with the D-Bus protocol, the operation fails with
6314 * %G_IO_ERROR_INVALID_ARGUMENT.
6316 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
6317 * error will be raised if it does not match. Said another way, if you give a @reply_type
6318 * then any non-%NULL return value will be of this type.
6320 * If the @parameters #GVariant is floating, it is consumed. This allows
6321 * convenient 'inline' use of g_variant_new(), e.g.:
6322 * |[<!-- language="C" -->
6323 * g_dbus_connection_call (connection,
6324 * "org.freedesktop.StringThings",
6325 * "/org/freedesktop/StringThings",
6326 * "org.freedesktop.StringThings",
6328 * g_variant_new ("(ss)",
6332 * G_DBUS_CALL_FLAGS_NONE,
6335 * (GAsyncReadyCallback) two_strings_done,
6339 * This is an asynchronous method. When the operation is finished,
6340 * @callback will be invoked in the
6341 * [thread-default main context][g-main-context-push-thread-default]
6342 * of the thread you are calling this method from. You can then call
6343 * g_dbus_connection_call_finish() to get the result of the operation.
6344 * See g_dbus_connection_call_sync() for the synchronous version of this
6347 * If @callback is %NULL then the D-Bus method call message will be sent with
6348 * the %G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set.
6353 g_dbus_connection_call (GDBusConnection *connection,
6354 const gchar *bus_name,
6355 const gchar *object_path,
6356 const gchar *interface_name,
6357 const gchar *method_name,
6358 GVariant *parameters,
6359 const GVariantType *reply_type,
6360 GDBusCallFlags flags,
6362 GCancellable *cancellable,
6363 GAsyncReadyCallback callback,
6366 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);
6370 * g_dbus_connection_call_finish:
6371 * @connection: a #GDBusConnection
6372 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call()
6373 * @error: return location for error or %NULL
6375 * Finishes an operation started with g_dbus_connection_call().
6377 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6378 * return values. Free with g_variant_unref().
6383 g_dbus_connection_call_finish (GDBusConnection *connection,
6387 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
6391 * g_dbus_connection_call_sync:
6392 * @connection: a #GDBusConnection
6393 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6394 * @connection is not a message bus connection
6395 * @object_path: path of remote object
6396 * @interface_name: D-Bus interface to invoke method on
6397 * @method_name: the name of the method to invoke
6398 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6399 * or %NULL if not passing parameters
6400 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6401 * @flags: flags from the #GDBusCallFlags enumeration
6402 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6403 * timeout or %G_MAXINT for no timeout
6404 * @cancellable: (allow-none): a #GCancellable or %NULL
6405 * @error: return location for error or %NULL
6407 * Synchronously invokes the @method_name method on the
6408 * @interface_name D-Bus interface on the remote object at
6409 * @object_path owned by @bus_name.
6411 * If @connection is closed then the operation will fail with
6412 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
6413 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
6414 * contains a value not compatible with the D-Bus protocol, the operation
6415 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
6417 * If @reply_type is non-%NULL then the reply will be checked for having
6418 * this type and an error will be raised if it does not match. Said
6419 * another way, if you give a @reply_type then any non-%NULL return
6420 * value will be of this type.
6422 * If the @parameters #GVariant is floating, it is consumed.
6423 * This allows convenient 'inline' use of g_variant_new(), e.g.:
6424 * |[<!-- language="C" -->
6425 * g_dbus_connection_call_sync (connection,
6426 * "org.freedesktop.StringThings",
6427 * "/org/freedesktop/StringThings",
6428 * "org.freedesktop.StringThings",
6430 * g_variant_new ("(ss)",
6434 * G_DBUS_CALL_FLAGS_NONE,
6440 * The calling thread is blocked until a reply is received. See
6441 * g_dbus_connection_call() for the asynchronous version of
6444 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6445 * return values. Free with g_variant_unref().
6450 g_dbus_connection_call_sync (GDBusConnection *connection,
6451 const gchar *bus_name,
6452 const gchar *object_path,
6453 const gchar *interface_name,
6454 const gchar *method_name,
6455 GVariant *parameters,
6456 const GVariantType *reply_type,
6457 GDBusCallFlags flags,
6459 GCancellable *cancellable,
6462 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);
6465 /* ---------------------------------------------------------------------------------------------------- */
6470 * g_dbus_connection_call_with_unix_fd_list:
6471 * @connection: a #GDBusConnection
6472 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6473 * @connection is not a message bus connection
6474 * @object_path: path of remote object
6475 * @interface_name: D-Bus interface to invoke method on
6476 * @method_name: the name of the method to invoke
6477 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6478 * or %NULL if not passing parameters
6479 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6480 * @flags: flags from the #GDBusCallFlags enumeration
6481 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6482 * timeout or %G_MAXINT for no timeout
6483 * @fd_list: (allow-none): a #GUnixFDList or %NULL
6484 * @cancellable: (allow-none): a #GCancellable or %NULL
6485 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request is
6486 * satisfied or %NULL if you don't * care about the result of the
6488 * @user_data: The data to pass to @callback.
6490 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
6492 * This method is only available on UNIX.
6497 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
6498 const gchar *bus_name,
6499 const gchar *object_path,
6500 const gchar *interface_name,
6501 const gchar *method_name,
6502 GVariant *parameters,
6503 const GVariantType *reply_type,
6504 GDBusCallFlags flags,
6506 GUnixFDList *fd_list,
6507 GCancellable *cancellable,
6508 GAsyncReadyCallback callback,
6511 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);
6515 * g_dbus_connection_call_with_unix_fd_list_finish:
6516 * @connection: a #GDBusConnection
6517 * @out_fd_list: (out) (allow-none): return location for a #GUnixFDList or %NULL
6518 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
6519 * g_dbus_connection_call_with_unix_fd_list()
6520 * @error: return location for error or %NULL
6522 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
6524 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6525 * return values. Free with g_variant_unref().
6530 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
6531 GUnixFDList **out_fd_list,
6535 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
6539 * g_dbus_connection_call_with_unix_fd_list_sync:
6540 * @connection: a #GDBusConnection
6541 * @bus_name: (allow-none): a unique or well-known bus name or %NULL
6542 * if @connection is not a message bus connection
6543 * @object_path: path of remote object
6544 * @interface_name: D-Bus interface to invoke method on
6545 * @method_name: the name of the method to invoke
6546 * @parameters: (allow-none): a #GVariant tuple with parameters for
6547 * the method or %NULL if not passing parameters
6548 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6549 * @flags: flags from the #GDBusCallFlags enumeration
6550 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6551 * timeout or %G_MAXINT for no timeout
6552 * @fd_list: (allow-none): a #GUnixFDList or %NULL
6553 * @out_fd_list: (out) (allow-none): return location for a #GUnixFDList or %NULL
6554 * @cancellable: (allow-none): a #GCancellable or %NULL
6555 * @error: return location for error or %NULL
6557 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
6559 * This method is only available on UNIX.
6561 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6562 * return values. Free with g_variant_unref().
6567 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
6568 const gchar *bus_name,
6569 const gchar *object_path,
6570 const gchar *interface_name,
6571 const gchar *method_name,
6572 GVariant *parameters,
6573 const GVariantType *reply_type,
6574 GDBusCallFlags flags,
6576 GUnixFDList *fd_list,
6577 GUnixFDList **out_fd_list,
6578 GCancellable *cancellable,
6581 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);
6584 #endif /* G_OS_UNIX */
6586 /* ---------------------------------------------------------------------------------------------------- */
6588 struct ExportedSubtree
6592 GDBusConnection *connection;
6593 GDBusSubtreeVTable *vtable;
6594 GDBusSubtreeFlags flags;
6596 GMainContext *context;
6598 GDestroyNotify user_data_free_func;
6602 exported_subtree_free (ExportedSubtree *es)
6604 call_destroy_notify (es->context,
6605 es->user_data_free_func,
6608 g_main_context_unref (es->context);
6610 _g_dbus_subtree_vtable_free (es->vtable);
6611 g_free (es->object_path);
6615 /* called without lock held in the thread where the caller registered
6619 handle_subtree_introspect (GDBusConnection *connection,
6620 ExportedSubtree *es,
6621 GDBusMessage *message)
6625 GDBusMessage *reply;
6628 const gchar *sender;
6629 const gchar *requested_object_path;
6630 const gchar *requested_node;
6631 GDBusInterfaceInfo **interfaces;
6633 gchar **subnode_paths;
6634 gboolean has_properties_interface;
6635 gboolean has_introspectable_interface;
6639 requested_object_path = g_dbus_message_get_path (message);
6640 sender = g_dbus_message_get_sender (message);
6641 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6643 s = g_string_new (NULL);
6644 introspect_append_header (s);
6646 /* Strictly we don't need the children in dynamic mode, but we avoid the
6647 * conditionals to preserve code clarity
6649 children = es->vtable->enumerate (es->connection,
6656 requested_node = strrchr (requested_object_path, '/') + 1;
6658 /* Assert existence of object if we are not dynamic */
6659 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
6660 !_g_strv_has_string ((const gchar * const *) children, requested_node))
6665 requested_node = NULL;
6668 interfaces = es->vtable->introspect (es->connection,
6673 if (interfaces != NULL)
6675 has_properties_interface = FALSE;
6676 has_introspectable_interface = FALSE;
6678 for (n = 0; interfaces[n] != NULL; n++)
6680 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
6681 has_properties_interface = TRUE;
6682 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
6683 has_introspectable_interface = TRUE;
6685 if (!has_properties_interface)
6686 g_string_append (s, introspect_properties_interface);
6687 if (!has_introspectable_interface)
6688 g_string_append (s, introspect_introspectable_interface);
6690 for (n = 0; interfaces[n] != NULL; n++)
6692 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
6693 g_dbus_interface_info_unref (interfaces[n]);
6695 g_free (interfaces);
6698 /* then include <node> entries from the Subtree for the root */
6701 for (n = 0; children != NULL && children[n] != NULL; n++)
6702 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
6705 /* finally include nodes registered below us */
6706 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
6707 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
6708 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
6709 g_strfreev (subnode_paths);
6711 g_string_append (s, "</node>\n");
6713 reply = g_dbus_message_new_method_reply (message);
6714 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6715 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6716 g_object_unref (reply);
6721 g_string_free (s, TRUE);
6722 g_strfreev (children);
6726 /* called without lock held in the thread where the caller registered
6730 handle_subtree_method_invocation (GDBusConnection *connection,
6731 ExportedSubtree *es,
6732 GDBusMessage *message)
6735 const gchar *sender;
6736 const gchar *interface_name;
6737 const gchar *member;
6738 const gchar *signature;
6739 const gchar *requested_object_path;
6740 const gchar *requested_node;
6742 GDBusInterfaceInfo *interface_info;
6743 const GDBusInterfaceVTable *interface_vtable;
6744 gpointer interface_user_data;
6746 GDBusInterfaceInfo **interfaces;
6747 gboolean is_property_get;
6748 gboolean is_property_set;
6749 gboolean is_property_get_all;
6754 requested_object_path = g_dbus_message_get_path (message);
6755 sender = g_dbus_message_get_sender (message);
6756 interface_name = g_dbus_message_get_interface (message);
6757 member = g_dbus_message_get_member (message);
6758 signature = g_dbus_message_get_signature (message);
6759 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6761 is_property_get = FALSE;
6762 is_property_set = FALSE;
6763 is_property_get_all = FALSE;
6764 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6766 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6767 is_property_get = TRUE;
6768 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6769 is_property_set = TRUE;
6770 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6771 is_property_get_all = TRUE;
6776 requested_node = strrchr (requested_object_path, '/') + 1;
6778 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6780 /* We don't want to dispatch to unenumerated
6781 * nodes, so ensure that the child exists.
6786 children = es->vtable->enumerate (es->connection,
6791 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6792 g_strfreev (children);
6800 requested_node = NULL;
6803 /* get introspection data for the node */
6804 interfaces = es->vtable->introspect (es->connection,
6806 requested_object_path,
6810 if (interfaces == NULL)
6813 interface_info = NULL;
6814 for (n = 0; interfaces[n] != NULL; n++)
6816 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6817 interface_info = interfaces[n];
6820 /* dispatch the call if the user wants to handle it */
6821 if (interface_info != NULL)
6823 /* figure out where to dispatch the method call */
6824 interface_user_data = NULL;
6825 interface_vtable = es->vtable->dispatch (es->connection,
6830 &interface_user_data,
6832 if (interface_vtable == NULL)
6835 CONNECTION_LOCK (connection);
6836 handled = validate_and_maybe_schedule_method_call (es->connection,
6843 interface_user_data);
6844 CONNECTION_UNLOCK (connection);
6846 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6847 else if (is_property_get || is_property_set || is_property_get_all)
6849 if (is_property_get)
6850 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6851 else if (is_property_set)
6852 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6853 else if (is_property_get_all)
6854 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6856 g_assert_not_reached ();
6858 /* see if the object supports this interface at all */
6859 for (n = 0; interfaces[n] != NULL; n++)
6861 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6862 interface_info = interfaces[n];
6865 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6866 * claims it won't support the interface
6868 if (interface_info == NULL)
6870 GDBusMessage *reply;
6871 reply = g_dbus_message_new_method_error (message,
6872 "org.freedesktop.DBus.Error.InvalidArgs",
6873 _("No such interface '%s'"),
6875 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6876 g_object_unref (reply);
6881 /* figure out where to dispatch the property get/set/getall calls */
6882 interface_user_data = NULL;
6883 interface_vtable = es->vtable->dispatch (es->connection,
6888 &interface_user_data,
6890 if (interface_vtable == NULL)
6892 g_warning ("The subtree introspection function indicates that '%s' "
6893 "is a valid interface name, but calling the dispatch "
6894 "function on that interface gave us NULL", interface_name);
6898 if (is_property_get || is_property_set)
6900 CONNECTION_LOCK (connection);
6901 handled = validate_and_maybe_schedule_property_getset (es->connection,
6909 interface_user_data);
6910 CONNECTION_UNLOCK (connection);
6912 else if (is_property_get_all)
6914 CONNECTION_LOCK (connection);
6915 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6922 interface_user_data);
6923 CONNECTION_UNLOCK (connection);
6928 if (interfaces != NULL)
6930 for (n = 0; interfaces[n] != NULL; n++)
6931 g_dbus_interface_info_unref (interfaces[n]);
6932 g_free (interfaces);
6940 GDBusMessage *message;
6941 ExportedSubtree *es;
6942 } SubtreeDeferredData;
6945 subtree_deferred_data_free (SubtreeDeferredData *data)
6947 g_object_unref (data->message);
6951 /* called without lock held in the thread where the caller registered the subtree */
6953 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6955 SubtreeDeferredData *data = _data;
6960 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6961 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6962 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6963 handled = handle_subtree_introspect (data->es->connection,
6967 handled = handle_subtree_method_invocation (data->es->connection,
6973 CONNECTION_LOCK (data->es->connection);
6974 handled = handle_generic_unlocked (data->es->connection, data->message);
6975 CONNECTION_UNLOCK (data->es->connection);
6978 /* if we couldn't handle the request, just bail with the UnknownMethod error */
6981 GDBusMessage *reply;
6982 reply = g_dbus_message_new_method_error (data->message,
6983 "org.freedesktop.DBus.Error.UnknownMethod",
6984 _("Method '%s' on interface '%s' with signature '%s' does not exist"),
6985 g_dbus_message_get_member (data->message),
6986 g_dbus_message_get_interface (data->message),
6987 g_dbus_message_get_signature (data->message));
6988 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6989 g_object_unref (reply);
6995 /* called in GDBusWorker thread with connection's lock held */
6997 subtree_message_func (GDBusConnection *connection,
6998 ExportedSubtree *es,
6999 GDBusMessage *message)
7001 GSource *idle_source;
7002 SubtreeDeferredData *data;
7004 data = g_new0 (SubtreeDeferredData, 1);
7005 data->message = g_object_ref (message);
7008 /* defer this call to an idle handler in the right thread */
7009 idle_source = g_idle_source_new ();
7010 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
7011 g_source_set_callback (idle_source,
7012 process_subtree_vtable_message_in_idle_cb,
7014 (GDestroyNotify) subtree_deferred_data_free);
7015 g_source_set_name (idle_source, "[gio] process_subtree_vtable_message_in_idle_cb");
7016 g_source_attach (idle_source, es->context);
7017 g_source_unref (idle_source);
7019 /* since we own the entire subtree, handlers for objects not in the subtree have been
7020 * tried already by libdbus-1 - so we just need to ensure that we're always going
7021 * to reply to the message
7027 * g_dbus_connection_register_subtree:
7028 * @connection: a #GDBusConnection
7029 * @object_path: the object path to register the subtree at
7030 * @vtable: a #GDBusSubtreeVTable to enumerate, introspect and
7031 * dispatch nodes in the subtree
7032 * @flags: flags used to fine tune the behavior of the subtree
7033 * @user_data: data to pass to functions in @vtable
7034 * @user_data_free_func: function to call when the subtree is unregistered
7035 * @error: return location for error or %NULL
7037 * Registers a whole subtree of dynamic objects.
7039 * The @enumerate and @introspection functions in @vtable are used to
7040 * convey, to remote callers, what nodes exist in the subtree rooted
7043 * When handling remote calls into any node in the subtree, first the
7044 * @enumerate function is used to check if the node exists. If the node exists
7045 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
7046 * the @introspection function is used to check if the node supports the
7047 * requested method. If so, the @dispatch function is used to determine
7048 * where to dispatch the call. The collected #GDBusInterfaceVTable and
7049 * #gpointer will be used to call into the interface vtable for processing
7052 * All calls into user-provided code will be invoked in the
7053 * [thread-default main context][g-main-context-push-thread-default]
7054 * of the thread you are calling this method from.
7056 * If an existing subtree is already registered at @object_path or
7057 * then @error is set to #G_IO_ERROR_EXISTS.
7059 * Note that it is valid to register regular objects (using
7060 * g_dbus_connection_register_object()) in a subtree registered with
7061 * g_dbus_connection_register_subtree() - if so, the subtree handler
7062 * is tried as the last resort. One way to think about a subtree
7063 * handler is to consider it a fallback handler for object paths not
7064 * registered via g_dbus_connection_register_object() or other bindings.
7066 * Note that @vtable will be copied so you cannot change it after
7069 * See this [server][gdbus-subtree-server] for an example of how to use
7072 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
7073 * that can be used with g_dbus_connection_unregister_subtree() .
7078 g_dbus_connection_register_subtree (GDBusConnection *connection,
7079 const gchar *object_path,
7080 const GDBusSubtreeVTable *vtable,
7081 GDBusSubtreeFlags flags,
7083 GDestroyNotify user_data_free_func,
7087 ExportedSubtree *es;
7089 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
7090 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
7091 g_return_val_if_fail (vtable != NULL, 0);
7092 g_return_val_if_fail (error == NULL || *error == NULL, 0);
7093 g_return_val_if_fail (check_initialized (connection), 0);
7097 CONNECTION_LOCK (connection);
7099 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
7105 _("A subtree is already exported for %s"),
7110 es = g_new0 (ExportedSubtree, 1);
7111 es->object_path = g_strdup (object_path);
7112 es->connection = connection;
7114 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
7116 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
7117 es->user_data = user_data;
7118 es->user_data_free_func = user_data_free_func;
7119 es->context = g_main_context_ref_thread_default ();
7121 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
7122 g_hash_table_insert (connection->map_id_to_es,
7123 GUINT_TO_POINTER (es->id),
7129 CONNECTION_UNLOCK (connection);
7134 /* ---------------------------------------------------------------------------------------------------- */
7137 * g_dbus_connection_unregister_subtree:
7138 * @connection: a #GDBusConnection
7139 * @registration_id: a subtree registration id obtained from
7140 * g_dbus_connection_register_subtree()
7142 * Unregisters a subtree.
7144 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise
7149 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
7150 guint registration_id)
7152 ExportedSubtree *es;
7155 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
7156 g_return_val_if_fail (check_initialized (connection), FALSE);
7160 CONNECTION_LOCK (connection);
7162 es = g_hash_table_lookup (connection->map_id_to_es,
7163 GUINT_TO_POINTER (registration_id));
7167 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
7168 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
7173 CONNECTION_UNLOCK (connection);
7178 /* ---------------------------------------------------------------------------------------------------- */
7180 /* may be called in any thread, with connection's lock held */
7182 handle_generic_ping_unlocked (GDBusConnection *connection,
7183 const gchar *object_path,
7184 GDBusMessage *message)
7186 GDBusMessage *reply;
7187 reply = g_dbus_message_new_method_reply (message);
7188 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7189 g_object_unref (reply);
7192 /* may be called in any thread, with connection's lock held */
7194 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
7195 const gchar *object_path,
7196 GDBusMessage *message)
7198 GDBusMessage *reply;
7201 if (connection->machine_id == NULL)
7206 connection->machine_id = _g_dbus_get_machine_id (&error);
7207 if (connection->machine_id == NULL)
7209 reply = g_dbus_message_new_method_error_literal (message,
7210 "org.freedesktop.DBus.Error.Failed",
7212 g_error_free (error);
7218 reply = g_dbus_message_new_method_reply (message);
7219 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
7221 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7222 g_object_unref (reply);
7225 /* may be called in any thread, with connection's lock held */
7227 handle_generic_introspect_unlocked (GDBusConnection *connection,
7228 const gchar *object_path,
7229 GDBusMessage *message)
7234 GDBusMessage *reply;
7236 /* first the header */
7237 s = g_string_new (NULL);
7238 introspect_append_header (s);
7240 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
7241 for (n = 0; registered != NULL && registered[n] != NULL; n++)
7242 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
7243 g_strfreev (registered);
7244 g_string_append (s, "</node>\n");
7246 reply = g_dbus_message_new_method_reply (message);
7247 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
7248 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7249 g_object_unref (reply);
7250 g_string_free (s, TRUE);
7253 /* may be called in any thread, with connection's lock held */
7255 handle_generic_unlocked (GDBusConnection *connection,
7256 GDBusMessage *message)
7259 const gchar *interface_name;
7260 const gchar *member;
7261 const gchar *signature;
7264 CONNECTION_ENSURE_LOCK (connection);
7268 interface_name = g_dbus_message_get_interface (message);
7269 member = g_dbus_message_get_member (message);
7270 signature = g_dbus_message_get_signature (message);
7271 path = g_dbus_message_get_path (message);
7273 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
7274 g_strcmp0 (member, "Introspect") == 0 &&
7275 g_strcmp0 (signature, "") == 0)
7277 handle_generic_introspect_unlocked (connection, path, message);
7280 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7281 g_strcmp0 (member, "Ping") == 0 &&
7282 g_strcmp0 (signature, "") == 0)
7284 handle_generic_ping_unlocked (connection, path, message);
7287 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7288 g_strcmp0 (member, "GetMachineId") == 0 &&
7289 g_strcmp0 (signature, "") == 0)
7291 handle_generic_get_machine_id_unlocked (connection, path, message);
7298 /* ---------------------------------------------------------------------------------------------------- */
7300 /* called in GDBusWorker thread with connection's lock held */
7302 distribute_method_call (GDBusConnection *connection,
7303 GDBusMessage *message)
7305 GDBusMessage *reply;
7307 ExportedSubtree *es;
7308 const gchar *object_path;
7309 const gchar *interface_name;
7310 const gchar *member;
7312 gchar *subtree_path;
7315 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
7317 interface_name = g_dbus_message_get_interface (message);
7318 member = g_dbus_message_get_member (message);
7319 path = g_dbus_message_get_path (message);
7320 subtree_path = g_strdup (path);
7321 needle = strrchr (subtree_path, '/');
7322 if (needle != NULL && needle != subtree_path)
7328 g_free (subtree_path);
7329 subtree_path = NULL;
7333 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
7335 _g_dbus_debug_print_lock ();
7336 g_print ("========================================================================\n"
7337 "GDBus-debug:Incoming:\n"
7338 " <<<< METHOD INVOCATION %s.%s()\n"
7340 " invoked by name %s\n"
7342 interface_name, member,
7344 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
7345 g_dbus_message_get_serial (message));
7346 _g_dbus_debug_print_unlock ();
7349 object_path = g_dbus_message_get_path (message);
7350 g_assert (object_path != NULL);
7352 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
7355 if (obj_message_func (connection, eo, message))
7359 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
7362 if (subtree_message_func (connection, es, message))
7366 if (subtree_path != NULL)
7368 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
7371 if (subtree_message_func (connection, es, message))
7376 if (handle_generic_unlocked (connection, message))
7379 /* if we end up here, the message has not been not handled - so return an error saying this */
7380 reply = g_dbus_message_new_method_error (message,
7381 "org.freedesktop.DBus.Error.UnknownMethod",
7382 _("No such interface '%s' on object at path %s"),
7385 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7386 g_object_unref (reply);
7389 g_free (subtree_path);
7392 /* ---------------------------------------------------------------------------------------------------- */
7394 /* Called in any user thread, with the message_bus_lock held. */
7396 message_bus_get_singleton (GBusType bus_type,
7400 const gchar *starter_bus;
7406 case G_BUS_TYPE_SESSION:
7407 ret = &the_session_bus;
7410 case G_BUS_TYPE_SYSTEM:
7411 ret = &the_system_bus;
7414 case G_BUS_TYPE_USER:
7415 ret = &the_user_bus;
7418 case G_BUS_TYPE_MACHINE:
7419 ret = &the_machine_bus;
7422 case G_BUS_TYPE_STARTER:
7423 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
7424 if (g_strcmp0 (starter_bus, "session") == 0)
7426 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
7429 else if (g_strcmp0 (starter_bus, "system") == 0)
7431 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
7436 if (starter_bus != NULL)
7440 G_IO_ERROR_INVALID_ARGUMENT,
7441 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
7442 " - unknown value '%s'"),
7447 g_set_error_literal (error,
7449 G_IO_ERROR_INVALID_ARGUMENT,
7450 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
7451 "variable is not set"));
7457 g_assert_not_reached ();
7465 /* Called in any user thread, without holding locks. */
7466 static GDBusConnection *
7467 get_uninitialized_connection (GBusType bus_type,
7468 GCancellable *cancellable,
7471 GWeakRef *singleton;
7472 GDBusConnection *ret;
7476 G_LOCK (message_bus_lock);
7477 singleton = message_bus_get_singleton (bus_type, error);
7478 if (singleton == NULL)
7481 ret = g_weak_ref_get (singleton);
7486 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
7487 if (address == NULL)
7489 ret = g_object_new (G_TYPE_DBUS_CONNECTION,
7491 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
7492 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
7493 "exit-on-close", TRUE,
7496 g_weak_ref_set (singleton, ret);
7500 g_assert (ret != NULL);
7503 G_UNLOCK (message_bus_lock);
7507 /* May be called from any thread. Must not hold message_bus_lock. */
7509 _g_bus_get_singleton_if_exists (GBusType bus_type)
7511 GWeakRef *singleton;
7512 GDBusConnection *ret = NULL;
7514 G_LOCK (message_bus_lock);
7515 singleton = message_bus_get_singleton (bus_type, NULL);
7516 if (singleton == NULL)
7519 ret = g_weak_ref_get (singleton);
7522 G_UNLOCK (message_bus_lock);
7528 * @bus_type: a #GBusType
7529 * @cancellable: (allow-none): a #GCancellable or %NULL
7530 * @error: return location for error or %NULL
7532 * Synchronously connects to the message bus specified by @bus_type.
7533 * Note that the returned object may shared with other callers,
7534 * e.g. if two separate parts of a process calls this function with
7535 * the same @bus_type, they will share the same object.
7537 * This is a synchronous failable function. See g_bus_get() and
7538 * g_bus_get_finish() for the asynchronous version.
7540 * The returned object is a singleton, that is, shared with other
7541 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7542 * event that you need a private message bus connection, use
7543 * g_dbus_address_get_for_bus_sync() and
7544 * g_dbus_connection_new_for_address().
7546 * Note that the returned #GDBusConnection object will (usually) have
7547 * the #GDBusConnection:exit-on-close property set to %TRUE.
7549 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7550 * Free with g_object_unref().
7555 g_bus_get_sync (GBusType bus_type,
7556 GCancellable *cancellable,
7559 GDBusConnection *connection;
7561 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7563 connection = get_uninitialized_connection (bus_type, cancellable, error);
7564 if (connection == NULL)
7567 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
7569 g_object_unref (connection);
7578 bus_get_async_initable_cb (GObject *source_object,
7582 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
7586 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
7590 g_assert (error != NULL);
7591 g_simple_async_result_take_error (simple, error);
7592 g_object_unref (source_object);
7596 g_simple_async_result_set_op_res_gpointer (simple,
7600 g_simple_async_result_complete_in_idle (simple);
7601 g_object_unref (simple);
7606 * @bus_type: a #GBusType
7607 * @cancellable: (allow-none): a #GCancellable or %NULL
7608 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
7609 * @user_data: the data to pass to @callback
7611 * Asynchronously connects to the message bus specified by @bus_type.
7613 * When the operation is finished, @callback will be invoked. You can
7614 * then call g_bus_get_finish() to get the result of the operation.
7616 * This is a asynchronous failable function. See g_bus_get_sync() for
7617 * the synchronous version.
7622 g_bus_get (GBusType bus_type,
7623 GCancellable *cancellable,
7624 GAsyncReadyCallback callback,
7627 GDBusConnection *connection;
7628 GSimpleAsyncResult *simple;
7631 simple = g_simple_async_result_new (NULL,
7635 g_simple_async_result_set_check_cancellable (simple, cancellable);
7638 connection = get_uninitialized_connection (bus_type, cancellable, &error);
7639 if (connection == NULL)
7641 g_assert (error != NULL);
7642 g_simple_async_result_take_error (simple, error);
7643 g_simple_async_result_complete_in_idle (simple);
7644 g_object_unref (simple);
7648 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
7651 bus_get_async_initable_cb,
7658 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
7660 * @error: return location for error or %NULL
7662 * Finishes an operation started with g_bus_get().
7664 * The returned object is a singleton, that is, shared with other
7665 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7666 * event that you need a private message bus connection, use
7667 * g_dbus_address_get_for_bus_sync() and
7668 * g_dbus_connection_new_for_address().
7670 * Note that the returned #GDBusConnection object will (usually) have
7671 * the #GDBusConnection:exit-on-close property set to %TRUE.
7673 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7674 * Free with g_object_unref().
7679 g_bus_get_finish (GAsyncResult *res,
7682 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
7684 GDBusConnection *ret;
7686 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7688 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
7692 if (g_simple_async_result_propagate_error (simple, error))
7695 object = g_simple_async_result_get_op_res_gpointer (simple);
7696 g_assert (object != NULL);
7697 ret = g_object_ref (G_DBUS_CONNECTION (object));
7703 /* ---------------------------------------------------------------------------------------------------- */