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,
2128 * Setting protocol version, before invoking g_dbus_message_to_blob() will
2129 * be removed after preparing new function only for kdbus transport purposes
2130 * (this function will be able to create blob directly/unconditionally in memfd
2131 * object, without making copy)
2134 if (G_IS_KDBUS_CONNECTION (connection->stream))
2135 _g_dbus_message_set_protocol_ver (message,2);
2137 _g_dbus_message_set_protocol_ver (message,1);
2139 blob = g_dbus_message_to_blob (message,
2141 connection->capabilities,
2146 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
2147 serial_to_use = g_dbus_message_get_serial (message);
2149 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
2154 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
2157 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
2160 g_assert_not_reached ();
2165 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
2166 blob_size, serial_to_use, connection);
2167 g_printerr ("----\n");
2168 hexdump (blob, blob_size);
2169 g_printerr ("----\n");
2172 /* TODO: use connection->auth to encode the blob */
2174 if (out_serial != NULL)
2175 *out_serial = serial_to_use;
2177 /* store used serial for the current thread */
2178 /* TODO: watch the thread disposal and remove associated record
2180 * - see https://bugzilla.gnome.org/show_bug.cgi?id=676825#c7
2182 g_hash_table_replace (connection->map_thread_to_last_serial,
2184 GUINT_TO_POINTER (serial_to_use));
2186 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
2187 g_dbus_message_set_serial (message, serial_to_use);
2189 g_dbus_message_lock (message);
2190 _g_dbus_worker_send_message (connection->worker,
2194 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
2205 * g_dbus_connection_send_message:
2206 * @connection: a #GDBusConnection
2207 * @message: a #GDBusMessage
2208 * @flags: flags affecting how the message is sent
2209 * @out_serial: (out) (allow-none): return location for serial number assigned
2210 * to @message when sending it or %NULL
2211 * @error: Return location for error or %NULL
2213 * Asynchronously sends @message to the peer represented by @connection.
2215 * Unless @flags contain the
2216 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2217 * will be assigned by @connection and set on @message via
2218 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2219 * serial number used will be written to this location prior to
2220 * submitting the message to the underlying transport.
2222 * If @connection is closed then the operation will fail with
2223 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
2224 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2226 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2227 * for an example of how to use this low-level API to send and receive
2228 * UNIX file descriptors.
2230 * Note that @message must be unlocked, unless @flags contain the
2231 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2233 * Returns: %TRUE if the message was well-formed and queued for
2234 * transmission, %FALSE if @error is set
2239 g_dbus_connection_send_message (GDBusConnection *connection,
2240 GDBusMessage *message,
2241 GDBusSendMessageFlags flags,
2242 volatile guint32 *out_serial,
2247 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2248 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
2249 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
2250 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2252 CONNECTION_LOCK (connection);
2253 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
2254 CONNECTION_UNLOCK (connection);
2258 /* ---------------------------------------------------------------------------------------------------- */
2262 volatile gint ref_count;
2263 GDBusConnection *connection;
2265 GSimpleAsyncResult *simple;
2267 GMainContext *main_context;
2269 GCancellable *cancellable;
2271 gulong cancellable_handler_id;
2273 GSource *timeout_source;
2278 /* Can be called from any thread with or without lock held */
2279 static SendMessageData *
2280 send_message_data_ref (SendMessageData *data)
2282 g_atomic_int_inc (&data->ref_count);
2286 /* Can be called from any thread with or without lock held */
2288 send_message_data_unref (SendMessageData *data)
2290 if (g_atomic_int_dec_and_test (&data->ref_count))
2292 g_assert (data->timeout_source == NULL);
2293 g_assert (data->simple == NULL);
2294 g_assert (data->cancellable_handler_id == 0);
2295 g_object_unref (data->connection);
2296 if (data->cancellable != NULL)
2297 g_object_unref (data->cancellable);
2298 g_main_context_unref (data->main_context);
2303 /* ---------------------------------------------------------------------------------------------------- */
2305 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
2307 send_message_with_reply_deliver (SendMessageData *data, gboolean remove)
2309 CONNECTION_ENSURE_LOCK (data->connection);
2311 g_assert (!data->delivered);
2313 data->delivered = TRUE;
2315 g_simple_async_result_complete_in_idle (data->simple);
2316 g_object_unref (data->simple);
2317 data->simple = NULL;
2319 if (data->timeout_source != NULL)
2321 g_source_destroy (data->timeout_source);
2322 data->timeout_source = NULL;
2324 if (data->cancellable_handler_id > 0)
2326 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
2327 data->cancellable_handler_id = 0;
2332 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
2333 GUINT_TO_POINTER (data->serial)));
2336 send_message_data_unref (data);
2339 /* ---------------------------------------------------------------------------------------------------- */
2341 /* Can be called from any thread with lock held */
2343 send_message_data_deliver_reply_unlocked (SendMessageData *data,
2344 GDBusMessage *reply)
2346 if (data->delivered)
2349 g_simple_async_result_set_op_res_gpointer (data->simple,
2350 g_object_ref (reply),
2353 send_message_with_reply_deliver (data, TRUE);
2359 /* ---------------------------------------------------------------------------------------------------- */
2361 /* Called from a user thread, lock is not held */
2363 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
2365 SendMessageData *data = user_data;
2367 CONNECTION_LOCK (data->connection);
2368 if (data->delivered)
2371 g_simple_async_result_set_error (data->simple,
2373 G_IO_ERROR_CANCELLED,
2374 _("Operation was cancelled"));
2376 send_message_with_reply_deliver (data, TRUE);
2379 CONNECTION_UNLOCK (data->connection);
2383 /* Can be called from any thread with or without lock held */
2385 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
2388 SendMessageData *data = user_data;
2389 GSource *idle_source;
2391 /* postpone cancellation to idle handler since we may be called directly
2392 * via g_cancellable_connect() (e.g. holding lock)
2394 idle_source = g_idle_source_new ();
2395 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
2396 g_source_set_callback (idle_source,
2397 send_message_with_reply_cancelled_idle_cb,
2398 send_message_data_ref (data),
2399 (GDestroyNotify) send_message_data_unref);
2400 g_source_set_name (idle_source, "[gio] send_message_with_reply_cancelled_idle_cb");
2401 g_source_attach (idle_source, data->main_context);
2402 g_source_unref (idle_source);
2405 /* ---------------------------------------------------------------------------------------------------- */
2407 /* Called from a user thread, lock is not held */
2409 send_message_with_reply_timeout_cb (gpointer user_data)
2411 SendMessageData *data = user_data;
2413 CONNECTION_LOCK (data->connection);
2414 if (data->delivered)
2417 g_simple_async_result_set_error (data->simple,
2419 G_IO_ERROR_TIMED_OUT,
2420 _("Timeout was reached"));
2422 send_message_with_reply_deliver (data, TRUE);
2425 CONNECTION_UNLOCK (data->connection);
2430 /* ---------------------------------------------------------------------------------------------------- */
2432 /* Called from a user thread, connection's lock is held */
2434 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
2435 GDBusMessage *message,
2436 GDBusSendMessageFlags flags,
2438 volatile guint32 *out_serial,
2439 GCancellable *cancellable,
2440 GAsyncReadyCallback callback,
2443 GSimpleAsyncResult *simple;
2444 SendMessageData *data;
2446 volatile guint32 serial;
2450 if (out_serial == NULL)
2451 out_serial = &serial;
2453 if (timeout_msec == -1)
2454 timeout_msec = 25 * 1000;
2456 simple = g_simple_async_result_new (G_OBJECT (connection),
2459 g_dbus_connection_send_message_with_reply);
2460 g_simple_async_result_set_check_cancellable (simple, cancellable);
2462 if (g_cancellable_is_cancelled (cancellable))
2464 g_simple_async_result_set_error (simple,
2466 G_IO_ERROR_CANCELLED,
2467 _("Operation was cancelled"));
2468 g_simple_async_result_complete_in_idle (simple);
2469 g_object_unref (simple);
2474 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
2476 g_simple_async_result_take_error (simple, error);
2477 g_simple_async_result_complete_in_idle (simple);
2478 g_object_unref (simple);
2482 data = g_new0 (SendMessageData, 1);
2483 data->ref_count = 1;
2484 data->connection = g_object_ref (connection);
2485 data->simple = simple;
2486 data->serial = *out_serial;
2487 data->main_context = g_main_context_ref_thread_default ();
2489 if (cancellable != NULL)
2491 data->cancellable = g_object_ref (cancellable);
2492 data->cancellable_handler_id = g_cancellable_connect (cancellable,
2493 G_CALLBACK (send_message_with_reply_cancelled_cb),
2494 send_message_data_ref (data),
2495 (GDestroyNotify) send_message_data_unref);
2498 if (timeout_msec != G_MAXINT)
2500 data->timeout_source = g_timeout_source_new (timeout_msec);
2501 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
2502 g_source_set_callback (data->timeout_source,
2503 send_message_with_reply_timeout_cb,
2504 send_message_data_ref (data),
2505 (GDestroyNotify) send_message_data_unref);
2506 g_source_attach (data->timeout_source, data->main_context);
2507 g_source_unref (data->timeout_source);
2510 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
2511 GUINT_TO_POINTER (*out_serial),
2519 * g_dbus_connection_send_message_with_reply:
2520 * @connection: a #GDBusConnection
2521 * @message: a #GDBusMessage
2522 * @flags: flags affecting how the message is sent
2523 * @timeout_msec: the timeout in milliseconds, -1 to use the default
2524 * timeout or %G_MAXINT for no timeout
2525 * @out_serial: (out) (allow-none): return location for serial number assigned
2526 * to @message when sending it or %NULL
2527 * @cancellable: (allow-none): a #GCancellable or %NULL
2528 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request
2529 * is satisfied or %NULL if you don't care about the result
2530 * @user_data: The data to pass to @callback
2532 * Asynchronously sends @message to the peer represented by @connection.
2534 * Unless @flags contain the
2535 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2536 * will be assigned by @connection and set on @message via
2537 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2538 * serial number used will be written to this location prior to
2539 * submitting the message to the underlying transport.
2541 * If @connection is closed then the operation will fail with
2542 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2543 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2544 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2546 * This is an asynchronous method. When the operation is finished, @callback
2547 * will be invoked in the
2548 * [thread-default main context][g-main-context-push-thread-default]
2549 * of the thread you are calling this method from. You can then call
2550 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
2551 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
2553 * Note that @message must be unlocked, unless @flags contain the
2554 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2556 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2557 * for an example of how to use this low-level API to send and receive
2558 * UNIX file descriptors.
2563 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
2564 GDBusMessage *message,
2565 GDBusSendMessageFlags flags,
2567 volatile guint32 *out_serial,
2568 GCancellable *cancellable,
2569 GAsyncReadyCallback callback,
2572 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2573 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2574 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2575 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2577 CONNECTION_LOCK (connection);
2578 g_dbus_connection_send_message_with_reply_unlocked (connection,
2586 CONNECTION_UNLOCK (connection);
2590 * g_dbus_connection_send_message_with_reply_finish:
2591 * @connection: a #GDBusConnection
2592 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
2593 * g_dbus_connection_send_message_with_reply()
2594 * @error: teturn location for error or %NULL
2596 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2598 * Note that @error is only set if a local in-process error
2599 * occurred. That is to say that the returned #GDBusMessage object may
2600 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2601 * g_dbus_message_to_gerror() to transcode this to a #GError.
2603 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2604 * for an example of how to use this low-level API to send and receive
2605 * UNIX file descriptors.
2607 * Returns: (transfer full): a locked #GDBusMessage or %NULL if @error is set
2612 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2616 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2617 GDBusMessage *reply;
2619 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2620 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2624 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
2626 if (g_simple_async_result_propagate_error (simple, error))
2629 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
2635 /* ---------------------------------------------------------------------------------------------------- */
2640 GMainContext *context;
2642 } SendMessageSyncData;
2644 /* Called from a user thread, lock is not held */
2646 send_message_with_reply_sync_cb (GDBusConnection *connection,
2650 SendMessageSyncData *data = user_data;
2651 data->res = g_object_ref (res);
2652 g_main_loop_quit (data->loop);
2656 * g_dbus_connection_send_message_with_reply_sync:
2657 * @connection: a #GDBusConnection
2658 * @message: a #GDBusMessage
2659 * @flags: flags affecting how the message is sent.
2660 * @timeout_msec: the timeout in milliseconds, -1 to use the default
2661 * timeout or %G_MAXINT for no timeout
2662 * @out_serial: (out) (allow-none): return location for serial number
2663 * assigned to @message when sending it or %NULL
2664 * @cancellable: (allow-none): a #GCancellable or %NULL
2665 * @error: return location for error or %NULL
2667 * Synchronously sends @message to the peer represented by @connection
2668 * and blocks the calling thread until a reply is received or the
2669 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2670 * for the asynchronous version of this method.
2672 * Unless @flags contain the
2673 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2674 * will be assigned by @connection and set on @message via
2675 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2676 * serial number used will be written to this location prior to
2677 * submitting the message to the underlying transport.
2679 * If @connection is closed then the operation will fail with
2680 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2681 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2682 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2684 * Note that @error is only set if a local in-process error
2685 * occurred. That is to say that the returned #GDBusMessage object may
2686 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2687 * g_dbus_message_to_gerror() to transcode this to a #GError.
2689 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2690 * for an example of how to use this low-level API to send and receive
2691 * UNIX file descriptors.
2693 * Note that @message must be unlocked, unless @flags contain the
2694 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2696 * Returns: (transfer full): a locked #GDBusMessage that is the reply
2697 * to @message or %NULL if @error is set
2702 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2703 GDBusMessage *message,
2704 GDBusSendMessageFlags flags,
2706 volatile guint32 *out_serial,
2707 GCancellable *cancellable,
2710 SendMessageSyncData *data;
2711 GDBusMessage *reply;
2713 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2714 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2715 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2716 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2717 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2719 data = g_new0 (SendMessageSyncData, 1);
2720 data->context = g_main_context_new ();
2721 data->loop = g_main_loop_new (data->context, FALSE);
2723 g_main_context_push_thread_default (data->context);
2725 g_dbus_connection_send_message_with_reply (connection,
2731 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2733 g_main_loop_run (data->loop);
2734 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2738 g_main_context_pop_thread_default (data->context);
2740 g_main_context_unref (data->context);
2741 g_main_loop_unref (data->loop);
2742 g_object_unref (data->res);
2748 /* ---------------------------------------------------------------------------------------------------- */
2752 GDBusMessageFilterFunction func;
2759 GDBusMessageFilterFunction filter_function;
2761 GDestroyNotify user_data_free_func;
2764 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2766 on_worker_message_received (GDBusWorker *worker,
2767 GDBusMessage *message,
2770 GDBusConnection *connection;
2771 FilterCallback *filters;
2776 G_LOCK (message_bus_lock);
2777 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2780 G_UNLOCK (message_bus_lock);
2783 connection = G_DBUS_CONNECTION (user_data);
2784 g_object_ref (connection);
2785 G_UNLOCK (message_bus_lock);
2787 //g_debug ("in on_worker_message_received");
2789 g_object_ref (message);
2790 g_dbus_message_lock (message);
2792 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2794 /* First collect the set of callback functions */
2795 CONNECTION_LOCK (connection);
2796 num_filters = connection->filters->len;
2797 filters = g_new0 (FilterCallback, num_filters);
2798 for (n = 0; n < num_filters; n++)
2800 FilterData *data = connection->filters->pdata[n];
2801 filters[n].func = data->filter_function;
2802 filters[n].user_data = data->user_data;
2804 CONNECTION_UNLOCK (connection);
2806 /* then call the filters in order (without holding the lock) */
2807 for (n = 0; n < num_filters; n++)
2809 message = filters[n].func (connection,
2812 filters[n].user_data);
2813 if (message == NULL)
2815 g_dbus_message_lock (message);
2818 /* Standard dispatch unless the filter ate the message - no need to
2819 * do anything if the message was altered
2821 if (message != NULL)
2823 GDBusMessageType message_type;
2825 message_type = g_dbus_message_get_message_type (message);
2826 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2828 guint32 reply_serial;
2829 SendMessageData *send_message_data;
2831 reply_serial = g_dbus_message_get_reply_serial (message);
2832 CONNECTION_LOCK (connection);
2833 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2834 GUINT_TO_POINTER (reply_serial));
2835 if (send_message_data != NULL)
2837 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2838 send_message_data_deliver_reply_unlocked (send_message_data, message);
2842 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2844 CONNECTION_UNLOCK (connection);
2846 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2848 CONNECTION_LOCK (connection);
2849 distribute_signals (connection, message);
2850 CONNECTION_UNLOCK (connection);
2852 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2854 CONNECTION_LOCK (connection);
2855 distribute_method_call (connection, message);
2856 CONNECTION_UNLOCK (connection);
2860 if (message != NULL)
2861 g_object_unref (message);
2862 g_object_unref (connection);
2866 /* Called in GDBusWorker's thread, lock is not held */
2867 static GDBusMessage *
2868 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2869 GDBusMessage *message,
2872 GDBusConnection *connection;
2873 FilterCallback *filters;
2878 G_LOCK (message_bus_lock);
2879 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2882 G_UNLOCK (message_bus_lock);
2885 connection = G_DBUS_CONNECTION (user_data);
2886 g_object_ref (connection);
2887 G_UNLOCK (message_bus_lock);
2889 //g_debug ("in on_worker_message_about_to_be_sent");
2891 /* First collect the set of callback functions */
2892 CONNECTION_LOCK (connection);
2893 num_filters = connection->filters->len;
2894 filters = g_new0 (FilterCallback, num_filters);
2895 for (n = 0; n < num_filters; n++)
2897 FilterData *data = connection->filters->pdata[n];
2898 filters[n].func = data->filter_function;
2899 filters[n].user_data = data->user_data;
2901 CONNECTION_UNLOCK (connection);
2903 /* then call the filters in order (without holding the lock) */
2904 for (n = 0; n < num_filters; n++)
2906 g_dbus_message_lock (message);
2907 message = filters[n].func (connection,
2910 filters[n].user_data);
2911 if (message == NULL)
2915 g_object_unref (connection);
2921 /* called with connection lock held, in GDBusWorker thread */
2923 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2925 SendMessageData *data = value;
2927 if (data->delivered)
2930 g_simple_async_result_set_error (data->simple,
2933 _("The connection is closed"));
2935 /* Ask send_message_with_reply_deliver not to remove the element from the
2936 * hash table - we're in the middle of a foreach; that would be unsafe.
2937 * Instead, return TRUE from this function so that it gets removed safely.
2939 send_message_with_reply_deliver (data, FALSE);
2943 /* Called in GDBusWorker's thread - we must not block - without lock held */
2945 on_worker_closed (GDBusWorker *worker,
2946 gboolean remote_peer_vanished,
2950 GDBusConnection *connection;
2952 guint old_atomic_flags;
2954 G_LOCK (message_bus_lock);
2955 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2958 G_UNLOCK (message_bus_lock);
2961 connection = G_DBUS_CONNECTION (user_data);
2962 g_object_ref (connection);
2963 G_UNLOCK (message_bus_lock);
2965 //g_debug ("in on_worker_closed: %s", error->message);
2967 CONNECTION_LOCK (connection);
2968 /* Even though this is atomic, we do it inside the lock to avoid breaking
2969 * assumptions in remove_match_rule(). We'd need the lock in a moment
2970 * anyway, so, no loss.
2972 old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
2974 if (!(old_atomic_flags & FLAG_CLOSED))
2976 g_hash_table_foreach_remove (connection->map_method_serial_to_send_message_data, cancel_method_on_close, NULL);
2977 schedule_closed_unlocked (connection, remote_peer_vanished, error);
2979 CONNECTION_UNLOCK (connection);
2981 g_object_unref (connection);
2984 /* ---------------------------------------------------------------------------------------------------- */
2986 /* Determines the biggest set of capabilities we can support on this
2989 * Called with the init_lock held.
2991 static GDBusCapabilityFlags
2992 get_offered_capabilities_max (GDBusConnection *connection)
2994 GDBusCapabilityFlags ret;
2995 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2997 if (G_IS_UNIX_CONNECTION (connection->stream))
2998 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
3003 /* Called in a user thread, lock is not held */
3005 initable_init (GInitable *initable,
3006 GCancellable *cancellable,
3009 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
3012 /* This method needs to be idempotent to work with the singleton
3013 * pattern. See the docs for g_initable_init(). We implement this by
3016 * Unfortunately we can't use the main lock since the on_worker_*()
3017 * callbacks above needs the lock during initialization (for message
3018 * bus connections we do a synchronous Hello() call on the bus).
3020 g_mutex_lock (&connection->init_lock);
3024 /* Make this a no-op if we're already initialized (successfully or
3027 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
3029 ret = (connection->initialization_error == NULL);
3033 /* Because of init_lock, we can't get here twice in different threads */
3034 g_assert (connection->initialization_error == NULL);
3036 /* The user can pass multiple (but mutally exclusive) construct
3039 * - stream (of type GIOStream)
3040 * - address (of type gchar*)
3042 * At the end of the day we end up with a non-NULL GIOStream
3043 * object in connection->stream.
3045 if (connection->address != NULL)
3047 g_assert (connection->stream == NULL);
3049 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
3050 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
3052 g_set_error_literal (&connection->initialization_error,
3054 G_IO_ERROR_INVALID_ARGUMENT,
3055 _("Unsupported flags encountered when constructing a client-side connection"));
3059 connection->stream = g_dbus_address_get_stream_sync (connection->address,
3060 NULL, /* TODO: out_guid */
3062 &connection->initialization_error);
3063 if (connection->stream == NULL)
3066 else if (connection->stream != NULL)
3072 g_assert_not_reached ();
3075 /* [KDBUS] Skip authentication process for kdbus transport */
3076 if (G_IS_KDBUS_CONNECTION (connection->stream))
3081 /* Authenticate the connection */
3082 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
3084 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
3085 g_assert (connection->guid != NULL);
3086 connection->auth = _g_dbus_auth_new (connection->stream);
3087 if (!_g_dbus_auth_run_server (connection->auth,
3088 connection->authentication_observer,
3090 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
3091 get_offered_capabilities_max (connection),
3092 &connection->capabilities,
3093 &connection->credentials,
3095 &connection->initialization_error))
3098 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
3100 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
3101 g_assert (connection->guid == NULL);
3102 connection->auth = _g_dbus_auth_new (connection->stream);
3103 connection->guid = _g_dbus_auth_run_client (connection->auth,
3104 connection->authentication_observer,
3105 get_offered_capabilities_max (connection),
3106 &connection->capabilities,
3108 &connection->initialization_error);
3109 if (connection->guid == NULL)
3113 if (connection->authentication_observer != NULL)
3115 g_object_unref (connection->authentication_observer);
3116 connection->authentication_observer = NULL;
3121 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
3123 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
3126 /* We want all IO operations to be non-blocking since they happen in
3127 * the worker thread which is shared by _all_ connections.
3129 if (G_IS_SOCKET_CONNECTION (connection->stream))
3131 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
3135 G_LOCK (message_bus_lock);
3136 if (alive_connections == NULL)
3137 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
3138 g_hash_table_insert (alive_connections, connection, connection);
3139 G_UNLOCK (message_bus_lock);
3141 connection->worker = _g_dbus_worker_new (connection->stream,
3142 connection->capabilities,
3143 ((connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) != 0),
3144 on_worker_message_received,
3145 on_worker_message_about_to_be_sent,
3149 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
3150 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3152 GVariant *hello_result;
3154 /* we could lift this restriction by adding code in gdbusprivate.c */
3155 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
3157 g_set_error_literal (&connection->initialization_error,
3160 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
3164 if (G_IS_KDBUS_CONNECTION (connection->stream))
3166 hello_result = _g_kdbus_Hello (connection->stream, &connection->initialization_error);
3170 hello_result = g_dbus_connection_call_sync (connection,
3171 "org.freedesktop.DBus", /* name */
3172 "/org/freedesktop/DBus", /* path */
3173 "org.freedesktop.DBus", /* interface */
3175 NULL, /* parameters */
3176 G_VARIANT_TYPE ("(s)"),
3177 CALL_FLAGS_INITIALIZING,
3179 NULL, /* TODO: cancellable */
3180 &connection->initialization_error);
3183 if (hello_result == NULL)
3186 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
3187 g_variant_unref (hello_result);
3188 //g_debug ("unique name is '%s'", connection->bus_unique_name);
3195 g_assert (connection->initialization_error != NULL);
3196 g_propagate_error (error, g_error_copy (connection->initialization_error));
3199 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
3200 g_mutex_unlock (&connection->init_lock);
3206 initable_iface_init (GInitableIface *initable_iface)
3208 initable_iface->init = initable_init;
3211 /* ---------------------------------------------------------------------------------------------------- */
3214 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
3219 /* ---------------------------------------------------------------------------------------------------- */
3222 * g_dbus_connection_new:
3223 * @stream: a #GIOStream
3224 * @guid: (allow-none): the GUID to use if a authenticating as a server or %NULL
3225 * @flags: flags describing how to make the connection
3226 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3227 * @cancellable: (allow-none): a #GCancellable or %NULL
3228 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
3229 * @user_data: the data to pass to @callback
3231 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
3232 * with the end represented by @stream.
3234 * If @stream is a #GSocketConnection, then the corresponding #GSocket
3235 * will be put into non-blocking mode.
3237 * The D-Bus connection will interact with @stream from a worker thread.
3238 * As a result, the caller should not interact with @stream after this
3239 * method has been called, except by calling g_object_unref() on it.
3241 * If @observer is not %NULL it may be used to control the
3242 * authentication process.
3244 * When the operation is finished, @callback will be invoked. You can
3245 * then call g_dbus_connection_new_finish() to get the result of the
3248 * This is a asynchronous failable constructor. See
3249 * g_dbus_connection_new_sync() for the synchronous
3255 g_dbus_connection_new (GIOStream *stream,
3257 GDBusConnectionFlags flags,
3258 GDBusAuthObserver *observer,
3259 GCancellable *cancellable,
3260 GAsyncReadyCallback callback,
3263 g_return_if_fail (G_IS_IO_STREAM (stream));
3264 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
3272 "authentication-observer", observer,
3277 * g_dbus_connection_new_finish:
3278 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback
3279 * passed to g_dbus_connection_new().
3280 * @error: return location for error or %NULL
3282 * Finishes an operation started with g_dbus_connection_new().
3284 * Returns: a #GDBusConnection or %NULL if @error is set. Free
3285 * with g_object_unref().
3290 g_dbus_connection_new_finish (GAsyncResult *res,
3294 GObject *source_object;
3296 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
3297 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3299 source_object = g_async_result_get_source_object (res);
3300 g_assert (source_object != NULL);
3301 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
3304 g_object_unref (source_object);
3306 return G_DBUS_CONNECTION (object);
3312 * g_dbus_connection_new_sync:
3313 * @stream: a #GIOStream
3314 * @guid: (allow-none): the GUID to use if a authenticating as a server or %NULL
3315 * @flags: flags describing how to make the connection
3316 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3317 * @cancellable: (allow-none): a #GCancellable or %NULL
3318 * @error: return location for error or %NULL
3320 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
3321 * with the end represented by @stream.
3323 * If @stream is a #GSocketConnection, then the corresponding #GSocket
3324 * will be put into non-blocking mode.
3326 * The D-Bus connection will interact with @stream from a worker thread.
3327 * As a result, the caller should not interact with @stream after this
3328 * method has been called, except by calling g_object_unref() on it.
3330 * If @observer is not %NULL it may be used to control the
3331 * authentication process.
3333 * This is a synchronous failable constructor. See
3334 * g_dbus_connection_new() for the asynchronous version.
3336 * Returns: a #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
3341 g_dbus_connection_new_sync (GIOStream *stream,
3343 GDBusConnectionFlags flags,
3344 GDBusAuthObserver *observer,
3345 GCancellable *cancellable,
3348 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
3349 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3350 return g_initable_new (G_TYPE_DBUS_CONNECTION,
3356 "authentication-observer", observer,
3360 /* ---------------------------------------------------------------------------------------------------- */
3363 * g_dbus_connection_new_for_address:
3364 * @address: a D-Bus address
3365 * @flags: flags describing how to make the connection
3366 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3367 * @cancellable: (allow-none): a #GCancellable or %NULL
3368 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
3369 * @user_data: the data to pass to @callback
3371 * Asynchronously connects and sets up a D-Bus client connection for
3372 * exchanging D-Bus messages with an endpoint specified by @address
3373 * which must be in the D-Bus address format.
3375 * This constructor can only be used to initiate client-side
3376 * connections - use g_dbus_connection_new() if you need to act as the
3377 * server. In particular, @flags cannot contain the
3378 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
3379 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
3381 * When the operation is finished, @callback will be invoked. You can
3382 * then call g_dbus_connection_new_finish() to get the result of the
3385 * If @observer is not %NULL it may be used to control the
3386 * authentication process.
3388 * This is a asynchronous failable constructor. See
3389 * g_dbus_connection_new_for_address_sync() for the synchronous
3395 g_dbus_connection_new_for_address (const gchar *address,
3396 GDBusConnectionFlags flags,
3397 GDBusAuthObserver *observer,
3398 GCancellable *cancellable,
3399 GAsyncReadyCallback callback,
3402 g_return_if_fail (address != NULL);
3403 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
3410 "authentication-observer", observer,
3415 * g_dbus_connection_new_for_address_finish:
3416 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
3417 * to g_dbus_connection_new()
3418 * @error: return location for error or %NULL
3420 * Finishes an operation started with g_dbus_connection_new_for_address().
3422 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
3428 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
3432 GObject *source_object;
3434 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
3435 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3437 source_object = g_async_result_get_source_object (res);
3438 g_assert (source_object != NULL);
3439 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
3442 g_object_unref (source_object);
3444 return G_DBUS_CONNECTION (object);
3450 * g_dbus_connection_new_for_address_sync:
3451 * @address: a D-Bus address
3452 * @flags: flags describing how to make the connection
3453 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3454 * @cancellable: (allow-none): a #GCancellable or %NULL
3455 * @error: return location for error or %NULL
3457 * Synchronously connects and sets up a D-Bus client connection for
3458 * exchanging D-Bus messages with an endpoint specified by @address
3459 * which must be in the D-Bus address format.
3461 * This constructor can only be used to initiate client-side
3462 * connections - use g_dbus_connection_new_sync() if you need to act
3463 * as the server. In particular, @flags cannot contain the
3464 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
3465 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
3467 * This is a synchronous failable constructor. See
3468 * g_dbus_connection_new_for_address() for the asynchronous version.
3470 * If @observer is not %NULL it may be used to control the
3471 * authentication process.
3473 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
3479 g_dbus_connection_new_for_address_sync (const gchar *address,
3480 GDBusConnectionFlags flags,
3481 GDBusAuthObserver *observer,
3482 GCancellable *cancellable,
3485 g_return_val_if_fail (address != NULL, NULL);
3486 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3487 return g_initable_new (G_TYPE_DBUS_CONNECTION,
3492 "authentication-observer", observer,
3496 /* ---------------------------------------------------------------------------------------------------- */
3499 * g_dbus_connection_set_exit_on_close:
3500 * @connection: a #GDBusConnection
3501 * @exit_on_close: whether the process should be terminated
3502 * when @connection is closed by the remote peer
3504 * Sets whether the process should be terminated when @connection is
3505 * closed by the remote peer. See #GDBusConnection:exit-on-close for
3508 * Note that this function should be used with care. Most modern UNIX
3509 * desktops tie the notion of a user session the session bus, and expect
3510 * all of a users applications to quit when their bus connection goes away.
3511 * If you are setting @exit_on_close to %FALSE for the shared session
3512 * bus connection, you should make sure that your application exits
3513 * when the user session ends.
3518 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
3519 gboolean exit_on_close)
3521 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3524 g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
3526 g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
3531 * g_dbus_connection_get_exit_on_close:
3532 * @connection: a #GDBusConnection
3534 * Gets whether the process is terminated when @connection is
3535 * closed by the remote peer. See
3536 * #GDBusConnection:exit-on-close for more details.
3538 * Returns: whether the process is terminated when @connection is
3539 * closed by the remote peer
3544 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
3546 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3548 if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
3555 * g_dbus_connection_get_guid:
3556 * @connection: a #GDBusConnection
3558 * The GUID of the peer performing the role of server when
3559 * authenticating. See #GDBusConnection:guid for more details.
3561 * Returns: The GUID. Do not free this string, it is owned by
3567 g_dbus_connection_get_guid (GDBusConnection *connection)
3569 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3570 return connection->guid;
3574 * g_dbus_connection_get_unique_name:
3575 * @connection: a #GDBusConnection
3577 * Gets the unique name of @connection as assigned by the message
3578 * bus. This can also be used to figure out if @connection is a
3579 * message bus connection.
3581 * Returns: the unique name or %NULL if @connection is not a message
3582 * bus connection. Do not free this string, it is owned by
3588 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3590 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3592 /* do not use g_return_val_if_fail(), we want the memory barrier */
3593 if (!check_initialized (connection))
3596 return connection->bus_unique_name;
3600 * g_dbus_connection_get_peer_credentials:
3601 * @connection: a #GDBusConnection
3603 * Gets the credentials of the authenticated peer. This will always
3604 * return %NULL unless @connection acted as a server
3605 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3606 * when set up and the client passed credentials as part of the
3607 * authentication process.
3609 * In a message bus setup, the message bus is always the server and
3610 * each application is a client. So this method will always return
3611 * %NULL for message bus clients.
3613 * Returns: (transfer none): a #GCredentials or %NULL if not available.
3614 * Do not free this object, it is owned by @connection.
3619 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3621 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3623 /* do not use g_return_val_if_fail(), we want the memory barrier */
3624 if (!check_initialized (connection))
3627 return connection->credentials;
3630 /* ---------------------------------------------------------------------------------------------------- */
3632 static guint _global_filter_id = 1;
3635 * g_dbus_connection_add_filter:
3636 * @connection: a #GDBusConnection
3637 * @filter_function: a filter function
3638 * @user_data: user data to pass to @filter_function
3639 * @user_data_free_func: function to free @user_data with when filter
3640 * is removed or %NULL
3642 * Adds a message filter. Filters are handlers that are run on all
3643 * incoming and outgoing messages, prior to standard dispatch. Filters
3644 * are run in the order that they were added. The same handler can be
3645 * added as a filter more than once, in which case it will be run more
3646 * than once. Filters added during a filter callback won't be run on
3647 * the message being processed. Filter functions are allowed to modify
3648 * and even drop messages.
3650 * Note that filters are run in a dedicated message handling thread so
3651 * they can't block and, generally, can't do anything but signal a
3652 * worker thread. Also note that filters are rarely needed - use API
3653 * such as g_dbus_connection_send_message_with_reply(),
3654 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3656 * If a filter consumes an incoming message the message is not
3657 * dispatched anywhere else - not even the standard dispatch machinery
3658 * (that API such as g_dbus_connection_signal_subscribe() and
3659 * g_dbus_connection_send_message_with_reply() relies on) will see the
3660 * message. Similary, if a filter consumes an outgoing message, the
3661 * message will not be sent to the other peer.
3663 * Returns: a filter identifier that can be used with
3664 * g_dbus_connection_remove_filter()
3669 g_dbus_connection_add_filter (GDBusConnection *connection,
3670 GDBusMessageFilterFunction filter_function,
3672 GDestroyNotify user_data_free_func)
3676 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3677 g_return_val_if_fail (filter_function != NULL, 0);
3678 g_return_val_if_fail (check_initialized (connection), 0);
3680 CONNECTION_LOCK (connection);
3681 data = g_new0 (FilterData, 1);
3682 data->id = _global_filter_id++; /* TODO: overflow etc. */
3683 data->filter_function = filter_function;
3684 data->user_data = user_data;
3685 data->user_data_free_func = user_data_free_func;
3686 g_ptr_array_add (connection->filters, data);
3687 CONNECTION_UNLOCK (connection);
3692 /* only called from finalize(), removes all filters */
3694 purge_all_filters (GDBusConnection *connection)
3697 for (n = 0; n < connection->filters->len; n++)
3699 FilterData *data = connection->filters->pdata[n];
3700 if (data->user_data_free_func != NULL)
3701 data->user_data_free_func (data->user_data);
3707 * g_dbus_connection_remove_filter:
3708 * @connection: a #GDBusConnection
3709 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3716 g_dbus_connection_remove_filter (GDBusConnection *connection,
3720 FilterData *to_destroy;
3722 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3723 g_return_if_fail (check_initialized (connection));
3725 CONNECTION_LOCK (connection);
3727 for (n = 0; n < connection->filters->len; n++)
3729 FilterData *data = connection->filters->pdata[n];
3730 if (data->id == filter_id)
3732 g_ptr_array_remove_index (connection->filters, n);
3737 CONNECTION_UNLOCK (connection);
3739 /* do free without holding lock */
3740 if (to_destroy != NULL)
3742 if (to_destroy->user_data_free_func != NULL)
3743 to_destroy->user_data_free_func (to_destroy->user_data);
3744 g_free (to_destroy);
3748 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3752 /* ---------------------------------------------------------------------------------------------------- */
3758 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3759 gchar *interface_name;
3763 GDBusSignalFlags flags;
3764 GArray *subscribers;
3769 GDBusSignalCallback callback;
3771 GDestroyNotify user_data_free_func;
3773 GMainContext *context;
3777 signal_data_free (SignalData *signal_data)
3779 g_free (signal_data->rule);
3780 g_free (signal_data->sender);
3781 g_free (signal_data->sender_unique_name);
3782 g_free (signal_data->interface_name);
3783 g_free (signal_data->member);
3784 g_free (signal_data->object_path);
3785 g_free (signal_data->arg0);
3786 g_array_free (signal_data->subscribers, TRUE);
3787 g_free (signal_data);
3791 args_to_rule (const gchar *sender,
3792 const gchar *interface_name,
3793 const gchar *member,
3794 const gchar *object_path,
3796 GDBusSignalFlags flags)
3800 rule = g_string_new ("type='signal'");
3801 if (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE)
3802 g_string_prepend_c (rule, '-');
3804 g_string_append_printf (rule, ",sender='%s'", sender);
3805 if (interface_name != NULL)
3806 g_string_append_printf (rule, ",interface='%s'", interface_name);
3808 g_string_append_printf (rule, ",member='%s'", member);
3809 if (object_path != NULL)
3810 g_string_append_printf (rule, ",path='%s'", object_path);
3814 if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3815 g_string_append_printf (rule, ",arg0path='%s'", arg0);
3816 else if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3817 g_string_append_printf (rule, ",arg0namespace='%s'", arg0);
3819 g_string_append_printf (rule, ",arg0='%s'", arg0);
3822 return g_string_free (rule, FALSE);
3825 static guint _global_subscriber_id = 1;
3826 static guint _global_registration_id = 1;
3827 static guint _global_subtree_registration_id = 1;
3829 /* ---------------------------------------------------------------------------------------------------- */
3831 /* Called in a user thread, lock is held */
3833 add_match_rule (GDBusConnection *connection,
3834 const gchar *match_rule)
3837 GDBusMessage *message;
3839 if (match_rule[0] == '-')
3842 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3843 "/org/freedesktop/DBus", /* path */
3844 "org.freedesktop.DBus", /* interface */
3846 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3848 if (!g_dbus_connection_send_message_unlocked (connection,
3850 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3854 g_critical ("Error while sending AddMatch() message: %s", error->message);
3855 g_error_free (error);
3857 g_object_unref (message);
3860 /* ---------------------------------------------------------------------------------------------------- */
3862 /* Called in a user thread, lock is held */
3864 remove_match_rule (GDBusConnection *connection,
3865 const gchar *match_rule)
3868 GDBusMessage *message;
3870 if (match_rule[0] == '-')
3873 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3874 "/org/freedesktop/DBus", /* path */
3875 "org.freedesktop.DBus", /* interface */
3877 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3880 if (!g_dbus_connection_send_message_unlocked (connection,
3882 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3886 /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
3887 * critical; but we're holding the lock, and our caller checked whether
3888 * we were already closed, so we can't get that error.
3890 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3891 g_error_free (error);
3893 g_object_unref (message);
3896 /* ---------------------------------------------------------------------------------------------------- */
3899 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3901 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3902 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3903 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3904 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3905 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3908 /* ---------------------------------------------------------------------------------------------------- */
3911 * g_dbus_connection_signal_subscribe:
3912 * @connection: a #GDBusConnection
3913 * @sender: (allow-none): sender name to match on (unique or well-known name)
3914 * or %NULL to listen from all senders
3915 * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3916 * match on all interfaces
3917 * @member: (allow-none): D-Bus signal name to match on or %NULL to match on
3919 * @object_path: (allow-none): object path to match on or %NULL to match on
3921 * @arg0: (allow-none): contents of first string argument to match on or %NULL
3922 * to match on all kinds of arguments
3923 * @flags: flags describing how to subscribe to the signal (currently unused)
3924 * @callback: callback to invoke when there is a signal matching the requested data
3925 * @user_data: user data to pass to @callback
3926 * @user_data_free_func: (allow-none): function to free @user_data with when
3927 * subscription is removed or %NULL
3929 * Subscribes to signals on @connection and invokes @callback with a whenever
3930 * the signal is received. Note that @callback will be invoked in the
3931 * [thread-default main context][g-main-context-push-thread-default]
3932 * of the thread you are calling this method from.
3934 * If @connection is not a message bus connection, @sender must be
3937 * If @sender is a well-known name note that @callback is invoked with
3938 * the unique name for the owner of @sender, not the well-known name
3939 * as one would expect. This is because the message bus rewrites the
3940 * name. As such, to avoid certain race conditions, users should be
3941 * tracking the name owner of the well-known name and use that when
3942 * processing the received signal.
3944 * If one of %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE or
3945 * %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH are given, @arg0 is
3946 * interpreted as part of a namespace or path. The first argument
3947 * of a signal is matched against that part as specified by D-Bus.
3949 * Returns: a subscription identifier that can be used with g_dbus_connection_signal_unsubscribe()
3954 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3955 const gchar *sender,
3956 const gchar *interface_name,
3957 const gchar *member,
3958 const gchar *object_path,
3960 GDBusSignalFlags flags,
3961 GDBusSignalCallback callback,
3963 GDestroyNotify user_data_free_func)
3966 SignalData *signal_data;
3967 SignalSubscriber subscriber;
3968 GPtrArray *signal_data_array;
3969 const gchar *sender_unique_name;
3971 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3972 * an OOM condition. We might want to change that but that would involve making
3973 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3974 * handle that. And there's really no sensible way of handling this short of retrying
3975 * to add the match rule... and then there's the little thing that, hey, maybe there's
3976 * a reason the bus in an OOM condition.
3978 * Doable, but not really sure it's worth it...
3981 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3982 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3983 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3984 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3985 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3986 g_return_val_if_fail (callback != NULL, 0);
3987 g_return_val_if_fail (check_initialized (connection), 0);
3988 g_return_val_if_fail (!((flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH) && (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)), 0);
3989 g_return_val_if_fail (!(arg0 == NULL && (flags & (G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH | G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE))), 0);
3991 CONNECTION_LOCK (connection);
3993 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3994 * with a '-' character to prefix the rule (which will otherwise be
3997 * This allows us to hash the rule and do our lifecycle tracking in
3998 * the usual way, but the '-' prevents the match rule from ever
3999 * actually being send to the bus (either for add or remove).
4001 rule = args_to_rule (sender, interface_name, member, object_path, arg0, flags);
4003 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
4004 sender_unique_name = sender;
4006 sender_unique_name = "";
4008 subscriber.callback = callback;
4009 subscriber.user_data = user_data;
4010 subscriber.user_data_free_func = user_data_free_func;
4011 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
4012 subscriber.context = g_main_context_ref_thread_default ();
4014 /* see if we've already have this rule */
4015 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
4016 if (signal_data != NULL)
4018 g_array_append_val (signal_data->subscribers, subscriber);
4023 signal_data = g_new0 (SignalData, 1);
4024 signal_data->rule = rule;
4025 signal_data->sender = g_strdup (sender);
4026 signal_data->sender_unique_name = g_strdup (sender_unique_name);
4027 signal_data->interface_name = g_strdup (interface_name);
4028 signal_data->member = g_strdup (member);
4029 signal_data->object_path = g_strdup (object_path);
4030 signal_data->arg0 = g_strdup (arg0);
4031 signal_data->flags = flags;
4032 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
4033 g_array_append_val (signal_data->subscribers, subscriber);
4035 g_hash_table_insert (connection->map_rule_to_signal_data,
4039 /* Add the match rule to the bus...
4041 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
4042 * always send such messages to us.
4044 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
4046 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
4047 add_match_rule (connection, signal_data->rule);
4050 if (G_IS_KDBUS_CONNECTION (connection->stream))
4052 if (g_strcmp0 (signal_data->member, "NameAcquired") == 0)
4053 _g_kdbus_subscribe_name_acquired (connection, arg0);
4054 else if (g_strcmp0 (signal_data->member, "NameLost") == 0)
4055 _g_kdbus_subscribe_name_lost (connection, arg0);
4060 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
4061 signal_data->sender_unique_name);
4062 if (signal_data_array == NULL)
4064 signal_data_array = g_ptr_array_new ();
4065 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
4066 g_strdup (signal_data->sender_unique_name),
4069 g_ptr_array_add (signal_data_array, signal_data);
4072 g_hash_table_insert (connection->map_id_to_signal_data,
4073 GUINT_TO_POINTER (subscriber.id),
4076 CONNECTION_UNLOCK (connection);
4078 return subscriber.id;
4081 /* ---------------------------------------------------------------------------------------------------- */
4083 /* called in any thread */
4084 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
4086 unsubscribe_id_internal (GDBusConnection *connection,
4087 guint subscription_id,
4088 GArray *out_removed_subscribers)
4090 SignalData *signal_data;
4091 GPtrArray *signal_data_array;
4094 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
4095 GUINT_TO_POINTER (subscription_id));
4096 if (signal_data == NULL)
4098 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
4102 for (n = 0; n < signal_data->subscribers->len; n++)
4104 SignalSubscriber *subscriber;
4106 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
4107 if (subscriber->id != subscription_id)
4110 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
4111 GUINT_TO_POINTER (subscription_id)));
4112 g_array_append_val (out_removed_subscribers, *subscriber);
4113 g_array_remove_index (signal_data->subscribers, n);
4115 if (signal_data->subscribers->len == 0)
4117 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
4119 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
4120 signal_data->sender_unique_name);
4121 g_warn_if_fail (signal_data_array != NULL);
4122 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
4124 if (signal_data_array->len == 0)
4126 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
4127 signal_data->sender_unique_name));
4130 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
4131 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
4132 !is_signal_data_for_name_lost_or_acquired (signal_data) &&
4133 !g_dbus_connection_is_closed (connection) &&
4134 !connection->finalizing)
4136 /* The check for g_dbus_connection_is_closed() means that
4137 * sending the RemoveMatch message can't fail with
4138 * G_IO_ERROR_CLOSED, because we're holding the lock,
4139 * so on_worker_closed() can't happen between the check we just
4140 * did, and releasing the lock later.
4142 remove_match_rule (connection, signal_data->rule);
4146 if (G_IS_KDBUS_CONNECTION (connection->stream))
4148 if (g_strcmp0 (signal_data->member, "NameAcquired") == 0)
4149 _g_kdbus_unsubscribe_name_acquired (connection);
4150 else if (g_strcmp0 (signal_data->member, "NameLost") == 0)
4151 _g_kdbus_unsubscribe_name_lost (connection);
4155 signal_data_free (signal_data);
4161 g_assert_not_reached ();
4168 * g_dbus_connection_signal_unsubscribe:
4169 * @connection: a #GDBusConnection
4170 * @subscription_id: a subscription id obtained from
4171 * g_dbus_connection_signal_subscribe()
4173 * Unsubscribes from signals.
4178 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
4179 guint subscription_id)
4181 GArray *subscribers;
4184 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4185 g_return_if_fail (check_initialized (connection));
4187 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
4189 CONNECTION_LOCK (connection);
4190 unsubscribe_id_internal (connection,
4193 CONNECTION_UNLOCK (connection);
4196 g_assert (subscribers->len == 0 || subscribers->len == 1);
4198 /* call GDestroyNotify without lock held */
4199 for (n = 0; n < subscribers->len; n++)
4201 SignalSubscriber *subscriber;
4202 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
4203 call_destroy_notify (subscriber->context,
4204 subscriber->user_data_free_func,
4205 subscriber->user_data);
4206 g_main_context_unref (subscriber->context);
4209 g_array_free (subscribers, TRUE);
4212 /* ---------------------------------------------------------------------------------------------------- */
4216 guint subscription_id;
4217 GDBusSignalCallback callback;
4219 GDBusMessage *message;
4220 GDBusConnection *connection;
4221 const gchar *sender;
4223 const gchar *interface;
4224 const gchar *member;
4227 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
4231 emit_signal_instance_in_idle_cb (gpointer data)
4233 SignalInstance *signal_instance = data;
4234 GVariant *parameters;
4235 gboolean has_subscription;
4237 parameters = g_dbus_message_get_body (signal_instance->message);
4238 if (parameters == NULL)
4240 parameters = g_variant_new ("()");
4241 g_variant_ref_sink (parameters);
4245 g_variant_ref (parameters);
4249 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
4250 signal_instance->subscription_id,
4251 signal_instance->sender,
4252 signal_instance->path,
4253 signal_instance->interface,
4254 signal_instance->member,
4255 g_variant_print (parameters, TRUE));
4258 /* Careful here, don't do the callback if we no longer has the subscription */
4259 CONNECTION_LOCK (signal_instance->connection);
4260 has_subscription = FALSE;
4261 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
4262 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
4263 has_subscription = TRUE;
4264 CONNECTION_UNLOCK (signal_instance->connection);
4266 if (has_subscription)
4267 signal_instance->callback (signal_instance->connection,
4268 signal_instance->sender,
4269 signal_instance->path,
4270 signal_instance->interface,
4271 signal_instance->member,
4273 signal_instance->user_data);
4275 g_variant_unref (parameters);
4281 signal_instance_free (SignalInstance *signal_instance)
4283 g_object_unref (signal_instance->message);
4284 g_object_unref (signal_instance->connection);
4285 g_free (signal_instance);
4289 namespace_rule_matches (const gchar *namespace,
4295 len_namespace = strlen (namespace);
4296 len_name = strlen (name);
4298 if (len_name < len_namespace)
4301 if (memcmp (namespace, name, len_namespace) != 0)
4304 return len_namespace == len_name || name[len_namespace] == '.';
4308 path_rule_matches (const gchar *path_a,
4309 const gchar *path_b)
4313 len_a = strlen (path_a);
4314 len_b = strlen (path_b);
4316 if (len_a < len_b && path_a[len_a - 1] != '/')
4319 if (len_b < len_a && path_b[len_b - 1] != '/')
4322 return memcmp (path_a, path_b, MIN (len_a, len_b)) == 0;
4325 /* called in GDBusWorker thread WITH lock held */
4327 schedule_callbacks (GDBusConnection *connection,
4328 GPtrArray *signal_data_array,
4329 GDBusMessage *message,
4330 const gchar *sender)
4333 const gchar *interface;
4334 const gchar *member;
4343 interface = g_dbus_message_get_interface (message);
4344 member = g_dbus_message_get_member (message);
4345 path = g_dbus_message_get_path (message);
4346 arg0 = g_dbus_message_get_arg0 (message);
4349 g_print ("In schedule_callbacks:\n"
4351 " interface = '%s'\n"
4362 /* TODO: if this is slow, then we can change signal_data_array into
4363 * map_object_path_to_signal_data_array or something.
4365 for (n = 0; n < signal_data_array->len; n++)
4367 SignalData *signal_data = signal_data_array->pdata[n];
4369 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
4372 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
4375 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
4378 if (signal_data->arg0 != NULL)
4383 if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
4385 if (!namespace_rule_matches (signal_data->arg0, arg0))
4388 else if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
4390 if (!path_rule_matches (signal_data->arg0, arg0))
4393 else if (!g_str_equal (signal_data->arg0, arg0))
4397 for (m = 0; m < signal_data->subscribers->len; m++)
4399 SignalSubscriber *subscriber;
4400 GSource *idle_source;
4401 SignalInstance *signal_instance;
4403 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
4405 signal_instance = g_new0 (SignalInstance, 1);
4406 signal_instance->subscription_id = subscriber->id;
4407 signal_instance->callback = subscriber->callback;
4408 signal_instance->user_data = subscriber->user_data;
4409 signal_instance->message = g_object_ref (message);
4410 signal_instance->connection = g_object_ref (connection);
4411 signal_instance->sender = sender;
4412 signal_instance->path = path;
4413 signal_instance->interface = interface;
4414 signal_instance->member = member;
4416 idle_source = g_idle_source_new ();
4417 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4418 g_source_set_callback (idle_source,
4419 emit_signal_instance_in_idle_cb,
4421 (GDestroyNotify) signal_instance_free);
4422 g_source_set_name (idle_source, "[gio] emit_signal_instance_in_idle_cb");
4423 g_source_attach (idle_source, subscriber->context);
4424 g_source_unref (idle_source);
4429 /* called in GDBusWorker thread with lock held */
4431 distribute_signals (GDBusConnection *connection,
4432 GDBusMessage *message)
4434 GPtrArray *signal_data_array;
4435 const gchar *sender;
4437 sender = g_dbus_message_get_sender (message);
4439 if (G_UNLIKELY (_g_dbus_debug_signal ()))
4441 _g_dbus_debug_print_lock ();
4442 g_print ("========================================================================\n"
4443 "GDBus-debug:Signal:\n"
4444 " <<<< RECEIVED SIGNAL %s.%s\n"
4446 " sent by name %s\n",
4447 g_dbus_message_get_interface (message),
4448 g_dbus_message_get_member (message),
4449 g_dbus_message_get_path (message),
4450 sender != NULL ? sender : "(none)");
4451 _g_dbus_debug_print_unlock ();
4454 /* collect subscribers that match on sender */
4457 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
4458 if (signal_data_array != NULL)
4459 schedule_callbacks (connection, signal_data_array, message, sender);
4462 /* collect subscribers not matching on sender */
4463 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
4464 if (signal_data_array != NULL)
4465 schedule_callbacks (connection, signal_data_array, message, sender);
4468 /* ---------------------------------------------------------------------------------------------------- */
4470 /* only called from finalize(), removes all subscriptions */
4472 purge_all_signal_subscriptions (GDBusConnection *connection)
4474 GHashTableIter iter;
4477 GArray *subscribers;
4480 ids = g_array_new (FALSE, FALSE, sizeof (guint));
4481 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
4482 while (g_hash_table_iter_next (&iter, &key, NULL))
4484 guint subscription_id = GPOINTER_TO_UINT (key);
4485 g_array_append_val (ids, subscription_id);
4488 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
4489 for (n = 0; n < ids->len; n++)
4491 guint subscription_id = g_array_index (ids, guint, n);
4492 unsubscribe_id_internal (connection,
4496 g_array_free (ids, TRUE);
4498 /* call GDestroyNotify without lock held */
4499 for (n = 0; n < subscribers->len; n++)
4501 SignalSubscriber *subscriber;
4502 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
4503 call_destroy_notify (subscriber->context,
4504 subscriber->user_data_free_func,
4505 subscriber->user_data);
4506 g_main_context_unref (subscriber->context);
4509 g_array_free (subscribers, TRUE);
4512 /* ---------------------------------------------------------------------------------------------------- */
4514 static GDBusInterfaceVTable *
4515 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
4517 /* Don't waste memory by copying padding - remember to update this
4518 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
4520 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4524 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
4529 /* ---------------------------------------------------------------------------------------------------- */
4531 static GDBusSubtreeVTable *
4532 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
4534 /* Don't waste memory by copying padding - remember to update this
4535 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
4537 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4541 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
4546 /* ---------------------------------------------------------------------------------------------------- */
4548 struct ExportedObject
4551 GDBusConnection *connection;
4553 /* maps gchar* -> ExportedInterface* */
4554 GHashTable *map_if_name_to_ei;
4557 /* only called with lock held */
4559 exported_object_free (ExportedObject *eo)
4561 g_free (eo->object_path);
4562 g_hash_table_unref (eo->map_if_name_to_ei);
4571 gchar *interface_name;
4572 GDBusInterfaceVTable *vtable;
4573 GDBusInterfaceInfo *interface_info;
4575 GMainContext *context;
4577 GDestroyNotify user_data_free_func;
4578 } ExportedInterface;
4580 /* called with lock held */
4582 exported_interface_free (ExportedInterface *ei)
4584 g_dbus_interface_info_cache_release (ei->interface_info);
4585 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
4587 call_destroy_notify (ei->context,
4588 ei->user_data_free_func,
4591 g_main_context_unref (ei->context);
4593 g_free (ei->interface_name);
4594 _g_dbus_interface_vtable_free (ei->vtable);
4598 /* ---------------------------------------------------------------------------------------------------- */
4600 /* Convenience function to check if @registration_id (if not zero) or
4601 * @subtree_registration_id (if not zero) has been unregistered. If
4602 * so, returns %TRUE.
4604 * May be called by any thread. Caller must *not* hold lock.
4607 has_object_been_unregistered (GDBusConnection *connection,
4608 guint registration_id,
4609 guint subtree_registration_id)
4613 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4617 CONNECTION_LOCK (connection);
4618 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
4619 GUINT_TO_POINTER (registration_id)) == NULL)
4623 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
4624 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
4628 CONNECTION_UNLOCK (connection);
4633 /* ---------------------------------------------------------------------------------------------------- */
4637 GDBusConnection *connection;
4638 GDBusMessage *message;
4640 const gchar *property_name;
4641 const GDBusInterfaceVTable *vtable;
4642 GDBusInterfaceInfo *interface_info;
4643 const GDBusPropertyInfo *property_info;
4644 guint registration_id;
4645 guint subtree_registration_id;
4649 property_data_free (PropertyData *data)
4651 g_object_unref (data->connection);
4652 g_object_unref (data->message);
4656 /* called in thread where object was registered - no locks held */
4658 invoke_get_property_in_idle_cb (gpointer _data)
4660 PropertyData *data = _data;
4663 GDBusMessage *reply;
4665 if (has_object_been_unregistered (data->connection,
4666 data->registration_id,
4667 data->subtree_registration_id))
4669 reply = g_dbus_message_new_method_error (data->message,
4670 "org.freedesktop.DBus.Error.UnknownMethod",
4671 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4672 g_dbus_message_get_path (data->message));
4673 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4674 g_object_unref (reply);
4679 value = data->vtable->get_property (data->connection,
4680 g_dbus_message_get_sender (data->message),
4681 g_dbus_message_get_path (data->message),
4682 data->interface_info->name,
4683 data->property_name,
4690 g_assert_no_error (error);
4692 g_variant_take_ref (value);
4693 reply = g_dbus_message_new_method_reply (data->message);
4694 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4695 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4696 g_variant_unref (value);
4697 g_object_unref (reply);
4701 gchar *dbus_error_name;
4702 g_assert (error != NULL);
4703 dbus_error_name = g_dbus_error_encode_gerror (error);
4704 reply = g_dbus_message_new_method_error_literal (data->message,
4707 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4708 g_free (dbus_error_name);
4709 g_error_free (error);
4710 g_object_unref (reply);
4717 /* called in thread where object was registered - no locks held */
4719 invoke_set_property_in_idle_cb (gpointer _data)
4721 PropertyData *data = _data;
4723 GDBusMessage *reply;
4729 g_variant_get (g_dbus_message_get_body (data->message),
4735 if (!data->vtable->set_property (data->connection,
4736 g_dbus_message_get_sender (data->message),
4737 g_dbus_message_get_path (data->message),
4738 data->interface_info->name,
4739 data->property_name,
4744 gchar *dbus_error_name;
4745 g_assert (error != NULL);
4746 dbus_error_name = g_dbus_error_encode_gerror (error);
4747 reply = g_dbus_message_new_method_error_literal (data->message,
4750 g_free (dbus_error_name);
4751 g_error_free (error);
4755 reply = g_dbus_message_new_method_reply (data->message);
4758 g_assert (reply != NULL);
4759 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4760 g_object_unref (reply);
4761 g_variant_unref (value);
4766 /* called in any thread with connection's lock held */
4768 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4769 GDBusMessage *message,
4770 guint registration_id,
4771 guint subtree_registration_id,
4773 GDBusInterfaceInfo *interface_info,
4774 const GDBusInterfaceVTable *vtable,
4775 GMainContext *main_context,
4779 const char *interface_name;
4780 const char *property_name;
4781 const GDBusPropertyInfo *property_info;
4782 GSource *idle_source;
4783 PropertyData *property_data;
4784 GDBusMessage *reply;
4789 g_variant_get (g_dbus_message_get_body (message),
4794 g_variant_get (g_dbus_message_get_body (message),
4803 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4805 property_info = NULL;
4807 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4808 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4809 if (property_info == NULL)
4811 reply = g_dbus_message_new_method_error (message,
4812 "org.freedesktop.DBus.Error.InvalidArgs",
4813 _("No such property '%s'"),
4815 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4816 g_object_unref (reply);
4821 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4823 reply = g_dbus_message_new_method_error (message,
4824 "org.freedesktop.DBus.Error.InvalidArgs",
4825 _("Property '%s' is not readable"),
4827 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4828 g_object_unref (reply);
4832 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4834 reply = g_dbus_message_new_method_error (message,
4835 "org.freedesktop.DBus.Error.InvalidArgs",
4836 _("Property '%s' is not writable"),
4838 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4839 g_object_unref (reply);
4848 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4849 * of the given value is wrong
4851 g_variant_get_child (g_dbus_message_get_body (message), 2, "v", &value);
4852 if (g_strcmp0 (g_variant_get_type_string (value), property_info->signature) != 0)
4854 reply = g_dbus_message_new_method_error (message,
4855 "org.freedesktop.DBus.Error.InvalidArgs",
4856 _("Error setting property '%s': Expected type '%s' but got '%s'"),
4857 property_name, property_info->signature,
4858 g_variant_get_type_string (value));
4859 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4860 g_variant_unref (value);
4861 g_object_unref (reply);
4866 g_variant_unref (value);
4869 /* If the vtable pointer for get_property() resp. set_property() is
4870 * NULL then dispatch the call via the method_call() handler.
4874 if (vtable->get_property == NULL)
4876 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4877 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4878 vtable, main_context, user_data);
4885 if (vtable->set_property == NULL)
4887 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4888 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4889 vtable, main_context, user_data);
4895 /* ok, got the property info - call user code in an idle handler */
4896 property_data = g_new0 (PropertyData, 1);
4897 property_data->connection = g_object_ref (connection);
4898 property_data->message = g_object_ref (message);
4899 property_data->user_data = user_data;
4900 property_data->property_name = property_name;
4901 property_data->vtable = vtable;
4902 property_data->interface_info = interface_info;
4903 property_data->property_info = property_info;
4904 property_data->registration_id = registration_id;
4905 property_data->subtree_registration_id = subtree_registration_id;
4907 idle_source = g_idle_source_new ();
4908 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4909 g_source_set_callback (idle_source,
4910 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4912 (GDestroyNotify) property_data_free);
4914 g_source_set_name (idle_source, "[gio] invoke_get_property_in_idle_cb");
4916 g_source_set_name (idle_source, "[gio] invoke_set_property_in_idle_cb");
4917 g_source_attach (idle_source, main_context);
4918 g_source_unref (idle_source);
4926 /* called in GDBusWorker thread with connection's lock held */
4928 handle_getset_property (GDBusConnection *connection,
4930 GDBusMessage *message,
4933 ExportedInterface *ei;
4935 const char *interface_name;
4936 const char *property_name;
4941 g_variant_get (g_dbus_message_get_body (message),
4946 g_variant_get (g_dbus_message_get_body (message),
4952 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4953 * no such interface registered
4955 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4958 GDBusMessage *reply;
4959 reply = g_dbus_message_new_method_error (message,
4960 "org.freedesktop.DBus.Error.InvalidArgs",
4961 _("No such interface '%s'"),
4963 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4964 g_object_unref (reply);
4969 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4982 /* ---------------------------------------------------------------------------------------------------- */
4986 GDBusConnection *connection;
4987 GDBusMessage *message;
4989 const GDBusInterfaceVTable *vtable;
4990 GDBusInterfaceInfo *interface_info;
4991 guint registration_id;
4992 guint subtree_registration_id;
4993 } PropertyGetAllData;
4996 property_get_all_data_free (PropertyData *data)
4998 g_object_unref (data->connection);
4999 g_object_unref (data->message);
5003 /* called in thread where object was registered - no locks held */
5005 invoke_get_all_properties_in_idle_cb (gpointer _data)
5007 PropertyGetAllData *data = _data;
5008 GVariantBuilder builder;
5009 GDBusMessage *reply;
5012 if (has_object_been_unregistered (data->connection,
5013 data->registration_id,
5014 data->subtree_registration_id))
5016 reply = g_dbus_message_new_method_error (data->message,
5017 "org.freedesktop.DBus.Error.UnknownMethod",
5018 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
5019 g_dbus_message_get_path (data->message));
5020 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5021 g_object_unref (reply);
5025 /* TODO: Right now we never fail this call - we just omit values if
5026 * a get_property() call is failing.
5028 * We could fail the whole call if just a single get_property() call
5029 * returns an error. We need clarification in the D-Bus spec about this.
5031 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
5032 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
5033 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
5035 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
5038 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
5041 value = data->vtable->get_property (data->connection,
5042 g_dbus_message_get_sender (data->message),
5043 g_dbus_message_get_path (data->message),
5044 data->interface_info->name,
5045 property_info->name,
5052 g_variant_take_ref (value);
5053 g_variant_builder_add (&builder,
5055 property_info->name,
5057 g_variant_unref (value);
5059 g_variant_builder_close (&builder);
5061 reply = g_dbus_message_new_method_reply (data->message);
5062 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
5063 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5064 g_object_unref (reply);
5071 interface_has_readable_properties (GDBusInterfaceInfo *interface_info)
5075 if (!interface_info->properties)
5078 for (i = 0; interface_info->properties[i]; i++)
5079 if (interface_info->properties[i]->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE)
5085 /* called in any thread with connection's lock held */
5087 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
5088 GDBusMessage *message,
5089 guint registration_id,
5090 guint subtree_registration_id,
5091 GDBusInterfaceInfo *interface_info,
5092 const GDBusInterfaceVTable *vtable,
5093 GMainContext *main_context,
5097 GSource *idle_source;
5098 PropertyGetAllData *property_get_all_data;
5105 /* If the vtable pointer for get_property() is NULL but we have a
5106 * non-zero number of readable properties, then dispatch the call via
5107 * the method_call() handler.
5109 if (vtable->get_property == NULL && interface_has_readable_properties (interface_info))
5111 schedule_method_call (connection, message, registration_id, subtree_registration_id,
5112 interface_info, NULL, NULL, g_dbus_message_get_body (message),
5113 vtable, main_context, user_data);
5118 /* ok, got the property info - call user in an idle handler */
5119 property_get_all_data = g_new0 (PropertyGetAllData, 1);
5120 property_get_all_data->connection = g_object_ref (connection);
5121 property_get_all_data->message = g_object_ref (message);
5122 property_get_all_data->user_data = user_data;
5123 property_get_all_data->vtable = vtable;
5124 property_get_all_data->interface_info = interface_info;
5125 property_get_all_data->registration_id = registration_id;
5126 property_get_all_data->subtree_registration_id = subtree_registration_id;
5128 idle_source = g_idle_source_new ();
5129 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
5130 g_source_set_callback (idle_source,
5131 invoke_get_all_properties_in_idle_cb,
5132 property_get_all_data,
5133 (GDestroyNotify) property_get_all_data_free);
5134 g_source_set_name (idle_source, "[gio] invoke_get_all_properties_in_idle_cb");
5135 g_source_attach (idle_source, main_context);
5136 g_source_unref (idle_source);
5144 /* called in GDBusWorker thread with connection's lock held */
5146 handle_get_all_properties (GDBusConnection *connection,
5148 GDBusMessage *message)
5150 ExportedInterface *ei;
5152 const char *interface_name;
5156 g_variant_get (g_dbus_message_get_body (message),
5160 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
5161 * no such interface registered
5163 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5166 GDBusMessage *reply;
5167 reply = g_dbus_message_new_method_error (message,
5168 "org.freedesktop.DBus.Error.InvalidArgs",
5169 _("No such interface"),
5171 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5172 g_object_unref (reply);
5177 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
5189 /* ---------------------------------------------------------------------------------------------------- */
5191 static const gchar introspect_header[] =
5192 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
5193 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
5194 "<!-- GDBus " PACKAGE_VERSION " -->\n"
5197 static const gchar introspect_tail[] =
5200 static const gchar introspect_properties_interface[] =
5201 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
5202 " <method name=\"Get\">\n"
5203 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5204 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
5205 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
5207 " <method name=\"GetAll\">\n"
5208 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5209 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
5211 " <method name=\"Set\">\n"
5212 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5213 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
5214 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
5216 " <signal name=\"PropertiesChanged\">\n"
5217 " <arg type=\"s\" name=\"interface_name\"/>\n"
5218 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
5219 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
5223 static const gchar introspect_introspectable_interface[] =
5224 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
5225 " <method name=\"Introspect\">\n"
5226 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
5229 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
5230 " <method name=\"Ping\"/>\n"
5231 " <method name=\"GetMachineId\">\n"
5232 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
5237 introspect_append_header (GString *s)
5239 g_string_append (s, introspect_header);
5243 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
5245 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
5251 begin = object_path + path_len;
5252 end = strchr (begin, '/');
5254 s = g_strndup (begin, end - begin);
5256 s = g_strdup (begin);
5258 if (g_hash_table_lookup (set, s) == NULL)
5259 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
5265 /* TODO: we want a nicer public interface for this */
5266 /* called in any thread with connection's lock held */
5268 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
5273 GHashTableIter hash_iter;
5274 const gchar *object_path;
5280 CONNECTION_ENSURE_LOCK (connection);
5282 path_len = strlen (path);
5286 set = g_hash_table_new (g_str_hash, g_str_equal);
5288 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
5289 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
5290 maybe_add_path (path, path_len, object_path, set);
5292 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
5293 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
5294 maybe_add_path (path, path_len, object_path, set);
5296 p = g_ptr_array_new ();
5297 keys = g_hash_table_get_keys (set);
5298 for (l = keys; l != NULL; l = l->next)
5299 g_ptr_array_add (p, l->data);
5300 g_hash_table_unref (set);
5303 g_ptr_array_add (p, NULL);
5304 ret = (gchar **) g_ptr_array_free (p, FALSE);
5308 /* called in any thread with connection's lock not held */
5310 g_dbus_connection_list_registered (GDBusConnection *connection,
5314 CONNECTION_LOCK (connection);
5315 ret = g_dbus_connection_list_registered_unlocked (connection, path);
5316 CONNECTION_UNLOCK (connection);
5320 /* called in GDBusWorker thread with connection's lock held */
5322 handle_introspect (GDBusConnection *connection,
5324 GDBusMessage *message)
5328 GDBusMessage *reply;
5329 GHashTableIter hash_iter;
5330 ExportedInterface *ei;
5333 /* first the header with the standard interfaces */
5334 s = g_string_sized_new (sizeof (introspect_header) +
5335 sizeof (introspect_properties_interface) +
5336 sizeof (introspect_introspectable_interface) +
5337 sizeof (introspect_tail));
5338 introspect_append_header (s);
5339 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
5340 "org.freedesktop.DBus.Properties"))
5341 g_string_append (s, introspect_properties_interface);
5343 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
5344 "org.freedesktop.DBus.Introspectable"))
5345 g_string_append (s, introspect_introspectable_interface);
5347 /* then include the registered interfaces */
5348 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
5349 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
5350 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
5352 /* finally include nodes registered below us */
5353 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
5354 for (n = 0; registered != NULL && registered[n] != NULL; n++)
5355 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
5356 g_strfreev (registered);
5357 g_string_append (s, introspect_tail);
5359 reply = g_dbus_message_new_method_reply (message);
5360 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5361 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5362 g_object_unref (reply);
5363 g_string_free (s, TRUE);
5368 /* called in thread where object was registered - no locks held */
5370 call_in_idle_cb (gpointer user_data)
5372 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
5373 GDBusInterfaceVTable *vtable;
5374 guint registration_id;
5375 guint subtree_registration_id;
5377 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
5378 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
5380 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
5382 subtree_registration_id))
5384 GDBusMessage *reply;
5385 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
5386 "org.freedesktop.DBus.Error.UnknownMethod",
5387 _("No such interface '%s' on object at path %s"),
5388 g_dbus_method_invocation_get_interface_name (invocation),
5389 g_dbus_method_invocation_get_object_path (invocation));
5390 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5391 g_object_unref (reply);
5395 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
5396 g_assert (vtable != NULL && vtable->method_call != NULL);
5398 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
5399 g_dbus_method_invocation_get_sender (invocation),
5400 g_dbus_method_invocation_get_object_path (invocation),
5401 g_dbus_method_invocation_get_interface_name (invocation),
5402 g_dbus_method_invocation_get_method_name (invocation),
5403 g_dbus_method_invocation_get_parameters (invocation),
5404 g_object_ref (invocation),
5405 g_dbus_method_invocation_get_user_data (invocation));
5411 /* called in GDBusWorker thread with connection's lock held */
5413 schedule_method_call (GDBusConnection *connection,
5414 GDBusMessage *message,
5415 guint registration_id,
5416 guint subtree_registration_id,
5417 const GDBusInterfaceInfo *interface_info,
5418 const GDBusMethodInfo *method_info,
5419 const GDBusPropertyInfo *property_info,
5420 GVariant *parameters,
5421 const GDBusInterfaceVTable *vtable,
5422 GMainContext *main_context,
5425 GDBusMethodInvocation *invocation;
5426 GSource *idle_source;
5428 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
5429 g_dbus_message_get_path (message),
5430 g_dbus_message_get_interface (message),
5431 g_dbus_message_get_member (message),
5439 /* TODO: would be nicer with a real MethodData like we already
5440 * have PropertyData and PropertyGetAllData... */
5441 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
5442 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
5443 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
5445 idle_source = g_idle_source_new ();
5446 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
5447 g_source_set_callback (idle_source,
5451 g_source_set_name (idle_source, "[gio] call_in_idle_cb");
5452 g_source_attach (idle_source, main_context);
5453 g_source_unref (idle_source);
5456 /* called in GDBusWorker thread with connection's lock held */
5458 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
5459 GDBusMessage *message,
5460 guint registration_id,
5461 guint subtree_registration_id,
5462 GDBusInterfaceInfo *interface_info,
5463 const GDBusInterfaceVTable *vtable,
5464 GMainContext *main_context,
5467 GDBusMethodInfo *method_info;
5468 GDBusMessage *reply;
5469 GVariant *parameters;
5471 GVariantType *in_type;
5475 /* TODO: the cost of this is O(n) - it might be worth caching the result */
5476 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
5478 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
5479 * error to the caller
5481 if (method_info == NULL)
5483 reply = g_dbus_message_new_method_error (message,
5484 "org.freedesktop.DBus.Error.UnknownMethod",
5485 _("No such method '%s'"),
5486 g_dbus_message_get_member (message));
5487 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5488 g_object_unref (reply);
5493 parameters = g_dbus_message_get_body (message);
5494 if (parameters == NULL)
5496 parameters = g_variant_new ("()");
5497 g_variant_ref_sink (parameters);
5501 g_variant_ref (parameters);
5504 /* Check that the incoming args are of the right type - if they are not, return
5505 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
5507 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
5508 if (!g_variant_is_of_type (parameters, in_type))
5512 type_string = g_variant_type_dup_string (in_type);
5514 reply = g_dbus_message_new_method_error (message,
5515 "org.freedesktop.DBus.Error.InvalidArgs",
5516 _("Type of message, '%s', does not match expected type '%s'"),
5517 g_variant_get_type_string (parameters),
5519 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5520 g_variant_type_free (in_type);
5521 g_variant_unref (parameters);
5522 g_object_unref (reply);
5523 g_free (type_string);
5527 g_variant_type_free (in_type);
5529 /* schedule the call in idle */
5530 schedule_method_call (connection, message, registration_id, subtree_registration_id,
5531 interface_info, method_info, NULL, parameters,
5532 vtable, main_context, user_data);
5533 g_variant_unref (parameters);
5540 /* ---------------------------------------------------------------------------------------------------- */
5542 /* called in GDBusWorker thread with connection's lock held */
5544 obj_message_func (GDBusConnection *connection,
5546 GDBusMessage *message)
5548 const gchar *interface_name;
5549 const gchar *member;
5550 const gchar *signature;
5555 interface_name = g_dbus_message_get_interface (message);
5556 member = g_dbus_message_get_member (message);
5557 signature = g_dbus_message_get_signature (message);
5559 /* see if we have an interface for handling this call */
5560 if (interface_name != NULL)
5562 ExportedInterface *ei;
5563 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5566 /* we do - invoke the handler in idle in the right thread */
5568 /* handle no vtable or handler being present */
5569 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
5572 handled = validate_and_maybe_schedule_method_call (connection,
5584 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5585 g_strcmp0 (member, "Introspect") == 0 &&
5586 g_strcmp0 (signature, "") == 0)
5588 handled = handle_introspect (connection, eo, message);
5591 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5592 g_strcmp0 (member, "Get") == 0 &&
5593 g_strcmp0 (signature, "ss") == 0)
5595 handled = handle_getset_property (connection, eo, message, TRUE);
5598 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5599 g_strcmp0 (member, "Set") == 0 &&
5600 g_strcmp0 (signature, "ssv") == 0)
5602 handled = handle_getset_property (connection, eo, message, FALSE);
5605 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5606 g_strcmp0 (member, "GetAll") == 0 &&
5607 g_strcmp0 (signature, "s") == 0)
5609 handled = handle_get_all_properties (connection, eo, message);
5618 * g_dbus_connection_register_object:
5619 * @connection: a #GDBusConnection
5620 * @object_path: the object path to register at
5621 * @interface_info: introspection data for the interface
5622 * @vtable: (allow-none): a #GDBusInterfaceVTable to call into or %NULL
5623 * @user_data: (allow-none): data to pass to functions in @vtable
5624 * @user_data_free_func: function to call when the object path is unregistered
5625 * @error: return location for error or %NULL
5627 * Registers callbacks for exported objects at @object_path with the
5628 * D-Bus interface that is described in @interface_info.
5630 * Calls to functions in @vtable (and @user_data_free_func) will happen
5632 * [thread-default main context][g-main-context-push-thread-default]
5633 * of the thread you are calling this method from.
5635 * Note that all #GVariant values passed to functions in @vtable will match
5636 * the signature given in @interface_info - if a remote caller passes
5637 * incorrect values, the `org.freedesktop.DBus.Error.InvalidArgs`
5638 * is returned to the remote caller.
5640 * Additionally, if the remote caller attempts to invoke methods or
5641 * access properties not mentioned in @interface_info the
5642 * `org.freedesktop.DBus.Error.UnknownMethod` resp.
5643 * `org.freedesktop.DBus.Error.InvalidArgs` errors
5644 * are returned to the caller.
5646 * It is considered a programming error if the
5647 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
5648 * #GVariant of incorrect type.
5650 * If an existing callback is already registered at @object_path and
5651 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
5653 * GDBus automatically implements the standard D-Bus interfaces
5654 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
5655 * and org.freedesktop.Peer, so you don't have to implement those for the
5656 * objects you export. You can implement org.freedesktop.DBus.Properties
5657 * yourself, e.g. to handle getting and setting of properties asynchronously.
5659 * Note that the reference count on @interface_info will be
5660 * incremented by 1 (unless allocated statically, e.g. if the
5661 * reference count is -1, see g_dbus_interface_info_ref()) for as long
5662 * as the object is exported. Also note that @vtable will be copied.
5664 * See this [server][gdbus-server] for an example of how to use this method.
5666 * Returns: 0 if @error is set, otherwise a registration id (never 0)
5667 * that can be used with g_dbus_connection_unregister_object()
5672 g_dbus_connection_register_object (GDBusConnection *connection,
5673 const gchar *object_path,
5674 GDBusInterfaceInfo *interface_info,
5675 const GDBusInterfaceVTable *vtable,
5677 GDestroyNotify user_data_free_func,
5681 ExportedInterface *ei;
5684 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5685 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5686 g_return_val_if_fail (interface_info != NULL, 0);
5687 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
5688 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5689 g_return_val_if_fail (check_initialized (connection), 0);
5693 CONNECTION_LOCK (connection);
5695 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5698 eo = g_new0 (ExportedObject, 1);
5699 eo->object_path = g_strdup (object_path);
5700 eo->connection = connection;
5701 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
5704 (GDestroyNotify) exported_interface_free);
5705 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
5708 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
5714 _("An object is already exported for the interface %s at %s"),
5715 interface_info->name,
5720 ei = g_new0 (ExportedInterface, 1);
5721 ei->id = _global_registration_id++; /* TODO: overflow etc. */
5723 ei->user_data = user_data;
5724 ei->user_data_free_func = user_data_free_func;
5725 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
5726 ei->interface_info = g_dbus_interface_info_ref (interface_info);
5727 g_dbus_interface_info_cache_build (ei->interface_info);
5728 ei->interface_name = g_strdup (interface_info->name);
5729 ei->context = g_main_context_ref_thread_default ();
5731 g_hash_table_insert (eo->map_if_name_to_ei,
5732 (gpointer) ei->interface_name,
5734 g_hash_table_insert (connection->map_id_to_ei,
5735 GUINT_TO_POINTER (ei->id),
5741 CONNECTION_UNLOCK (connection);
5747 * g_dbus_connection_unregister_object:
5748 * @connection: a #GDBusConnection
5749 * @registration_id: a registration id obtained from
5750 * g_dbus_connection_register_object()
5752 * Unregisters an object.
5754 * Returns: %TRUE if the object was unregistered, %FALSE otherwise
5759 g_dbus_connection_unregister_object (GDBusConnection *connection,
5760 guint registration_id)
5762 ExportedInterface *ei;
5766 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5767 g_return_val_if_fail (check_initialized (connection), FALSE);
5771 CONNECTION_LOCK (connection);
5773 ei = g_hash_table_lookup (connection->map_id_to_ei,
5774 GUINT_TO_POINTER (registration_id));
5780 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5781 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5782 /* unregister object path if we have no more exported interfaces */
5783 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5784 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5790 CONNECTION_UNLOCK (connection);
5795 /* ---------------------------------------------------------------------------------------------------- */
5798 * g_dbus_connection_emit_signal:
5799 * @connection: a #GDBusConnection
5800 * @destination_bus_name: (allow-none): the unique bus name for the destination
5801 * for the signal or %NULL to emit to all listeners
5802 * @object_path: path of remote object
5803 * @interface_name: D-Bus interface to emit a signal on
5804 * @signal_name: the name of the signal to emit
5805 * @parameters: (allow-none): a #GVariant tuple with parameters for the signal
5806 * or %NULL if not passing parameters
5807 * @error: Return location for error or %NULL
5811 * If the parameters GVariant is floating, it is consumed.
5813 * This can only fail if @parameters is not compatible with the D-Bus protocol.
5815 * Returns: %TRUE unless @error is set
5820 g_dbus_connection_emit_signal (GDBusConnection *connection,
5821 const gchar *destination_bus_name,
5822 const gchar *object_path,
5823 const gchar *interface_name,
5824 const gchar *signal_name,
5825 GVariant *parameters,
5828 GDBusMessage *message;
5834 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5835 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5836 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5837 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5838 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5839 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5840 g_return_val_if_fail (check_initialized (connection), FALSE);
5842 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5844 _g_dbus_debug_print_lock ();
5845 g_print ("========================================================================\n"
5846 "GDBus-debug:Emission:\n"
5847 " >>>> SIGNAL EMISSION %s.%s()\n"
5849 " destination %s\n",
5850 interface_name, signal_name,
5852 destination_bus_name != NULL ? destination_bus_name : "(none)");
5853 _g_dbus_debug_print_unlock ();
5856 message = g_dbus_message_new_signal (object_path,
5860 if (destination_bus_name != NULL)
5861 g_dbus_message_set_header (message,
5862 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5863 g_variant_new_string (destination_bus_name));
5865 if (parameters != NULL)
5866 g_dbus_message_set_body (message, parameters);
5868 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5869 g_object_unref (message);
5875 add_call_flags (GDBusMessage *message,
5876 GDBusCallFlags flags)
5878 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5879 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
5883 decode_method_reply (GDBusMessage *reply,
5884 const gchar *method_name,
5885 const GVariantType *reply_type,
5886 GUnixFDList **out_fd_list,
5892 switch (g_dbus_message_get_message_type (reply))
5894 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5895 result = g_dbus_message_get_body (reply);
5898 result = g_variant_new ("()");
5899 g_variant_ref_sink (result);
5903 g_variant_ref (result);
5906 if (!g_variant_is_of_type (result, reply_type))
5908 gchar *type_string = g_variant_type_dup_string (reply_type);
5912 G_IO_ERROR_INVALID_ARGUMENT,
5913 _("Method '%s' returned type '%s', but expected '%s'"),
5914 method_name, g_variant_get_type_string (result), type_string);
5916 g_variant_unref (result);
5917 g_free (type_string);
5924 if (out_fd_list != NULL)
5926 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5927 if (*out_fd_list != NULL)
5928 g_object_ref (*out_fd_list);
5934 case G_DBUS_MESSAGE_TYPE_ERROR:
5935 g_dbus_message_to_gerror (reply, error);
5939 g_assert_not_reached ();
5949 GSimpleAsyncResult *simple;
5950 GVariantType *reply_type;
5951 gchar *method_name; /* for error message */
5955 GUnixFDList *fd_list;
5959 call_state_free (CallState *state)
5961 g_variant_type_free (state->reply_type);
5962 g_free (state->method_name);
5964 if (state->value != NULL)
5965 g_variant_unref (state->value);
5966 if (state->fd_list != NULL)
5967 g_object_unref (state->fd_list);
5968 g_slice_free (CallState, state);
5971 /* called in any thread, with the connection's lock not held */
5973 g_dbus_connection_call_done (GObject *source,
5974 GAsyncResult *result,
5977 GSimpleAsyncResult *simple;
5978 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5979 CallState *state = user_data;
5981 GDBusMessage *reply;
5984 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5988 if (G_UNLIKELY (_g_dbus_debug_call ()))
5990 _g_dbus_debug_print_lock ();
5991 g_print ("========================================================================\n"
5992 "GDBus-debug:Call:\n"
5993 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5999 g_print ("SUCCESS\n");
6003 g_print ("FAILED: %s\n",
6006 _g_dbus_debug_print_unlock ();
6010 state->value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
6012 simple = state->simple; /* why? because state is freed before we unref simple.. */
6015 g_simple_async_result_take_error (state->simple, error);
6016 g_simple_async_result_complete (state->simple);
6017 call_state_free (state);
6021 g_simple_async_result_set_op_res_gpointer (state->simple, state, (GDestroyNotify) call_state_free);
6022 g_simple_async_result_complete (state->simple);
6024 g_clear_object (&reply);
6025 g_object_unref (simple);
6028 /* called in any thread, with the connection's lock not held */
6030 g_dbus_connection_call_internal (GDBusConnection *connection,
6031 const gchar *bus_name,
6032 const gchar *object_path,
6033 const gchar *interface_name,
6034 const gchar *method_name,
6035 GVariant *parameters,
6036 const GVariantType *reply_type,
6037 GDBusCallFlags flags,
6039 GUnixFDList *fd_list,
6040 GCancellable *cancellable,
6041 GAsyncReadyCallback callback,
6044 GDBusMessage *message;
6047 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
6048 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
6049 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
6050 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
6051 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
6052 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
6053 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
6054 g_return_if_fail (check_initialized (connection));
6056 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
6058 g_return_if_fail (fd_list == NULL);
6061 message = g_dbus_message_new_method_call (bus_name,
6065 add_call_flags (message, flags);
6066 if (parameters != NULL)
6067 g_dbus_message_set_body (message, parameters);
6070 if (fd_list != NULL)
6071 g_dbus_message_set_unix_fd_list (message, fd_list);
6074 /* If the user has no callback then we can just send the message with
6075 * the G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set and skip all
6076 * the logic for processing the reply. If the service sends the reply
6077 * anyway then it will just be ignored.
6079 if (callback != NULL)
6083 state = g_slice_new0 (CallState);
6084 state->simple = g_simple_async_result_new (G_OBJECT (connection),
6085 callback, user_data,
6086 g_dbus_connection_call_internal);
6087 g_simple_async_result_set_check_cancellable (state->simple, cancellable);
6088 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
6090 if (reply_type == NULL)
6091 reply_type = G_VARIANT_TYPE_ANY;
6093 state->reply_type = g_variant_type_copy (reply_type);
6095 g_dbus_connection_send_message_with_reply (connection,
6097 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
6101 g_dbus_connection_call_done,
6103 serial = state->serial;
6107 GDBusMessageFlags flags;
6109 flags = g_dbus_message_get_flags (message);
6110 flags |= G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
6111 g_dbus_message_set_flags (message, flags);
6113 g_dbus_connection_send_message (connection,
6115 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
6119 if (G_UNLIKELY (_g_dbus_debug_call ()))
6121 _g_dbus_debug_print_lock ();
6122 g_print ("========================================================================\n"
6123 "GDBus-debug:Call:\n"
6124 " >>>> ASYNC %s.%s()\n"
6126 " owned by name %s (serial %d)\n",
6130 bus_name != NULL ? bus_name : "(none)",
6132 _g_dbus_debug_print_unlock ();
6135 if (message != NULL)
6136 g_object_unref (message);
6139 /* called in any thread, with the connection's lock not held */
6141 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
6142 GUnixFDList **out_fd_list,
6146 GSimpleAsyncResult *simple;
6149 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
6150 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
6151 g_dbus_connection_call_internal), NULL);
6152 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6154 simple = G_SIMPLE_ASYNC_RESULT (res);
6156 if (g_simple_async_result_propagate_error (simple, error))
6159 state = g_simple_async_result_get_op_res_gpointer (simple);
6160 if (out_fd_list != NULL)
6161 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
6162 return g_variant_ref (state->value);
6165 /* called in any user thread, with the connection's lock not held */
6167 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
6168 const gchar *bus_name,
6169 const gchar *object_path,
6170 const gchar *interface_name,
6171 const gchar *method_name,
6172 GVariant *parameters,
6173 const GVariantType *reply_type,
6174 GDBusCallFlags flags,
6176 GUnixFDList *fd_list,
6177 GUnixFDList **out_fd_list,
6178 GCancellable *cancellable,
6181 GDBusMessage *message;
6182 GDBusMessage *reply;
6184 GError *local_error;
6185 GDBusSendMessageFlags send_flags;
6191 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
6192 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
6193 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
6194 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
6195 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
6196 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
6197 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
6199 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
6201 g_return_val_if_fail (fd_list == NULL, NULL);
6203 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6205 if (!(flags & CALL_FLAGS_INITIALIZING))
6206 g_return_val_if_fail (check_initialized (connection), FALSE);
6208 if (reply_type == NULL)
6209 reply_type = G_VARIANT_TYPE_ANY;
6211 message = g_dbus_message_new_method_call (bus_name,
6215 add_call_flags (message, flags);
6216 if (parameters != NULL)
6217 g_dbus_message_set_body (message, parameters);
6220 if (fd_list != NULL)
6221 g_dbus_message_set_unix_fd_list (message, fd_list);
6224 if (G_UNLIKELY (_g_dbus_debug_call ()))
6226 _g_dbus_debug_print_lock ();
6227 g_print ("========================================================================\n"
6228 "GDBus-debug:Call:\n"
6229 " >>>> SYNC %s.%s()\n"
6231 " owned by name %s\n",
6235 bus_name != NULL ? bus_name : "(none)");
6236 _g_dbus_debug_print_unlock ();
6241 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
6243 /* translate from one flavour of flags to another... */
6244 if (flags & CALL_FLAGS_INITIALIZING)
6245 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
6247 reply = g_dbus_connection_send_message_with_reply_sync (connection,
6251 NULL, /* volatile guint32 *out_serial */
6255 if (G_UNLIKELY (_g_dbus_debug_call ()))
6257 _g_dbus_debug_print_lock ();
6258 g_print ("========================================================================\n"
6259 "GDBus-debug:Call:\n"
6260 " <<<< SYNC COMPLETE %s.%s()\n"
6266 g_print ("SUCCESS\n");
6270 g_print ("FAILED: %s\n",
6271 local_error->message);
6273 _g_dbus_debug_print_unlock ();
6279 *error = local_error;
6281 g_error_free (local_error);
6285 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
6288 if (message != NULL)
6289 g_object_unref (message);
6291 g_object_unref (reply);
6296 /* ---------------------------------------------------------------------------------------------------- */
6299 * g_dbus_connection_call:
6300 * @connection: a #GDBusConnection
6301 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6302 * @connection is not a message bus connection
6303 * @object_path: path of remote object
6304 * @interface_name: D-Bus interface to invoke method on
6305 * @method_name: the name of the method to invoke
6306 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6307 * or %NULL if not passing parameters
6308 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6309 * @flags: flags from the #GDBusCallFlags enumeration
6310 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6311 * timeout or %G_MAXINT for no timeout
6312 * @cancellable: (allow-none): a #GCancellable or %NULL
6313 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request
6314 * is satisfied or %NULL if you don't care about the result of the
6316 * @user_data: the data to pass to @callback
6318 * Asynchronously invokes the @method_name method on the
6319 * @interface_name D-Bus interface on the remote object at
6320 * @object_path owned by @bus_name.
6322 * If @connection is closed then the operation will fail with
6323 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
6324 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
6325 * not compatible with the D-Bus protocol, the operation fails with
6326 * %G_IO_ERROR_INVALID_ARGUMENT.
6328 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
6329 * error will be raised if it does not match. Said another way, if you give a @reply_type
6330 * then any non-%NULL return value will be of this type.
6332 * If the @parameters #GVariant is floating, it is consumed. This allows
6333 * convenient 'inline' use of g_variant_new(), e.g.:
6334 * |[<!-- language="C" -->
6335 * g_dbus_connection_call (connection,
6336 * "org.freedesktop.StringThings",
6337 * "/org/freedesktop/StringThings",
6338 * "org.freedesktop.StringThings",
6340 * g_variant_new ("(ss)",
6344 * G_DBUS_CALL_FLAGS_NONE,
6347 * (GAsyncReadyCallback) two_strings_done,
6351 * This is an asynchronous method. When the operation is finished,
6352 * @callback will be invoked in the
6353 * [thread-default main context][g-main-context-push-thread-default]
6354 * of the thread you are calling this method from. You can then call
6355 * g_dbus_connection_call_finish() to get the result of the operation.
6356 * See g_dbus_connection_call_sync() for the synchronous version of this
6359 * If @callback is %NULL then the D-Bus method call message will be sent with
6360 * the %G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set.
6365 g_dbus_connection_call (GDBusConnection *connection,
6366 const gchar *bus_name,
6367 const gchar *object_path,
6368 const gchar *interface_name,
6369 const gchar *method_name,
6370 GVariant *parameters,
6371 const GVariantType *reply_type,
6372 GDBusCallFlags flags,
6374 GCancellable *cancellable,
6375 GAsyncReadyCallback callback,
6378 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);
6382 * g_dbus_connection_call_finish:
6383 * @connection: a #GDBusConnection
6384 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call()
6385 * @error: return location for error or %NULL
6387 * Finishes an operation started with g_dbus_connection_call().
6389 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6390 * return values. Free with g_variant_unref().
6395 g_dbus_connection_call_finish (GDBusConnection *connection,
6399 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
6403 * g_dbus_connection_call_sync:
6404 * @connection: a #GDBusConnection
6405 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6406 * @connection is not a message bus connection
6407 * @object_path: path of remote object
6408 * @interface_name: D-Bus interface to invoke method on
6409 * @method_name: the name of the method to invoke
6410 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6411 * or %NULL if not passing parameters
6412 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6413 * @flags: flags from the #GDBusCallFlags enumeration
6414 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6415 * timeout or %G_MAXINT for no timeout
6416 * @cancellable: (allow-none): a #GCancellable or %NULL
6417 * @error: return location for error or %NULL
6419 * Synchronously invokes the @method_name method on the
6420 * @interface_name D-Bus interface on the remote object at
6421 * @object_path owned by @bus_name.
6423 * If @connection is closed then the operation will fail with
6424 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
6425 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
6426 * contains a value not compatible with the D-Bus protocol, the operation
6427 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
6429 * If @reply_type is non-%NULL then the reply will be checked for having
6430 * this type and an error will be raised if it does not match. Said
6431 * another way, if you give a @reply_type then any non-%NULL return
6432 * value will be of this type.
6434 * If the @parameters #GVariant is floating, it is consumed.
6435 * This allows convenient 'inline' use of g_variant_new(), e.g.:
6436 * |[<!-- language="C" -->
6437 * g_dbus_connection_call_sync (connection,
6438 * "org.freedesktop.StringThings",
6439 * "/org/freedesktop/StringThings",
6440 * "org.freedesktop.StringThings",
6442 * g_variant_new ("(ss)",
6446 * G_DBUS_CALL_FLAGS_NONE,
6452 * The calling thread is blocked until a reply is received. See
6453 * g_dbus_connection_call() for the asynchronous version of
6456 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6457 * return values. Free with g_variant_unref().
6462 g_dbus_connection_call_sync (GDBusConnection *connection,
6463 const gchar *bus_name,
6464 const gchar *object_path,
6465 const gchar *interface_name,
6466 const gchar *method_name,
6467 GVariant *parameters,
6468 const GVariantType *reply_type,
6469 GDBusCallFlags flags,
6471 GCancellable *cancellable,
6474 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);
6477 /* ---------------------------------------------------------------------------------------------------- */
6482 * g_dbus_connection_call_with_unix_fd_list:
6483 * @connection: a #GDBusConnection
6484 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6485 * @connection is not a message bus connection
6486 * @object_path: path of remote object
6487 * @interface_name: D-Bus interface to invoke method on
6488 * @method_name: the name of the method to invoke
6489 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6490 * or %NULL if not passing parameters
6491 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6492 * @flags: flags from the #GDBusCallFlags enumeration
6493 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6494 * timeout or %G_MAXINT for no timeout
6495 * @fd_list: (allow-none): a #GUnixFDList or %NULL
6496 * @cancellable: (allow-none): a #GCancellable or %NULL
6497 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request is
6498 * satisfied or %NULL if you don't * care about the result of the
6500 * @user_data: The data to pass to @callback.
6502 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
6504 * This method is only available on UNIX.
6509 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
6510 const gchar *bus_name,
6511 const gchar *object_path,
6512 const gchar *interface_name,
6513 const gchar *method_name,
6514 GVariant *parameters,
6515 const GVariantType *reply_type,
6516 GDBusCallFlags flags,
6518 GUnixFDList *fd_list,
6519 GCancellable *cancellable,
6520 GAsyncReadyCallback callback,
6523 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);
6527 * g_dbus_connection_call_with_unix_fd_list_finish:
6528 * @connection: a #GDBusConnection
6529 * @out_fd_list: (out) (allow-none): return location for a #GUnixFDList or %NULL
6530 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
6531 * g_dbus_connection_call_with_unix_fd_list()
6532 * @error: return location for error or %NULL
6534 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
6536 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6537 * return values. Free with g_variant_unref().
6542 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
6543 GUnixFDList **out_fd_list,
6547 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
6551 * g_dbus_connection_call_with_unix_fd_list_sync:
6552 * @connection: a #GDBusConnection
6553 * @bus_name: (allow-none): a unique or well-known bus name or %NULL
6554 * if @connection is not a message bus connection
6555 * @object_path: path of remote object
6556 * @interface_name: D-Bus interface to invoke method on
6557 * @method_name: the name of the method to invoke
6558 * @parameters: (allow-none): a #GVariant tuple with parameters for
6559 * the method or %NULL if not passing parameters
6560 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6561 * @flags: flags from the #GDBusCallFlags enumeration
6562 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6563 * timeout or %G_MAXINT for no timeout
6564 * @fd_list: (allow-none): a #GUnixFDList or %NULL
6565 * @out_fd_list: (out) (allow-none): return location for a #GUnixFDList or %NULL
6566 * @cancellable: (allow-none): a #GCancellable or %NULL
6567 * @error: return location for error or %NULL
6569 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
6571 * This method is only available on UNIX.
6573 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6574 * return values. Free with g_variant_unref().
6579 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
6580 const gchar *bus_name,
6581 const gchar *object_path,
6582 const gchar *interface_name,
6583 const gchar *method_name,
6584 GVariant *parameters,
6585 const GVariantType *reply_type,
6586 GDBusCallFlags flags,
6588 GUnixFDList *fd_list,
6589 GUnixFDList **out_fd_list,
6590 GCancellable *cancellable,
6593 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);
6596 #endif /* G_OS_UNIX */
6598 /* ---------------------------------------------------------------------------------------------------- */
6600 struct ExportedSubtree
6604 GDBusConnection *connection;
6605 GDBusSubtreeVTable *vtable;
6606 GDBusSubtreeFlags flags;
6608 GMainContext *context;
6610 GDestroyNotify user_data_free_func;
6614 exported_subtree_free (ExportedSubtree *es)
6616 call_destroy_notify (es->context,
6617 es->user_data_free_func,
6620 g_main_context_unref (es->context);
6622 _g_dbus_subtree_vtable_free (es->vtable);
6623 g_free (es->object_path);
6627 /* called without lock held in the thread where the caller registered
6631 handle_subtree_introspect (GDBusConnection *connection,
6632 ExportedSubtree *es,
6633 GDBusMessage *message)
6637 GDBusMessage *reply;
6640 const gchar *sender;
6641 const gchar *requested_object_path;
6642 const gchar *requested_node;
6643 GDBusInterfaceInfo **interfaces;
6645 gchar **subnode_paths;
6646 gboolean has_properties_interface;
6647 gboolean has_introspectable_interface;
6651 requested_object_path = g_dbus_message_get_path (message);
6652 sender = g_dbus_message_get_sender (message);
6653 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6655 s = g_string_new (NULL);
6656 introspect_append_header (s);
6658 /* Strictly we don't need the children in dynamic mode, but we avoid the
6659 * conditionals to preserve code clarity
6661 children = es->vtable->enumerate (es->connection,
6668 requested_node = strrchr (requested_object_path, '/') + 1;
6670 /* Assert existence of object if we are not dynamic */
6671 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
6672 !_g_strv_has_string ((const gchar * const *) children, requested_node))
6677 requested_node = NULL;
6680 interfaces = es->vtable->introspect (es->connection,
6685 if (interfaces != NULL)
6687 has_properties_interface = FALSE;
6688 has_introspectable_interface = FALSE;
6690 for (n = 0; interfaces[n] != NULL; n++)
6692 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
6693 has_properties_interface = TRUE;
6694 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
6695 has_introspectable_interface = TRUE;
6697 if (!has_properties_interface)
6698 g_string_append (s, introspect_properties_interface);
6699 if (!has_introspectable_interface)
6700 g_string_append (s, introspect_introspectable_interface);
6702 for (n = 0; interfaces[n] != NULL; n++)
6704 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
6705 g_dbus_interface_info_unref (interfaces[n]);
6707 g_free (interfaces);
6710 /* then include <node> entries from the Subtree for the root */
6713 for (n = 0; children != NULL && children[n] != NULL; n++)
6714 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
6717 /* finally include nodes registered below us */
6718 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
6719 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
6720 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
6721 g_strfreev (subnode_paths);
6723 g_string_append (s, "</node>\n");
6725 reply = g_dbus_message_new_method_reply (message);
6726 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6727 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6728 g_object_unref (reply);
6733 g_string_free (s, TRUE);
6734 g_strfreev (children);
6738 /* called without lock held in the thread where the caller registered
6742 handle_subtree_method_invocation (GDBusConnection *connection,
6743 ExportedSubtree *es,
6744 GDBusMessage *message)
6747 const gchar *sender;
6748 const gchar *interface_name;
6749 const gchar *member;
6750 const gchar *signature;
6751 const gchar *requested_object_path;
6752 const gchar *requested_node;
6754 GDBusInterfaceInfo *interface_info;
6755 const GDBusInterfaceVTable *interface_vtable;
6756 gpointer interface_user_data;
6758 GDBusInterfaceInfo **interfaces;
6759 gboolean is_property_get;
6760 gboolean is_property_set;
6761 gboolean is_property_get_all;
6766 requested_object_path = g_dbus_message_get_path (message);
6767 sender = g_dbus_message_get_sender (message);
6768 interface_name = g_dbus_message_get_interface (message);
6769 member = g_dbus_message_get_member (message);
6770 signature = g_dbus_message_get_signature (message);
6771 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6773 is_property_get = FALSE;
6774 is_property_set = FALSE;
6775 is_property_get_all = FALSE;
6776 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6778 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6779 is_property_get = TRUE;
6780 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6781 is_property_set = TRUE;
6782 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6783 is_property_get_all = TRUE;
6788 requested_node = strrchr (requested_object_path, '/') + 1;
6790 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6792 /* We don't want to dispatch to unenumerated
6793 * nodes, so ensure that the child exists.
6798 children = es->vtable->enumerate (es->connection,
6803 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6804 g_strfreev (children);
6812 requested_node = NULL;
6815 /* get introspection data for the node */
6816 interfaces = es->vtable->introspect (es->connection,
6818 requested_object_path,
6822 if (interfaces == NULL)
6825 interface_info = NULL;
6826 for (n = 0; interfaces[n] != NULL; n++)
6828 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6829 interface_info = interfaces[n];
6832 /* dispatch the call if the user wants to handle it */
6833 if (interface_info != NULL)
6835 /* figure out where to dispatch the method call */
6836 interface_user_data = NULL;
6837 interface_vtable = es->vtable->dispatch (es->connection,
6842 &interface_user_data,
6844 if (interface_vtable == NULL)
6847 CONNECTION_LOCK (connection);
6848 handled = validate_and_maybe_schedule_method_call (es->connection,
6855 interface_user_data);
6856 CONNECTION_UNLOCK (connection);
6858 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6859 else if (is_property_get || is_property_set || is_property_get_all)
6861 if (is_property_get)
6862 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6863 else if (is_property_set)
6864 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6865 else if (is_property_get_all)
6866 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6868 g_assert_not_reached ();
6870 /* see if the object supports this interface at all */
6871 for (n = 0; interfaces[n] != NULL; n++)
6873 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6874 interface_info = interfaces[n];
6877 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6878 * claims it won't support the interface
6880 if (interface_info == NULL)
6882 GDBusMessage *reply;
6883 reply = g_dbus_message_new_method_error (message,
6884 "org.freedesktop.DBus.Error.InvalidArgs",
6885 _("No such interface '%s'"),
6887 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6888 g_object_unref (reply);
6893 /* figure out where to dispatch the property get/set/getall calls */
6894 interface_user_data = NULL;
6895 interface_vtable = es->vtable->dispatch (es->connection,
6900 &interface_user_data,
6902 if (interface_vtable == NULL)
6904 g_warning ("The subtree introspection function indicates that '%s' "
6905 "is a valid interface name, but calling the dispatch "
6906 "function on that interface gave us NULL", interface_name);
6910 if (is_property_get || is_property_set)
6912 CONNECTION_LOCK (connection);
6913 handled = validate_and_maybe_schedule_property_getset (es->connection,
6921 interface_user_data);
6922 CONNECTION_UNLOCK (connection);
6924 else if (is_property_get_all)
6926 CONNECTION_LOCK (connection);
6927 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6934 interface_user_data);
6935 CONNECTION_UNLOCK (connection);
6940 if (interfaces != NULL)
6942 for (n = 0; interfaces[n] != NULL; n++)
6943 g_dbus_interface_info_unref (interfaces[n]);
6944 g_free (interfaces);
6952 GDBusMessage *message;
6953 ExportedSubtree *es;
6954 } SubtreeDeferredData;
6957 subtree_deferred_data_free (SubtreeDeferredData *data)
6959 g_object_unref (data->message);
6963 /* called without lock held in the thread where the caller registered the subtree */
6965 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6967 SubtreeDeferredData *data = _data;
6972 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6973 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6974 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6975 handled = handle_subtree_introspect (data->es->connection,
6979 handled = handle_subtree_method_invocation (data->es->connection,
6985 CONNECTION_LOCK (data->es->connection);
6986 handled = handle_generic_unlocked (data->es->connection, data->message);
6987 CONNECTION_UNLOCK (data->es->connection);
6990 /* if we couldn't handle the request, just bail with the UnknownMethod error */
6993 GDBusMessage *reply;
6994 reply = g_dbus_message_new_method_error (data->message,
6995 "org.freedesktop.DBus.Error.UnknownMethod",
6996 _("Method '%s' on interface '%s' with signature '%s' does not exist"),
6997 g_dbus_message_get_member (data->message),
6998 g_dbus_message_get_interface (data->message),
6999 g_dbus_message_get_signature (data->message));
7000 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7001 g_object_unref (reply);
7007 /* called in GDBusWorker thread with connection's lock held */
7009 subtree_message_func (GDBusConnection *connection,
7010 ExportedSubtree *es,
7011 GDBusMessage *message)
7013 GSource *idle_source;
7014 SubtreeDeferredData *data;
7016 data = g_new0 (SubtreeDeferredData, 1);
7017 data->message = g_object_ref (message);
7020 /* defer this call to an idle handler in the right thread */
7021 idle_source = g_idle_source_new ();
7022 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
7023 g_source_set_callback (idle_source,
7024 process_subtree_vtable_message_in_idle_cb,
7026 (GDestroyNotify) subtree_deferred_data_free);
7027 g_source_set_name (idle_source, "[gio] process_subtree_vtable_message_in_idle_cb");
7028 g_source_attach (idle_source, es->context);
7029 g_source_unref (idle_source);
7031 /* since we own the entire subtree, handlers for objects not in the subtree have been
7032 * tried already by libdbus-1 - so we just need to ensure that we're always going
7033 * to reply to the message
7039 * g_dbus_connection_register_subtree:
7040 * @connection: a #GDBusConnection
7041 * @object_path: the object path to register the subtree at
7042 * @vtable: a #GDBusSubtreeVTable to enumerate, introspect and
7043 * dispatch nodes in the subtree
7044 * @flags: flags used to fine tune the behavior of the subtree
7045 * @user_data: data to pass to functions in @vtable
7046 * @user_data_free_func: function to call when the subtree is unregistered
7047 * @error: return location for error or %NULL
7049 * Registers a whole subtree of dynamic objects.
7051 * The @enumerate and @introspection functions in @vtable are used to
7052 * convey, to remote callers, what nodes exist in the subtree rooted
7055 * When handling remote calls into any node in the subtree, first the
7056 * @enumerate function is used to check if the node exists. If the node exists
7057 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
7058 * the @introspection function is used to check if the node supports the
7059 * requested method. If so, the @dispatch function is used to determine
7060 * where to dispatch the call. The collected #GDBusInterfaceVTable and
7061 * #gpointer will be used to call into the interface vtable for processing
7064 * All calls into user-provided code will be invoked in the
7065 * [thread-default main context][g-main-context-push-thread-default]
7066 * of the thread you are calling this method from.
7068 * If an existing subtree is already registered at @object_path or
7069 * then @error is set to #G_IO_ERROR_EXISTS.
7071 * Note that it is valid to register regular objects (using
7072 * g_dbus_connection_register_object()) in a subtree registered with
7073 * g_dbus_connection_register_subtree() - if so, the subtree handler
7074 * is tried as the last resort. One way to think about a subtree
7075 * handler is to consider it a fallback handler for object paths not
7076 * registered via g_dbus_connection_register_object() or other bindings.
7078 * Note that @vtable will be copied so you cannot change it after
7081 * See this [server][gdbus-subtree-server] for an example of how to use
7084 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
7085 * that can be used with g_dbus_connection_unregister_subtree() .
7090 g_dbus_connection_register_subtree (GDBusConnection *connection,
7091 const gchar *object_path,
7092 const GDBusSubtreeVTable *vtable,
7093 GDBusSubtreeFlags flags,
7095 GDestroyNotify user_data_free_func,
7099 ExportedSubtree *es;
7101 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
7102 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
7103 g_return_val_if_fail (vtable != NULL, 0);
7104 g_return_val_if_fail (error == NULL || *error == NULL, 0);
7105 g_return_val_if_fail (check_initialized (connection), 0);
7109 CONNECTION_LOCK (connection);
7111 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
7117 _("A subtree is already exported for %s"),
7122 es = g_new0 (ExportedSubtree, 1);
7123 es->object_path = g_strdup (object_path);
7124 es->connection = connection;
7126 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
7128 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
7129 es->user_data = user_data;
7130 es->user_data_free_func = user_data_free_func;
7131 es->context = g_main_context_ref_thread_default ();
7133 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
7134 g_hash_table_insert (connection->map_id_to_es,
7135 GUINT_TO_POINTER (es->id),
7141 CONNECTION_UNLOCK (connection);
7146 /* ---------------------------------------------------------------------------------------------------- */
7149 * g_dbus_connection_unregister_subtree:
7150 * @connection: a #GDBusConnection
7151 * @registration_id: a subtree registration id obtained from
7152 * g_dbus_connection_register_subtree()
7154 * Unregisters a subtree.
7156 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise
7161 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
7162 guint registration_id)
7164 ExportedSubtree *es;
7167 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
7168 g_return_val_if_fail (check_initialized (connection), FALSE);
7172 CONNECTION_LOCK (connection);
7174 es = g_hash_table_lookup (connection->map_id_to_es,
7175 GUINT_TO_POINTER (registration_id));
7179 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
7180 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
7185 CONNECTION_UNLOCK (connection);
7190 /* ---------------------------------------------------------------------------------------------------- */
7192 /* may be called in any thread, with connection's lock held */
7194 handle_generic_ping_unlocked (GDBusConnection *connection,
7195 const gchar *object_path,
7196 GDBusMessage *message)
7198 GDBusMessage *reply;
7199 reply = g_dbus_message_new_method_reply (message);
7200 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7201 g_object_unref (reply);
7204 /* may be called in any thread, with connection's lock held */
7206 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
7207 const gchar *object_path,
7208 GDBusMessage *message)
7210 GDBusMessage *reply;
7213 if (connection->machine_id == NULL)
7218 connection->machine_id = _g_dbus_get_machine_id (&error);
7219 if (connection->machine_id == NULL)
7221 reply = g_dbus_message_new_method_error_literal (message,
7222 "org.freedesktop.DBus.Error.Failed",
7224 g_error_free (error);
7230 reply = g_dbus_message_new_method_reply (message);
7231 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
7233 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7234 g_object_unref (reply);
7237 /* may be called in any thread, with connection's lock held */
7239 handle_generic_introspect_unlocked (GDBusConnection *connection,
7240 const gchar *object_path,
7241 GDBusMessage *message)
7246 GDBusMessage *reply;
7248 /* first the header */
7249 s = g_string_new (NULL);
7250 introspect_append_header (s);
7252 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
7253 for (n = 0; registered != NULL && registered[n] != NULL; n++)
7254 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
7255 g_strfreev (registered);
7256 g_string_append (s, "</node>\n");
7258 reply = g_dbus_message_new_method_reply (message);
7259 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
7260 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7261 g_object_unref (reply);
7262 g_string_free (s, TRUE);
7265 /* may be called in any thread, with connection's lock held */
7267 handle_generic_unlocked (GDBusConnection *connection,
7268 GDBusMessage *message)
7271 const gchar *interface_name;
7272 const gchar *member;
7273 const gchar *signature;
7276 CONNECTION_ENSURE_LOCK (connection);
7280 interface_name = g_dbus_message_get_interface (message);
7281 member = g_dbus_message_get_member (message);
7282 signature = g_dbus_message_get_signature (message);
7283 path = g_dbus_message_get_path (message);
7285 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
7286 g_strcmp0 (member, "Introspect") == 0 &&
7287 g_strcmp0 (signature, "") == 0)
7289 handle_generic_introspect_unlocked (connection, path, message);
7292 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7293 g_strcmp0 (member, "Ping") == 0 &&
7294 g_strcmp0 (signature, "") == 0)
7296 handle_generic_ping_unlocked (connection, path, message);
7299 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7300 g_strcmp0 (member, "GetMachineId") == 0 &&
7301 g_strcmp0 (signature, "") == 0)
7303 handle_generic_get_machine_id_unlocked (connection, path, message);
7310 /* ---------------------------------------------------------------------------------------------------- */
7312 /* called in GDBusWorker thread with connection's lock held */
7314 distribute_method_call (GDBusConnection *connection,
7315 GDBusMessage *message)
7317 GDBusMessage *reply;
7319 ExportedSubtree *es;
7320 const gchar *object_path;
7321 const gchar *interface_name;
7322 const gchar *member;
7324 gchar *subtree_path;
7327 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
7329 interface_name = g_dbus_message_get_interface (message);
7330 member = g_dbus_message_get_member (message);
7331 path = g_dbus_message_get_path (message);
7332 subtree_path = g_strdup (path);
7333 needle = strrchr (subtree_path, '/');
7334 if (needle != NULL && needle != subtree_path)
7340 g_free (subtree_path);
7341 subtree_path = NULL;
7345 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
7347 _g_dbus_debug_print_lock ();
7348 g_print ("========================================================================\n"
7349 "GDBus-debug:Incoming:\n"
7350 " <<<< METHOD INVOCATION %s.%s()\n"
7352 " invoked by name %s\n"
7354 interface_name, member,
7356 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
7357 g_dbus_message_get_serial (message));
7358 _g_dbus_debug_print_unlock ();
7361 object_path = g_dbus_message_get_path (message);
7362 g_assert (object_path != NULL);
7364 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
7367 if (obj_message_func (connection, eo, message))
7371 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
7374 if (subtree_message_func (connection, es, message))
7378 if (subtree_path != NULL)
7380 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
7383 if (subtree_message_func (connection, es, message))
7388 if (handle_generic_unlocked (connection, message))
7391 /* if we end up here, the message has not been not handled - so return an error saying this */
7392 reply = g_dbus_message_new_method_error (message,
7393 "org.freedesktop.DBus.Error.UnknownMethod",
7394 _("No such interface '%s' on object at path %s"),
7397 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7398 g_object_unref (reply);
7401 g_free (subtree_path);
7404 /* ---------------------------------------------------------------------------------------------------- */
7406 /* Called in any user thread, with the message_bus_lock held. */
7408 message_bus_get_singleton (GBusType bus_type,
7412 const gchar *starter_bus;
7418 case G_BUS_TYPE_SESSION:
7419 ret = &the_session_bus;
7422 case G_BUS_TYPE_SYSTEM:
7423 ret = &the_system_bus;
7426 case G_BUS_TYPE_USER:
7427 ret = &the_user_bus;
7430 case G_BUS_TYPE_MACHINE:
7431 ret = &the_machine_bus;
7434 case G_BUS_TYPE_STARTER:
7435 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
7436 if (g_strcmp0 (starter_bus, "session") == 0)
7438 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
7441 else if (g_strcmp0 (starter_bus, "system") == 0)
7443 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
7448 if (starter_bus != NULL)
7452 G_IO_ERROR_INVALID_ARGUMENT,
7453 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
7454 " - unknown value '%s'"),
7459 g_set_error_literal (error,
7461 G_IO_ERROR_INVALID_ARGUMENT,
7462 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
7463 "variable is not set"));
7469 g_assert_not_reached ();
7477 /* Called in any user thread, without holding locks. */
7478 static GDBusConnection *
7479 get_uninitialized_connection (GBusType bus_type,
7480 GCancellable *cancellable,
7483 GWeakRef *singleton;
7484 GDBusConnection *ret;
7488 G_LOCK (message_bus_lock);
7489 singleton = message_bus_get_singleton (bus_type, error);
7490 if (singleton == NULL)
7493 ret = g_weak_ref_get (singleton);
7498 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
7499 if (address == NULL)
7501 ret = g_object_new (G_TYPE_DBUS_CONNECTION,
7503 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
7504 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
7505 "exit-on-close", TRUE,
7508 g_weak_ref_set (singleton, ret);
7512 g_assert (ret != NULL);
7515 G_UNLOCK (message_bus_lock);
7519 /* May be called from any thread. Must not hold message_bus_lock. */
7521 _g_bus_get_singleton_if_exists (GBusType bus_type)
7523 GWeakRef *singleton;
7524 GDBusConnection *ret = NULL;
7526 G_LOCK (message_bus_lock);
7527 singleton = message_bus_get_singleton (bus_type, NULL);
7528 if (singleton == NULL)
7531 ret = g_weak_ref_get (singleton);
7534 G_UNLOCK (message_bus_lock);
7540 * @bus_type: a #GBusType
7541 * @cancellable: (allow-none): a #GCancellable or %NULL
7542 * @error: return location for error or %NULL
7544 * Synchronously connects to the message bus specified by @bus_type.
7545 * Note that the returned object may shared with other callers,
7546 * e.g. if two separate parts of a process calls this function with
7547 * the same @bus_type, they will share the same object.
7549 * This is a synchronous failable function. See g_bus_get() and
7550 * g_bus_get_finish() for the asynchronous version.
7552 * The returned object is a singleton, that is, shared with other
7553 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7554 * event that you need a private message bus connection, use
7555 * g_dbus_address_get_for_bus_sync() and
7556 * g_dbus_connection_new_for_address().
7558 * Note that the returned #GDBusConnection object will (usually) have
7559 * the #GDBusConnection:exit-on-close property set to %TRUE.
7561 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7562 * Free with g_object_unref().
7567 g_bus_get_sync (GBusType bus_type,
7568 GCancellable *cancellable,
7571 GDBusConnection *connection;
7573 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7575 connection = get_uninitialized_connection (bus_type, cancellable, error);
7576 if (connection == NULL)
7579 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
7581 g_object_unref (connection);
7590 bus_get_async_initable_cb (GObject *source_object,
7594 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
7598 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
7602 g_assert (error != NULL);
7603 g_simple_async_result_take_error (simple, error);
7604 g_object_unref (source_object);
7608 g_simple_async_result_set_op_res_gpointer (simple,
7612 g_simple_async_result_complete_in_idle (simple);
7613 g_object_unref (simple);
7618 * @bus_type: a #GBusType
7619 * @cancellable: (allow-none): a #GCancellable or %NULL
7620 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
7621 * @user_data: the data to pass to @callback
7623 * Asynchronously connects to the message bus specified by @bus_type.
7625 * When the operation is finished, @callback will be invoked. You can
7626 * then call g_bus_get_finish() to get the result of the operation.
7628 * This is a asynchronous failable function. See g_bus_get_sync() for
7629 * the synchronous version.
7634 g_bus_get (GBusType bus_type,
7635 GCancellable *cancellable,
7636 GAsyncReadyCallback callback,
7639 GDBusConnection *connection;
7640 GSimpleAsyncResult *simple;
7643 simple = g_simple_async_result_new (NULL,
7647 g_simple_async_result_set_check_cancellable (simple, cancellable);
7650 connection = get_uninitialized_connection (bus_type, cancellable, &error);
7651 if (connection == NULL)
7653 g_assert (error != NULL);
7654 g_simple_async_result_take_error (simple, error);
7655 g_simple_async_result_complete_in_idle (simple);
7656 g_object_unref (simple);
7660 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
7663 bus_get_async_initable_cb,
7670 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
7672 * @error: return location for error or %NULL
7674 * Finishes an operation started with g_bus_get().
7676 * The returned object is a singleton, that is, shared with other
7677 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7678 * event that you need a private message bus connection, use
7679 * g_dbus_address_get_for_bus_sync() and
7680 * g_dbus_connection_new_for_address().
7682 * Note that the returned #GDBusConnection object will (usually) have
7683 * the #GDBusConnection:exit-on-close property set to %TRUE.
7685 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7686 * Free with g_object_unref().
7691 g_bus_get_finish (GAsyncResult *res,
7694 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
7696 GDBusConnection *ret;
7698 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7700 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
7704 if (g_simple_async_result_propagate_error (simple, error))
7707 object = g_simple_async_result_get_op_res_gpointer (simple);
7708 g_assert (object != NULL);
7709 ret = g_object_ref (G_DBUS_CONNECTION (object));
7715 /* ---------------------------------------------------------------------------------------------------- */