1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
18 * Author: David Zeuthen <davidz@redhat.com>
24 * - would be nice to expose GDBusAuthMechanism and an extension point
26 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
27 * the mechanism VFuncs need to be able to set an error.
29 * - Need to document other mechanisms/sources for determining the D-Bus
30 * address of a well-known bus.
32 * - e.g. on Win32 we need code like from here
34 * http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
36 * that was never copied over here because it originally was copy-paste
37 * from the GPLv2 / AFL 2.1 libdbus sources.
39 * - on OS X we need to look in launchd for the address
41 * https://bugs.freedesktop.org/show_bug.cgi?id=14259
43 * - on X11 we need to look in a X11 property on the X server
44 * - (we can also just use dbus-launch(1) from the D-Bus
47 * - (ideally) this requires D-Bus spec work because none of
48 * this has never really been specced out properly (except
51 * - Related to the above, we also need to be able to launch a message bus
52 * instance.... Since we don't want to write our own bus daemon we should
53 * launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
55 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
56 * to specify where the nonce is stored. This will allow people to use
57 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
58 * to easily achieve secure RPC via nonce-tcp.
60 * - need to expose an extension point for resolving D-Bus address and
61 * turning them into GIOStream objects. This will allow us to implement
62 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
64 * - see g_dbus_address_connect() in gdbusaddress.c
66 * - would be cute to use kernel-specific APIs to resolve fds for
67 * debug output when using G_DBUS_DEBUG=message, e.g. in addition to
69 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
71 * maybe we can show more information about what fd 21 really is.
72 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
73 * Initial experiments on Linux 2.6 suggests that the symlink looks
78 * e.g. not of much use.
80 * - GDBus High-Level docs
81 * - Proxy: properties, signals...
82 * - Connection: IOStream based, ::close, connection setup steps
83 * mainloop integration, threading
84 * - Differences from libdbus (extend "Migrating from")
85 * - the message handling thread
86 * - Using GVariant instead of GValue
87 * - Explain why the high-level API is a good thing and what
88 * kind of pitfalls it avoids
89 * - Export objects before claiming names
90 * - Talk about auto-starting services (cf. GBusNameWatcherFlags)
92 * - use abstract sockets in test code
93 * - right now it doesn't work, dbus-daemon(1) fails with
95 * /gdbus/connection/filter: Failed to start message bus: Failed to bind
96 * socket "/tmp/g-dbus-tests-pid-28531": Address already in use
97 * ** WARNING **: Error reading address from dbus daemon, 0 bytes read
107 #include "gdbusauth.h"
108 #include "gdbusutils.h"
109 #include "gdbusaddress.h"
110 #include "gdbusmessage.h"
111 #include "gdbusconnection.h"
112 #include "gdbuserror.h"
113 #include "gioenumtypes.h"
114 #include "gdbusintrospection.h"
115 #include "gdbusmethodinvocation.h"
116 #include "gdbusprivate.h"
117 #include "gdbusauthobserver.h"
118 #include "ginitable.h"
119 #include "gasyncinitable.h"
120 #include "giostream.h"
121 #include "gasyncresult.h"
122 #include "gsimpleasyncresult.h"
126 #include "gunixconnection.h"
127 #include "gunixfdmessage.h"
130 #include "glibintl.h"
133 * SECTION:gdbusconnection
134 * @short_description: D-Bus Connections
135 * @include: gio/gio.h
137 * The #GDBusConnection type is used for D-Bus connections to remote
138 * peers such as a message buses. It is a low-level API that offers a
139 * lot of flexibility. For instance, it lets you establish a connection
140 * over any transport that can by represented as an #GIOStream.
142 * This class is rarely used directly in D-Bus clients. If you are writing
143 * a D-Bus client, it is often easier to use the g_bus_own_name(),
144 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
146 * As an exception to the usual GLib rule that a particular object must not
147 * be used by two threads at the same time, #GDBusConnection's methods may be
148 * called from any thread. This is so that g_bus_get() and g_bus_get_sync()
149 * can safely return the same #GDBusConnection when called from any thread.
151 * Most of the ways to obtain a #GDBusConnection automatically initialize it
152 * (i.e. connect to D-Bus): for instance, g_dbus_connection_new() and
153 * g_bus_get(), and the synchronous versions of those methods, give you an
154 * initialized connection. Language bindings for GIO should use
155 * g_initable_new() or g_async_initable_new_async(), which also initialize the
158 * If you construct an uninitialized #GDBusConnection, such as via
159 * g_object_new(), you must initialize it via g_initable_init() or
160 * g_async_initable_init_async() before using its methods or properties.
161 * Calling methods or accessing properties on a #GDBusConnection that has not
162 * completed initialization successfully is considered to be invalid, and leads
163 * to undefined behaviour. In particular, if initialization fails with a
164 * #GError, the only valid thing you can do with that #GDBusConnection is to
165 * free it with g_object_unref().
167 * ## An example D-Bus server # {#gdbus-server}
169 * Here is an example for a D-Bus server:
170 * [gdbus-example-server.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-server.c)
172 * ## An example for exporting a subtree # {#gdbus-subtree-server}
174 * Here is an example for exporting a subtree:
175 * [gdbus-example-subtree.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-subtree.c)
177 * ## An example for file descriptor passing # {#gdbus-unix-fd-client}
179 * Here is an example for passing UNIX file descriptors:
180 * [gdbus-unix-fd-client.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-unix-fd-client.c)
182 * ## An example for exporting a GObject # {#gdbus-export}
184 * Here is an example for exporting a #GObject:
185 * [gdbus-example-export.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-export.c)
188 /* ---------------------------------------------------------------------------------------------------- */
190 typedef struct _GDBusConnectionClass GDBusConnectionClass;
193 * GDBusConnectionClass:
194 * @closed: Signal class handler for the #GDBusConnection::closed signal.
196 * Class structure for #GDBusConnection.
200 struct _GDBusConnectionClass
203 GObjectClass parent_class;
207 void (*closed) (GDBusConnection *connection,
208 gboolean remote_peer_vanished,
212 G_LOCK_DEFINE_STATIC (message_bus_lock);
214 static GWeakRef the_session_bus;
215 static GWeakRef the_system_bus;
216 static GWeakRef the_user_bus;
217 static GWeakRef the_machine_bus;
219 /* Extra pseudo-member of GDBusSendMessageFlags.
220 * Set by initable_init() to indicate that despite not being initialized yet,
221 * enough of the only-valid-after-init members are set that we can send a
222 * message, and we're being called from its thread, so no memory barrier is
223 * required before accessing them.
225 #define SEND_MESSAGE_FLAGS_INITIALIZING (1<<31)
227 /* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
228 #define CALL_FLAGS_INITIALIZING (1<<31)
230 /* ---------------------------------------------------------------------------------------------------- */
234 GDestroyNotify callback;
236 GMainContext *context;
237 } CallDestroyNotifyData;
240 call_destroy_notify_data_in_idle (gpointer user_data)
242 CallDestroyNotifyData *data = user_data;
243 data->callback (data->user_data);
248 call_destroy_notify_data_free (CallDestroyNotifyData *data)
250 if (data->context != NULL)
251 g_main_context_unref (data->context);
256 * call_destroy_notify: <internal>
257 * @context: (allow-none): A #GMainContext or %NULL.
258 * @callback: (allow-none): A #GDestroyNotify or %NULL.
259 * @user_data: Data to pass to @callback.
261 * Schedules @callback to run in @context.
264 call_destroy_notify (GMainContext *context,
265 GDestroyNotify callback,
268 GSource *idle_source;
269 CallDestroyNotifyData *data;
271 if (callback == NULL)
274 data = g_new0 (CallDestroyNotifyData, 1);
275 data->callback = callback;
276 data->user_data = user_data;
277 data->context = context;
278 if (data->context != NULL)
279 g_main_context_ref (data->context);
281 idle_source = g_idle_source_new ();
282 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
283 g_source_set_callback (idle_source,
284 call_destroy_notify_data_in_idle,
286 (GDestroyNotify) call_destroy_notify_data_free);
287 g_source_set_name (idle_source, "[gio] call_destroy_notify_data_in_idle");
288 g_source_attach (idle_source, data->context);
289 g_source_unref (idle_source);
295 /* ---------------------------------------------------------------------------------------------------- */
298 _g_strv_has_string (const gchar* const *haystack,
303 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
305 if (g_strcmp0 (haystack[n], needle) == 0)
311 /* ---------------------------------------------------------------------------------------------------- */
314 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
316 // TODO: for some reason this doesn't work on Windows
317 #define CONNECTION_ENSURE_LOCK(obj) do { \
318 if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock))) \
320 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
321 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
326 #define CONNECTION_LOCK(obj) do { \
327 g_mutex_lock (&(obj)->lock); \
330 #define CONNECTION_UNLOCK(obj) do { \
331 g_mutex_unlock (&(obj)->lock); \
334 /* Flags in connection->atomic_flags */
336 FLAG_INITIALIZED = 1 << 0,
337 FLAG_EXIT_ON_CLOSE = 1 << 1,
344 * The #GDBusConnection structure contains only private data and
345 * should only be accessed using the provided API.
349 struct _GDBusConnection
352 GObject parent_instance;
354 /* ------------------------------------------------------------------------ */
355 /* -- General object state ------------------------------------------------ */
356 /* ------------------------------------------------------------------------ */
358 /* General-purpose lock for most fields */
361 /* A lock used in the init() method of the GInitable interface - see comments
362 * in initable_init() for why a separate lock is needed.
364 * If you need both @lock and @init_lock, you must take @init_lock first.
368 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
369 * someone calls org.freedesktop.DBus.Peer.GetMachineId(). Protected by @lock.
373 /* The underlying stream used for communication
374 * Read-only after initable_init(), so it may be read if you either
375 * hold @init_lock or check for initialization first.
379 /* The object used for authentication (if any).
380 * Read-only after initable_init(), so it may be read if you either
381 * hold @init_lock or check for initialization first.
385 /* Last serial used. Protected by @lock. */
388 /* The object used to send/receive messages.
389 * Read-only after initable_init(), so it may be read if you either
390 * hold @init_lock or check for initialization first.
393 GKDBusWorker *kdbus_worker;
395 /* If connected to a message bus, this contains the unique name assigned to
396 * us by the bus (e.g. ":1.42").
397 * Read-only after initable_init(), so it may be read if you either
398 * hold @init_lock or check for initialization first.
400 gchar *bus_unique_name;
402 /* The GUID returned by the other side if we authenticed as a client or
403 * the GUID to use if authenticating as a server.
404 * Read-only after initable_init(), so it may be read if you either
405 * hold @init_lock or check for initialization first.
409 /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
410 * Inspect @initialization_error to see whether it succeeded or failed.
412 * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
414 * FLAG_CLOSED is the closed property. It may be read at any time, but
415 * may only be written while holding @lock.
417 volatile gint atomic_flags;
419 /* If the connection could not be established during initable_init(),
420 * this GError will be set.
421 * Read-only after initable_init(), so it may be read if you either
422 * hold @init_lock or check for initialization first.
424 GError *initialization_error;
426 /* The result of g_main_context_ref_thread_default() when the object
427 * was created (the GObject _init() function) - this is used for delivery
428 * of the :closed GObject signal.
430 * Only set in the GObject init function, so no locks are needed.
432 GMainContext *main_context_at_construction;
434 /* Read-only construct properties, no locks needed */
436 GDBusConnectionFlags flags;
438 /* Map used for managing method replies, protected by @lock */
439 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
441 /* Maps used for managing signal subscription, protected by @lock */
442 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
443 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
444 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
446 /* Maps used for managing exported objects and subtrees,
449 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
450 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
451 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
452 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
454 /* Map used for storing last used serials for each thread, protected by @lock */
455 GHashTable *map_thread_to_last_serial;
457 /* Structure used for message filters, protected by @lock */
460 /* Capabilities negotiated during authentication
461 * Read-only after initable_init(), so it may be read without holding a
462 * lock, if you check for initialization first.
464 GDBusCapabilityFlags capabilities;
466 /* Protected by @init_lock */
467 GDBusAuthObserver *authentication_observer;
469 /* Read-only after initable_init(), so it may be read if you either
470 * hold @init_lock or check for initialization first.
472 GCredentials *credentials;
474 /* set to TRUE when finalizing */
478 typedef struct ExportedObject ExportedObject;
479 static void exported_object_free (ExportedObject *eo);
481 typedef struct ExportedSubtree ExportedSubtree;
482 static void exported_subtree_free (ExportedSubtree *es);
500 PROP_CAPABILITY_FLAGS,
501 PROP_AUTHENTICATION_OBSERVER,
504 static void distribute_signals (GDBusConnection *connection,
505 GDBusMessage *message);
507 static void distribute_method_call (GDBusConnection *connection,
508 GDBusMessage *message);
510 static gboolean handle_generic_unlocked (GDBusConnection *connection,
511 GDBusMessage *message);
514 static void purge_all_signal_subscriptions (GDBusConnection *connection);
515 static void purge_all_filters (GDBusConnection *connection);
517 static void schedule_method_call (GDBusConnection *connection,
518 GDBusMessage *message,
519 guint registration_id,
520 guint subtree_registration_id,
521 const GDBusInterfaceInfo *interface_info,
522 const GDBusMethodInfo *method_info,
523 const GDBusPropertyInfo *property_info,
524 GVariant *parameters,
525 const GDBusInterfaceVTable *vtable,
526 GMainContext *main_context,
529 #define _G_ENSURE_LOCK(name) do { \
530 if (G_UNLIKELY (G_TRYLOCK(name))) \
532 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
533 "_G_ENSURE_LOCK: Lock '" #name "' is not locked"); \
537 static guint signals[LAST_SIGNAL] = { 0 };
539 static void initable_iface_init (GInitableIface *initable_iface);
540 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
542 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
543 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
544 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
548 * Check that all members of @connection that can only be accessed after
549 * the connection is initialized can safely be accessed. If not,
550 * log a critical warning. This function is a memory barrier.
552 * Returns: %TRUE if initialized
555 check_initialized (GDBusConnection *connection)
557 /* The access to @atomic_flags isn't conditional, so that this function
558 * provides a memory barrier for thread-safety even if checks are disabled.
559 * (If you don't want this stricter guarantee, you can call
560 * g_return_if_fail (check_initialized (c)).)
562 * This isn't strictly necessary now that we've decided use of an
563 * uninitialized GDBusConnection is undefined behaviour, but it seems
564 * better to be as deterministic as is feasible.
566 * (Anything that could suffer a crash from seeing undefined values
567 * must have a race condition - thread A initializes the connection while
568 * thread B calls a method without initialization, hoping that thread A will
569 * win the race - so its behaviour is undefined anyway.)
571 gint flags = g_atomic_int_get (&connection->atomic_flags);
573 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
575 /* We can safely access this, due to the memory barrier above */
576 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
582 MAY_BE_UNINITIALIZED = (1<<1)
583 } CheckUnclosedFlags;
586 * Check the same thing as check_initialized(), and also that the
587 * connection is not closed. If the connection is uninitialized,
588 * raise a critical warning (it's programmer error); if it's closed,
589 * raise a recoverable GError (it's a runtime error).
591 * This function is a memory barrier.
593 * Returns: %TRUE if initialized and not closed
596 check_unclosed (GDBusConnection *connection,
597 CheckUnclosedFlags check,
600 /* check_initialized() is effectively inlined, so we don't waste time
601 * doing two memory barriers
603 gint flags = g_atomic_int_get (&connection->atomic_flags);
605 if (!(check & MAY_BE_UNINITIALIZED))
607 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
608 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
611 if (flags & FLAG_CLOSED)
613 g_set_error_literal (error,
616 _("The connection is closed"));
623 static GHashTable *alive_connections = NULL;
626 g_dbus_connection_dispose (GObject *object)
628 GDBusConnection *connection = G_DBUS_CONNECTION (object);
630 G_LOCK (message_bus_lock);
631 CONNECTION_LOCK (connection);
632 if (connection->worker != NULL)
634 _g_dbus_worker_stop (connection->worker);
635 connection->worker = NULL;
636 if (alive_connections != NULL)
637 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
641 if (alive_connections != NULL)
642 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
644 CONNECTION_UNLOCK (connection);
645 G_UNLOCK (message_bus_lock);
647 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
648 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
652 g_dbus_connection_finalize (GObject *object)
654 GDBusConnection *connection = G_DBUS_CONNECTION (object);
656 connection->finalizing = TRUE;
658 purge_all_signal_subscriptions (connection);
660 purge_all_filters (connection);
661 g_ptr_array_unref (connection->filters);
663 if (connection->authentication_observer != NULL)
664 g_object_unref (connection->authentication_observer);
666 if (connection->auth != NULL)
667 g_object_unref (connection->auth);
669 if (connection->credentials)
670 g_object_unref (connection->credentials);
672 if (connection->stream != NULL)
674 g_object_unref (connection->stream);
675 connection->stream = NULL;
678 g_free (connection->address);
680 g_free (connection->guid);
681 g_free (connection->bus_unique_name);
683 if (connection->initialization_error != NULL)
684 g_error_free (connection->initialization_error);
686 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
688 g_hash_table_unref (connection->map_rule_to_signal_data);
689 g_hash_table_unref (connection->map_id_to_signal_data);
690 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
692 g_hash_table_unref (connection->map_id_to_ei);
693 g_hash_table_unref (connection->map_object_path_to_eo);
694 g_hash_table_unref (connection->map_id_to_es);
695 g_hash_table_unref (connection->map_object_path_to_es);
697 g_hash_table_unref (connection->map_thread_to_last_serial);
699 g_main_context_unref (connection->main_context_at_construction);
701 g_free (connection->machine_id);
703 g_mutex_clear (&connection->init_lock);
704 g_mutex_clear (&connection->lock);
706 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
709 /* called in any user thread, with the connection's lock not held */
711 g_dbus_connection_get_property (GObject *object,
716 GDBusConnection *connection = G_DBUS_CONNECTION (object);
721 g_value_set_object (value, g_dbus_connection_get_stream (connection));
725 g_value_set_string (value, g_dbus_connection_get_guid (connection));
728 case PROP_UNIQUE_NAME:
729 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
733 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
736 case PROP_EXIT_ON_CLOSE:
737 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
740 case PROP_CAPABILITY_FLAGS:
741 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
745 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
750 /* called in any user thread, with the connection's lock not held */
752 g_dbus_connection_set_property (GObject *object,
757 GDBusConnection *connection = G_DBUS_CONNECTION (object);
762 connection->stream = g_value_dup_object (value);
766 connection->guid = g_value_dup_string (value);
770 connection->address = g_value_dup_string (value);
774 connection->flags = g_value_get_flags (value);
777 case PROP_EXIT_ON_CLOSE:
778 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
781 case PROP_AUTHENTICATION_OBSERVER:
782 connection->authentication_observer = g_value_dup_object (value);
786 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
791 /* Base-class implementation of GDBusConnection::closed.
793 * Called in a user thread, by the main context that was thread-default when
794 * the object was constructed.
797 g_dbus_connection_real_closed (GDBusConnection *connection,
798 gboolean remote_peer_vanished,
801 gint flags = g_atomic_int_get (&connection->atomic_flags);
803 /* Because atomic int access is a memory barrier, we can safely read
804 * initialization_error without a lock, as long as we do it afterwards.
806 if (remote_peer_vanished &&
807 (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
808 (flags & FLAG_INITIALIZED) != 0 &&
809 connection->initialization_error == NULL)
813 g_printerr ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
816 g_quark_to_string (error->domain), error->code);
820 g_printerr ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
827 g_dbus_connection_class_init (GDBusConnectionClass *klass)
829 GObjectClass *gobject_class;
831 gobject_class = G_OBJECT_CLASS (klass);
833 gobject_class->finalize = g_dbus_connection_finalize;
834 gobject_class->dispose = g_dbus_connection_dispose;
835 gobject_class->set_property = g_dbus_connection_set_property;
836 gobject_class->get_property = g_dbus_connection_get_property;
838 klass->closed = g_dbus_connection_real_closed;
841 * GDBusConnection:stream:
843 * The underlying #GIOStream used for I/O.
845 * If this is passed on construction and is a #GSocketConnection,
846 * then the corresponding #GSocket will be put into non-blocking mode.
848 * While the #GDBusConnection is active, it will interact with this
849 * stream from a worker thread, so it is not safe to interact with
850 * the stream directly.
854 g_object_class_install_property (gobject_class,
856 g_param_spec_object ("stream",
858 P_("The underlying streams used for I/O"),
862 G_PARAM_CONSTRUCT_ONLY |
863 G_PARAM_STATIC_NAME |
864 G_PARAM_STATIC_BLURB |
865 G_PARAM_STATIC_NICK));
868 * GDBusConnection:address:
870 * A D-Bus address specifying potential endpoints that can be used
871 * when establishing the connection.
875 g_object_class_install_property (gobject_class,
877 g_param_spec_string ("address",
879 P_("D-Bus address specifying potential socket endpoints"),
882 G_PARAM_CONSTRUCT_ONLY |
883 G_PARAM_STATIC_NAME |
884 G_PARAM_STATIC_BLURB |
885 G_PARAM_STATIC_NICK));
888 * GDBusConnection:flags:
890 * Flags from the #GDBusConnectionFlags enumeration.
894 g_object_class_install_property (gobject_class,
896 g_param_spec_flags ("flags",
899 G_TYPE_DBUS_CONNECTION_FLAGS,
900 G_DBUS_CONNECTION_FLAGS_NONE,
902 G_PARAM_CONSTRUCT_ONLY |
903 G_PARAM_STATIC_NAME |
904 G_PARAM_STATIC_BLURB |
905 G_PARAM_STATIC_NICK));
908 * GDBusConnection:guid:
910 * The GUID of the peer performing the role of server when
913 * If you are constructing a #GDBusConnection and pass
914 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
915 * #GDBusConnection:flags property then you MUST also set this
916 * property to a valid guid.
918 * If you are constructing a #GDBusConnection and pass
919 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
920 * #GDBusConnection:flags property you will be able to read the GUID
921 * of the other peer here after the connection has been successfully
926 g_object_class_install_property (gobject_class,
928 g_param_spec_string ("guid",
930 P_("GUID of the server peer"),
934 G_PARAM_CONSTRUCT_ONLY |
935 G_PARAM_STATIC_NAME |
936 G_PARAM_STATIC_BLURB |
937 G_PARAM_STATIC_NICK));
940 * GDBusConnection:unique-name:
942 * The unique name as assigned by the message bus or %NULL if the
943 * connection is not open or not a message bus connection.
947 g_object_class_install_property (gobject_class,
949 g_param_spec_string ("unique-name",
951 P_("Unique name of bus connection"),
954 G_PARAM_STATIC_NAME |
955 G_PARAM_STATIC_BLURB |
956 G_PARAM_STATIC_NICK));
959 * GDBusConnection:closed:
961 * A boolean specifying whether the connection has been closed.
965 g_object_class_install_property (gobject_class,
967 g_param_spec_boolean ("closed",
969 P_("Whether the connection is closed"),
972 G_PARAM_STATIC_NAME |
973 G_PARAM_STATIC_BLURB |
974 G_PARAM_STATIC_NICK));
977 * GDBusConnection:exit-on-close:
979 * A boolean specifying whether the process will be terminated (by
980 * calling `raise(SIGTERM)`) if the connection is closed by the
983 * Note that #GDBusConnection objects returned by g_bus_get_finish()
984 * and g_bus_get_sync() will (usually) have this property set to %TRUE.
988 g_object_class_install_property (gobject_class,
990 g_param_spec_boolean ("exit-on-close",
992 P_("Whether the process is terminated when the connection is closed"),
996 G_PARAM_STATIC_NAME |
997 G_PARAM_STATIC_BLURB |
998 G_PARAM_STATIC_NICK));
1001 * GDBusConnection:capabilities:
1003 * Flags from the #GDBusCapabilityFlags enumeration
1004 * representing connection features negotiated with the other peer.
1008 g_object_class_install_property (gobject_class,
1009 PROP_CAPABILITY_FLAGS,
1010 g_param_spec_flags ("capabilities",
1013 G_TYPE_DBUS_CAPABILITY_FLAGS,
1014 G_DBUS_CAPABILITY_FLAGS_NONE,
1016 G_PARAM_STATIC_NAME |
1017 G_PARAM_STATIC_BLURB |
1018 G_PARAM_STATIC_NICK));
1021 * GDBusConnection:authentication-observer:
1023 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
1027 g_object_class_install_property (gobject_class,
1028 PROP_AUTHENTICATION_OBSERVER,
1029 g_param_spec_object ("authentication-observer",
1030 P_("Authentication Observer"),
1031 P_("Object used to assist in the authentication process"),
1032 G_TYPE_DBUS_AUTH_OBSERVER,
1034 G_PARAM_CONSTRUCT_ONLY |
1035 G_PARAM_STATIC_NAME |
1036 G_PARAM_STATIC_BLURB |
1037 G_PARAM_STATIC_NICK));
1040 * GDBusConnection::closed:
1041 * @connection: the #GDBusConnection emitting the signal
1042 * @remote_peer_vanished: %TRUE if @connection is closed because the
1043 * remote peer closed its end of the connection
1044 * @error: (allow-none): a #GError with more details about the event or %NULL
1046 * Emitted when the connection is closed.
1048 * The cause of this event can be
1050 * - If g_dbus_connection_close() is called. In this case
1051 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
1053 * - If the remote peer closes the connection. In this case
1054 * @remote_peer_vanished is set to %TRUE and @error is set.
1056 * - If the remote peer sends invalid or malformed data. In this
1057 * case @remote_peer_vanished is set to %FALSE and @error is set.
1059 * Upon receiving this signal, you should give up your reference to
1060 * @connection. You are guaranteed that this signal is emitted only
1065 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
1066 G_TYPE_DBUS_CONNECTION,
1068 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1079 g_dbus_connection_init (GDBusConnection *connection)
1081 g_mutex_init (&connection->lock);
1082 g_mutex_init (&connection->init_lock);
1084 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
1086 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1088 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1090 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1093 (GDestroyNotify) g_ptr_array_unref);
1095 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1098 (GDestroyNotify) exported_object_free);
1100 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1103 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1106 (GDestroyNotify) exported_subtree_free);
1108 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1111 connection->map_thread_to_last_serial = g_hash_table_new (g_direct_hash,
1114 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1116 connection->filters = g_ptr_array_new ();
1120 * g_dbus_connection_get_stream:
1121 * @connection: a #GDBusConnection
1123 * Gets the underlying stream used for IO.
1125 * While the #GDBusConnection is active, it will interact with this
1126 * stream from a worker thread, so it is not safe to interact with
1127 * the stream directly.
1129 * Returns: (transfer none): the stream used for IO
1134 g_dbus_connection_get_stream (GDBusConnection *connection)
1136 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1138 /* do not use g_return_val_if_fail(), we want the memory barrier */
1139 if (!check_initialized (connection))
1142 return connection->stream;
1146 * g_dbus_connection_start_message_processing:
1147 * @connection: a #GDBusConnection
1149 * If @connection was created with
1150 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1151 * starts processing messages. Does nothing on if @connection wasn't
1152 * created with this flag or if the method has already been called.
1157 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1159 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1161 /* do not use g_return_val_if_fail(), we want the memory barrier */
1162 if (!check_initialized (connection))
1165 g_assert (connection->worker || connection->kdbus_worker);
1167 if (connection->kdbus_worker)
1168 g_kdbus_worker_unfreeze (connection->kdbus_worker);
1170 _g_dbus_worker_unfreeze (connection->worker);
1174 * g_dbus_connection_is_closed:
1175 * @connection: a #GDBusConnection
1177 * Gets whether @connection is closed.
1179 * Returns: %TRUE if the connection is closed, %FALSE otherwise
1184 g_dbus_connection_is_closed (GDBusConnection *connection)
1188 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1190 flags = g_atomic_int_get (&connection->atomic_flags);
1192 return (flags & FLAG_CLOSED) ? TRUE : FALSE;
1196 * g_dbus_connection_get_capabilities:
1197 * @connection: a #GDBusConnection
1199 * Gets the capabilities negotiated with the remote peer
1201 * Returns: zero or more flags from the #GDBusCapabilityFlags enumeration
1205 GDBusCapabilityFlags
1206 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1208 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1210 /* do not use g_return_val_if_fail(), we want the memory barrier */
1211 if (!check_initialized (connection))
1212 return G_DBUS_CAPABILITY_FLAGS_NONE;
1214 return connection->capabilities;
1217 /* ---------------------------------------------------------------------------------------------------- */
1219 /* Called in a temporary thread without holding locks. */
1221 flush_in_thread_func (GSimpleAsyncResult *res,
1223 GCancellable *cancellable)
1228 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1231 g_simple_async_result_take_error (res, error);
1235 * g_dbus_connection_flush:
1236 * @connection: a #GDBusConnection
1237 * @cancellable: (allow-none): a #GCancellable or %NULL
1238 * @callback: (allow-none): a #GAsyncReadyCallback to call when the
1239 * request is satisfied or %NULL if you don't care about the result
1240 * @user_data: The data to pass to @callback
1242 * Asynchronously flushes @connection, that is, writes all queued
1243 * outgoing message to the transport and then flushes the transport
1244 * (using g_output_stream_flush_async()). This is useful in programs
1245 * that wants to emit a D-Bus signal and then exit immediately. Without
1246 * flushing the connection, there is no guaranteed that the message has
1247 * been sent to the networking buffers in the OS kernel.
1249 * This is an asynchronous method. When the operation is finished,
1250 * @callback will be invoked in the
1251 * [thread-default main context][g-main-context-push-thread-default]
1252 * of the thread you are calling this method from. You can
1253 * then call g_dbus_connection_flush_finish() to get the result of the
1254 * operation. See g_dbus_connection_flush_sync() for the synchronous
1260 g_dbus_connection_flush (GDBusConnection *connection,
1261 GCancellable *cancellable,
1262 GAsyncReadyCallback callback,
1265 GSimpleAsyncResult *simple;
1267 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1269 simple = g_simple_async_result_new (G_OBJECT (connection),
1272 g_dbus_connection_flush);
1273 g_simple_async_result_set_check_cancellable (simple, cancellable);
1274 g_simple_async_result_run_in_thread (simple,
1275 flush_in_thread_func,
1278 g_object_unref (simple);
1282 * g_dbus_connection_flush_finish:
1283 * @connection: a #GDBusConnection
1284 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1285 * to g_dbus_connection_flush()
1286 * @error: return location for error or %NULL
1288 * Finishes an operation started with g_dbus_connection_flush().
1290 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1295 g_dbus_connection_flush_finish (GDBusConnection *connection,
1299 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1304 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1305 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1306 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1308 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1310 if (g_simple_async_result_propagate_error (simple, error))
1320 * g_dbus_connection_flush_sync:
1321 * @connection: a #GDBusConnection
1322 * @cancellable: (allow-none): a #GCancellable or %NULL
1323 * @error: return location for error or %NULL
1325 * Synchronously flushes @connection. The calling thread is blocked
1326 * until this is done. See g_dbus_connection_flush() for the
1327 * asynchronous version of this method and more details about what it
1330 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1335 g_dbus_connection_flush_sync (GDBusConnection *connection,
1336 GCancellable *cancellable,
1341 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1342 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1346 /* This is only a best-effort attempt to see whether the connection is
1347 * closed, so it doesn't need the lock. If the connection closes just
1348 * after this check, but before scheduling the flush operation, the
1349 * result will be more or less the same as if the connection closed while
1350 * the flush operation was pending - it'll fail with either CLOSED or
1353 if (!check_unclosed (connection, 0, error))
1356 if (connection->kdbus_worker)
1362 g_assert (connection->worker != NULL);
1364 ret = _g_dbus_worker_flush_sync (connection->worker,
1372 /* ---------------------------------------------------------------------------------------------------- */
1376 GDBusConnection *connection;
1378 gboolean remote_peer_vanished;
1382 emit_closed_data_free (EmitClosedData *data)
1384 g_object_unref (data->connection);
1385 if (data->error != NULL)
1386 g_error_free (data->error);
1390 /* Called in a user thread that has acquired the main context that was
1391 * thread-default when the object was constructed
1394 emit_closed_in_idle (gpointer user_data)
1396 EmitClosedData *data = user_data;
1399 g_object_notify (G_OBJECT (data->connection), "closed");
1400 g_signal_emit (data->connection,
1401 signals[CLOSED_SIGNAL],
1403 data->remote_peer_vanished,
1409 /* Can be called from any thread, must hold lock.
1410 * FLAG_CLOSED must already have been set.
1413 schedule_closed_unlocked (GDBusConnection *connection,
1414 gboolean remote_peer_vanished,
1417 GSource *idle_source;
1418 EmitClosedData *data;
1420 CONNECTION_ENSURE_LOCK (connection);
1422 data = g_new0 (EmitClosedData, 1);
1423 data->connection = g_object_ref (connection);
1424 data->remote_peer_vanished = remote_peer_vanished;
1425 data->error = error != NULL ? g_error_copy (error) : NULL;
1427 idle_source = g_idle_source_new ();
1428 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1429 g_source_set_callback (idle_source,
1430 emit_closed_in_idle,
1432 (GDestroyNotify) emit_closed_data_free);
1433 g_source_set_name (idle_source, "[gio] emit_closed_in_idle");
1434 g_source_attach (idle_source, connection->main_context_at_construction);
1435 g_source_unref (idle_source);
1438 /* ---------------------------------------------------------------------------------------------------- */
1441 * g_dbus_connection_close:
1442 * @connection: a #GDBusConnection
1443 * @cancellable: (allow-none): a #GCancellable or %NULL
1444 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request is
1445 * satisfied or %NULL if you don't care about the result
1446 * @user_data: The data to pass to @callback
1448 * Closes @connection. Note that this never causes the process to
1449 * exit (this might only happen if the other end of a shared message
1450 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1452 * Once the connection is closed, operations such as sending a message
1453 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1454 * will not automatically flush the connection so queued messages may
1455 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1457 * If @connection is already closed, this method fails with
1458 * %G_IO_ERROR_CLOSED.
1460 * When @connection has been closed, the #GDBusConnection::closed
1461 * signal is emitted in the
1462 * [thread-default main context][g-main-context-push-thread-default]
1463 * of the thread that @connection was constructed in.
1465 * This is an asynchronous method. When the operation is finished,
1466 * @callback will be invoked in the
1467 * [thread-default main context][g-main-context-push-thread-default]
1468 * of the thread you are calling this method from. You can
1469 * then call g_dbus_connection_close_finish() to get the result of the
1470 * operation. See g_dbus_connection_close_sync() for the synchronous
1476 g_dbus_connection_close (GDBusConnection *connection,
1477 GCancellable *cancellable,
1478 GAsyncReadyCallback callback,
1481 GSimpleAsyncResult *simple;
1483 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1485 /* do not use g_return_val_if_fail(), we want the memory barrier */
1486 if (!check_initialized (connection))
1489 g_assert (connection->worker != NULL);
1491 simple = g_simple_async_result_new (G_OBJECT (connection),
1494 g_dbus_connection_close);
1495 g_simple_async_result_set_check_cancellable (simple, cancellable);
1496 _g_dbus_worker_close (connection->worker, cancellable, simple);
1497 g_object_unref (simple);
1501 * g_dbus_connection_close_finish:
1502 * @connection: a #GDBusConnection
1503 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1504 * to g_dbus_connection_close()
1505 * @error: return location for error or %NULL
1507 * Finishes an operation started with g_dbus_connection_close().
1509 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1514 g_dbus_connection_close_finish (GDBusConnection *connection,
1518 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1523 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1524 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1525 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1527 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1529 if (g_simple_async_result_propagate_error (simple, error))
1540 GAsyncResult *result;
1543 /* Can be called by any thread, without the connection lock */
1545 sync_close_cb (GObject *source_object,
1549 SyncCloseData *data = user_data;
1551 data->result = g_object_ref (res);
1552 g_main_loop_quit (data->loop);
1556 * g_dbus_connection_close_sync:
1557 * @connection: a #GDBusConnection
1558 * @cancellable: (allow-none): a #GCancellable or %NULL
1559 * @error: return location for error or %NULL
1561 * Synchronously closees @connection. The calling thread is blocked
1562 * until this is done. See g_dbus_connection_close() for the
1563 * asynchronous version of this method and more details about what it
1566 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1571 g_dbus_connection_close_sync (GDBusConnection *connection,
1572 GCancellable *cancellable,
1577 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1578 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1582 if (check_unclosed (connection, 0, error))
1584 GMainContext *context;
1587 context = g_main_context_new ();
1588 g_main_context_push_thread_default (context);
1589 data.loop = g_main_loop_new (context, TRUE);
1592 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1593 g_main_loop_run (data.loop);
1594 ret = g_dbus_connection_close_finish (connection, data.result, error);
1596 g_object_unref (data.result);
1597 g_main_loop_unref (data.loop);
1598 g_main_context_pop_thread_default (context);
1599 g_main_context_unref (context);
1605 /* ---------------------------------------------------------------------------------------------------- */
1608 * g_dbus_request_name:
1609 * @connection: a #GDBusConnection
1610 * @name: well-known bus name (name to request)
1611 * @flags: a set of flags from the GBusNameOwnerFlags enumeration
1612 * @error: return location for error or %NULL
1614 * Synchronously acquires name on the bus and returns status code.
1616 * The calling thread is blocked until a reply is received.
1618 * Returns: status code or %G_BUS_REQUEST_NAME_FLAGS_ERROR
1623 GBusRequestNameReplyFlags
1624 g_dbus_request_name (GDBusConnection *connection,
1626 GBusNameOwnerFlags flags,
1630 guint32 request_name_reply;
1632 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_BUS_RELEASE_NAME_FLAGS_ERROR);
1633 g_return_val_if_fail (g_dbus_is_name (name) && !g_dbus_is_unique_name (name), G_BUS_RELEASE_NAME_FLAGS_ERROR);
1634 g_return_val_if_fail (error == NULL || *error == NULL, G_BUS_RELEASE_NAME_FLAGS_ERROR);
1636 if (connection->kdbus_worker)
1637 result = _g_kdbus_RequestName (connection->kdbus_worker, name, flags, error);
1639 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/org/freedesktop/DBus",
1640 "org.freedesktop.DBus", "RequestName",
1641 g_variant_new ("(su)", name, flags), G_VARIANT_TYPE ("(u)"),
1642 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1646 g_variant_get (result, "(u)", &request_name_reply);
1647 g_variant_unref (result);
1650 request_name_reply = G_BUS_REQUEST_NAME_FLAGS_ERROR;
1652 return (GBusRequestNameReplyFlags) request_name_reply;
1656 * g_dbus_release_name:
1657 * @connection: a #GDBusConnection
1658 * @name: well-known bus name (name to release)
1659 * @error: return location for error or %NULL
1661 * Synchronously releases name on the bus and returns status code.
1663 * The calling thread is blocked until a reply is received.
1665 * Returns: status code or %G_BUS_RELEASE_NAME_FLAGS_ERROR
1670 GBusReleaseNameReplyFlags
1671 g_dbus_release_name (GDBusConnection *connection,
1676 guint32 release_name_reply;
1678 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_BUS_RELEASE_NAME_FLAGS_ERROR);
1679 g_return_val_if_fail (g_dbus_is_name (name) && !g_dbus_is_unique_name (name), G_BUS_RELEASE_NAME_FLAGS_ERROR);
1680 g_return_val_if_fail (error == NULL || *error == NULL, G_BUS_RELEASE_NAME_FLAGS_ERROR);
1682 if (connection->kdbus_worker)
1683 result = _g_kdbus_ReleaseName (connection->kdbus_worker, name, error);
1685 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/org/freedesktop/DBus",
1686 "org.freedesktop.DBus", "ReleaseName",
1687 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(u)"),
1688 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1692 g_variant_get (result, "(u)", &release_name_reply);
1693 g_variant_unref (result);
1696 release_name_reply = G_BUS_RELEASE_NAME_FLAGS_ERROR;
1698 return (GBusReleaseNameReplyFlags) release_name_reply;
1702 * g_dbus_get_bus_id:
1703 * @connection: a #GDBusConnection
1704 * @error: return location for error or %NULL
1706 * Synchronously returns the unique ID of the bus.
1708 * The calling thread is blocked until a reply is received.
1710 * Returns: the unique ID of the bus or %NULL if @error is set.
1711 * Free with g_free().
1716 g_dbus_get_bus_id (GDBusConnection *connection,
1722 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1723 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1728 if (connection->kdbus_worker)
1730 result = _g_kdbus_GetBusId (connection->kdbus_worker, error);
1734 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1735 "org.freedesktop.DBus", "GetId",
1736 NULL, G_VARIANT_TYPE ("(s)"),
1737 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1742 g_variant_get (result, "(s)", &bus_id);
1743 g_variant_unref (result);
1752 LIST_ACTIVATABLE_NAMES,
1754 } GDBusListNameType;
1757 _g_dbus_get_list_internal (GDBusConnection *connection,
1759 GDBusListNameType list_name_type,
1771 if (list_name_type == LIST_QUEUED_OWNERS)
1773 if (connection->kdbus_worker)
1774 result = _g_kdbus_GetListQueuedOwners (connection->kdbus_worker, name, error);
1776 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1777 "org.freedesktop.DBus", "ListQueuedOwners",
1778 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(as)"),
1779 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1785 if (list_name_type == LIST_NAMES)
1786 method_name = "ListNames";
1788 method_name = "ListActivatableNames";
1790 if (connection->kdbus_worker)
1791 result = _g_kdbus_GetListNames (connection->kdbus_worker, list_name_type, error);
1793 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1794 "org.freedesktop.DBus", method_name,
1795 NULL, G_VARIANT_TYPE ("(as)"),
1796 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1801 g_variant_get (result, "(as)", &iter);
1802 n = g_variant_iter_n_children (iter);
1803 strv = g_new (gchar *, n + 1);
1806 while (g_variant_iter_loop (iter, "s", &str))
1808 strv[i] = g_strdup (str);
1813 g_variant_iter_free (iter);
1814 g_variant_unref (result);
1821 * g_dbus_get_list_names:
1822 * @connection: a #GDBusConnection
1823 * @error: return location for error or %NULL
1825 * Synchronously returns a list of all currently-owned names on the bus.
1827 * The calling thread is blocked until a reply is received.
1829 * Returns: a list of all currently-owned names on the bus or %NULL if
1830 * @error is set. Free with g_strfreev().
1835 g_dbus_get_list_names (GDBusConnection *connection,
1840 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1841 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1843 strv = _g_dbus_get_list_internal (connection, NULL, LIST_NAMES, error);
1849 * g_dbus_get_list_activatable_names:
1850 * @connection: a #GDBusConnection
1851 * @error: return location for error or %NULL
1853 * Synchronously returns a list of all names that can be activated on the bus.
1855 * The calling thread is blocked until a reply is received.
1857 * Returns: a list of all names that can be activated on the bus or %NULL if
1858 * @error is set. Free with g_strfreev().
1863 g_dbus_get_list_activatable_names (GDBusConnection *connection,
1868 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1869 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1871 strv = _g_dbus_get_list_internal (connection, NULL, LIST_ACTIVATABLE_NAMES, error);
1877 * g_dbus_get_list_queued_names:
1878 * @connection: a #GDBusConnection
1879 * @name: a unique or well-known bus name
1880 * @error: return location for error or %NULL
1882 * Synchronously returns the unique bus names of connections currently queued
1885 * If @name contains a value not compatible with the D-Bus syntax and naming
1886 * conventions for bus names, the operation returns %NULL and @error is set.
1888 * The calling thread is blocked until a reply is received.
1890 * Returns: the unique bus names of connections currently queued for the @name
1891 * or %NULL if @error is set. Free with g_strfreev().
1896 g_dbus_get_list_queued_owners (GDBusConnection *connection,
1902 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1903 g_return_val_if_fail (name == NULL || g_dbus_is_name (name), NULL);
1904 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1906 strv = _g_dbus_get_list_internal (connection, name, LIST_QUEUED_OWNERS, error);
1912 * g_dbus_get_name_owner:
1913 * @connection: a #GDBusConnection
1914 * @name: well-known bus name to get the owner of
1915 * @error: return location for error or %NULL
1917 * Synchronously returns the unique connection name of the primary owner of
1918 * the name given. If the requested name doesn't have an owner, an @error is
1921 * If @name contains a value not compatible with the D-Bus syntax and naming
1922 * conventions for bus names, the operation returns %NULL and @error is set.
1924 * The calling thread is blocked until a reply is received.
1926 * Returns: the unique connection name of the primary owner of the
1927 * name given. If the requested name doesn't have an owner, function
1928 * returns %NULL and @error is set. Free with g_free().
1933 g_dbus_get_name_owner (GDBusConnection *connection,
1940 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1941 g_return_val_if_fail (name == NULL || g_dbus_is_name (name), NULL);
1942 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1947 if (connection->kdbus_worker)
1948 result = _g_kdbus_GetNameOwner (connection->kdbus_worker, name, error);
1950 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1951 "org.freedesktop.DBus", "GetNameOwner",
1952 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(s)"),
1953 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1956 g_variant_get (result, "(s)", &name_owner);
1957 g_variant_unref (result);
1966 * g_dbus_get_connection_pid:
1967 * @connection: a #GDBusConnection
1968 * @name: a unique or well-known bus name of the connection to query
1969 * @error: return location for error or %NULL
1971 * Synchronously returns the Unix process ID of the process connected to the
1972 * bus. If unable to determine it, an @error is returned.
1974 * If @name contains a value not compatible with the D-Bus syntax and naming
1975 * conventions for bus names, the operation returns (guint32) -1 and @error
1978 * The calling thread is blocked until a reply is received.
1980 * Returns: the Unix process ID of the process connected to the bus or
1981 * (guint32) -1 if @error is set.
1986 g_dbus_get_connection_pid (GDBusConnection *connection,
1993 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), -1);
1994 g_return_val_if_fail (name == NULL || g_dbus_is_name (name), -1);
1995 g_return_val_if_fail (error == NULL || *error == NULL, -1);
2000 if (connection->kdbus_worker)
2001 result = _g_kdbus_GetConnectionUnixProcessID (connection->kdbus_worker, name, error);
2003 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
2004 "org.freedesktop.DBus", "GetConnectionUnixProcessID",
2005 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(u)"),
2006 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
2009 g_variant_get (result, "(u)", &pid);
2010 g_variant_unref (result);
2017 * g_dbus_get_connection_uid:
2018 * @connection: a #GDBusConnection
2019 * @name: a unique or well-known bus name of the connection to query
2020 * @error: return location for error or %NULL
2022 * Synchronously returns the Unix user ID of the process connected to the
2023 * bus. If unable to determine it, an @error is returned.
2025 * If @name contains a value not compatible with the D-Bus syntax and naming
2026 * conventions for bus names, the operation returns (guint32) -1 and @error
2029 * The calling thread is blocked until a reply is received.
2031 * Returns: the Unix user ID of the process connected to the bus or
2032 * (guint32) -1 if @error is set.
2037 g_dbus_get_connection_uid (GDBusConnection *connection,
2044 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), -1);
2045 g_return_val_if_fail (name == NULL || g_dbus_is_name (name), -1);
2046 g_return_val_if_fail (error == NULL || *error == NULL, -1);
2051 if (connection->kdbus_worker)
2052 result = _g_kdbus_GetConnectionUnixUser (connection->kdbus_worker, name, error);
2054 result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
2055 "org.freedesktop.DBus", "GetConnectionUnixUser",
2056 g_variant_new ("(s)", name), G_VARIANT_TYPE ("(u)"),
2057 G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
2060 g_variant_get (result, "(u)", &uid);
2061 g_variant_unref (result);
2067 /* ---------------------------------------------------------------------------------------------------- */
2070 * g_dbus_connection_get_last_serial:
2071 * @connection: a #GDBusConnection
2073 * Retrieves the last serial number assigned to a #GDBusMessage on
2074 * the current thread. This includes messages sent via both low-level
2075 * API such as g_dbus_connection_send_message() as well as
2076 * high-level API such as g_dbus_connection_emit_signal(),
2077 * g_dbus_connection_call() or g_dbus_proxy_call().
2079 * Returns: the last used serial or zero when no message has been sent
2080 * within the current thread
2085 g_dbus_connection_get_last_serial (GDBusConnection *connection)
2089 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2091 CONNECTION_LOCK (connection);
2092 ret = GPOINTER_TO_UINT (g_hash_table_lookup (connection->map_thread_to_last_serial,
2094 CONNECTION_UNLOCK (connection);
2099 /* ---------------------------------------------------------------------------------------------------- */
2101 /* Can be called by any thread, with the connection lock held */
2103 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
2104 GDBusMessage *message,
2105 GDBusSendMessageFlags flags,
2106 volatile guint32 *out_serial,
2111 guint32 serial_to_use;
2114 CONNECTION_ENSURE_LOCK (connection);
2116 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2117 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
2119 /* TODO: check all necessary headers are present */
2124 if (out_serial != NULL)
2127 /* If we're in initable_init(), don't check for being initialized, to avoid
2128 * chicken-and-egg problems. initable_init() is responsible for setting up
2129 * our prerequisites (mainly connection->worker), and only calling us
2130 * from its own thread (so no memory barrier is needed).
2132 if (!check_unclosed (connection,
2133 (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
2137 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
2138 g_dbus_message_set_serial (message, ++connection->last_serial);
2140 serial_to_use = g_dbus_message_get_serial (message);
2143 * serializes message to a blob
2145 if (connection->worker)
2147 blob = g_dbus_message_to_blob (message,
2149 connection->capabilities,
2157 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
2160 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
2163 g_assert_not_reached ();
2168 g_dbus_message_lock (message);
2171 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
2172 blob_size, serial_to_use, connection);
2173 g_printerr ("----\n");
2174 hexdump (blob, blob_size);
2175 g_printerr ("----\n");
2178 /* TODO: use connection->auth to encode the blob */
2180 if (out_serial != NULL)
2181 *out_serial = serial_to_use;
2183 /* store used serial for the current thread */
2184 /* TODO: watch the thread disposal and remove associated record
2186 * - see https://bugzilla.gnome.org/show_bug.cgi?id=676825#c7
2188 g_hash_table_replace (connection->map_thread_to_last_serial,
2190 GUINT_TO_POINTER (serial_to_use));
2194 if (connection->worker)
2195 _g_dbus_worker_send_message (connection->worker,
2200 ret = g_kdbus_worker_send_message (connection->kdbus_worker, message, error);
2202 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
2211 * g_dbus_connection_send_message:
2212 * @connection: a #GDBusConnection
2213 * @message: a #GDBusMessage
2214 * @flags: flags affecting how the message is sent
2215 * @out_serial: (out) (allow-none): return location for serial number assigned
2216 * to @message when sending it or %NULL
2217 * @error: Return location for error or %NULL
2219 * Asynchronously sends @message to the peer represented by @connection.
2221 * Unless @flags contain the
2222 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2223 * will be assigned by @connection and set on @message via
2224 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2225 * serial number used will be written to this location prior to
2226 * submitting the message to the underlying transport.
2228 * If @connection is closed then the operation will fail with
2229 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
2230 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2232 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2233 * for an example of how to use this low-level API to send and receive
2234 * UNIX file descriptors.
2236 * Note that @message must be unlocked, unless @flags contain the
2237 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2239 * Returns: %TRUE if the message was well-formed and queued for
2240 * transmission, %FALSE if @error is set
2245 g_dbus_connection_send_message (GDBusConnection *connection,
2246 GDBusMessage *message,
2247 GDBusSendMessageFlags flags,
2248 volatile guint32 *out_serial,
2253 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2254 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
2255 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
2256 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2258 CONNECTION_LOCK (connection);
2259 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
2260 CONNECTION_UNLOCK (connection);
2264 /* ---------------------------------------------------------------------------------------------------- */
2268 volatile gint ref_count;
2269 GDBusConnection *connection;
2271 GSimpleAsyncResult *simple;
2273 GMainContext *main_context;
2275 GCancellable *cancellable;
2277 gulong cancellable_handler_id;
2279 GSource *timeout_source;
2284 /* Can be called from any thread with or without lock held */
2285 static SendMessageData *
2286 send_message_data_ref (SendMessageData *data)
2288 g_atomic_int_inc (&data->ref_count);
2292 /* Can be called from any thread with or without lock held */
2294 send_message_data_unref (SendMessageData *data)
2296 if (g_atomic_int_dec_and_test (&data->ref_count))
2298 g_assert (data->timeout_source == NULL);
2299 g_assert (data->simple == NULL);
2300 g_assert (data->cancellable_handler_id == 0);
2301 g_object_unref (data->connection);
2302 if (data->cancellable != NULL)
2303 g_object_unref (data->cancellable);
2304 g_main_context_unref (data->main_context);
2309 /* ---------------------------------------------------------------------------------------------------- */
2311 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
2313 send_message_with_reply_deliver (SendMessageData *data, gboolean remove)
2315 CONNECTION_ENSURE_LOCK (data->connection);
2317 g_assert (!data->delivered);
2319 data->delivered = TRUE;
2321 g_simple_async_result_complete_in_idle (data->simple);
2322 g_object_unref (data->simple);
2323 data->simple = NULL;
2325 if (data->timeout_source != NULL)
2327 g_source_destroy (data->timeout_source);
2328 data->timeout_source = NULL;
2330 if (data->cancellable_handler_id > 0)
2332 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
2333 data->cancellable_handler_id = 0;
2338 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
2339 GUINT_TO_POINTER (data->serial)));
2342 send_message_data_unref (data);
2345 /* ---------------------------------------------------------------------------------------------------- */
2347 /* Can be called from any thread with lock held */
2349 send_message_data_deliver_reply_unlocked (SendMessageData *data,
2350 GDBusMessage *reply)
2352 if (data->delivered)
2355 g_simple_async_result_set_op_res_gpointer (data->simple,
2356 g_object_ref (reply),
2359 send_message_with_reply_deliver (data, TRUE);
2365 /* ---------------------------------------------------------------------------------------------------- */
2367 /* Called from a user thread, lock is not held */
2369 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
2371 SendMessageData *data = user_data;
2373 CONNECTION_LOCK (data->connection);
2374 if (data->delivered)
2377 g_simple_async_result_set_error (data->simple,
2379 G_IO_ERROR_CANCELLED,
2380 _("Operation was cancelled"));
2382 send_message_with_reply_deliver (data, TRUE);
2385 CONNECTION_UNLOCK (data->connection);
2389 /* Can be called from any thread with or without lock held */
2391 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
2394 SendMessageData *data = user_data;
2395 GSource *idle_source;
2397 /* postpone cancellation to idle handler since we may be called directly
2398 * via g_cancellable_connect() (e.g. holding lock)
2400 idle_source = g_idle_source_new ();
2401 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
2402 g_source_set_callback (idle_source,
2403 send_message_with_reply_cancelled_idle_cb,
2404 send_message_data_ref (data),
2405 (GDestroyNotify) send_message_data_unref);
2406 g_source_set_name (idle_source, "[gio] send_message_with_reply_cancelled_idle_cb");
2407 g_source_attach (idle_source, data->main_context);
2408 g_source_unref (idle_source);
2411 /* ---------------------------------------------------------------------------------------------------- */
2413 /* Called from a user thread, lock is not held */
2415 send_message_with_reply_timeout_cb (gpointer user_data)
2417 SendMessageData *data = user_data;
2419 CONNECTION_LOCK (data->connection);
2420 if (data->delivered)
2423 g_simple_async_result_set_error (data->simple,
2425 G_IO_ERROR_TIMED_OUT,
2426 _("Timeout was reached"));
2428 send_message_with_reply_deliver (data, TRUE);
2431 CONNECTION_UNLOCK (data->connection);
2436 /* ---------------------------------------------------------------------------------------------------- */
2438 /* Called from a user thread, connection's lock is held */
2440 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
2441 GDBusMessage *message,
2442 GDBusSendMessageFlags flags,
2444 volatile guint32 *out_serial,
2445 GCancellable *cancellable,
2446 GAsyncReadyCallback callback,
2449 GSimpleAsyncResult *simple;
2450 SendMessageData *data;
2452 volatile guint32 serial;
2456 if (out_serial == NULL)
2457 out_serial = &serial;
2459 if (timeout_msec == -1)
2460 timeout_msec = 25 * 1000;
2462 simple = g_simple_async_result_new (G_OBJECT (connection),
2465 g_dbus_connection_send_message_with_reply);
2466 g_simple_async_result_set_check_cancellable (simple, cancellable);
2468 if (g_cancellable_is_cancelled (cancellable))
2470 g_simple_async_result_set_error (simple,
2472 G_IO_ERROR_CANCELLED,
2473 _("Operation was cancelled"));
2474 g_simple_async_result_complete_in_idle (simple);
2475 g_object_unref (simple);
2480 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
2482 g_simple_async_result_take_error (simple, error);
2483 g_simple_async_result_complete_in_idle (simple);
2484 g_object_unref (simple);
2488 data = g_new0 (SendMessageData, 1);
2489 data->ref_count = 1;
2490 data->connection = g_object_ref (connection);
2491 data->simple = simple;
2492 data->serial = *out_serial;
2493 data->main_context = g_main_context_ref_thread_default ();
2495 if (cancellable != NULL)
2497 data->cancellable = g_object_ref (cancellable);
2498 data->cancellable_handler_id = g_cancellable_connect (cancellable,
2499 G_CALLBACK (send_message_with_reply_cancelled_cb),
2500 send_message_data_ref (data),
2501 (GDestroyNotify) send_message_data_unref);
2504 if (timeout_msec != G_MAXINT)
2506 data->timeout_source = g_timeout_source_new (timeout_msec);
2507 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
2508 g_source_set_callback (data->timeout_source,
2509 send_message_with_reply_timeout_cb,
2510 send_message_data_ref (data),
2511 (GDestroyNotify) send_message_data_unref);
2512 g_source_attach (data->timeout_source, data->main_context);
2513 g_source_unref (data->timeout_source);
2516 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
2517 GUINT_TO_POINTER (*out_serial),
2525 * g_dbus_connection_send_message_with_reply:
2526 * @connection: a #GDBusConnection
2527 * @message: a #GDBusMessage
2528 * @flags: flags affecting how the message is sent
2529 * @timeout_msec: the timeout in milliseconds, -1 to use the default
2530 * timeout or %G_MAXINT for no timeout
2531 * @out_serial: (out) (allow-none): return location for serial number assigned
2532 * to @message when sending it or %NULL
2533 * @cancellable: (allow-none): a #GCancellable or %NULL
2534 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request
2535 * is satisfied or %NULL if you don't care about the result
2536 * @user_data: The data to pass to @callback
2538 * Asynchronously sends @message to the peer represented by @connection.
2540 * Unless @flags contain the
2541 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2542 * will be assigned by @connection and set on @message via
2543 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2544 * serial number used will be written to this location prior to
2545 * submitting the message to the underlying transport.
2547 * If @connection is closed then the operation will fail with
2548 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2549 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2550 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2552 * This is an asynchronous method. When the operation is finished, @callback
2553 * will be invoked in the
2554 * [thread-default main context][g-main-context-push-thread-default]
2555 * of the thread you are calling this method from. You can then call
2556 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
2557 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
2559 * Note that @message must be unlocked, unless @flags contain the
2560 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2562 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2563 * for an example of how to use this low-level API to send and receive
2564 * UNIX file descriptors.
2569 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
2570 GDBusMessage *message,
2571 GDBusSendMessageFlags flags,
2573 volatile guint32 *out_serial,
2574 GCancellable *cancellable,
2575 GAsyncReadyCallback callback,
2578 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2579 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2580 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2581 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2583 CONNECTION_LOCK (connection);
2584 g_dbus_connection_send_message_with_reply_unlocked (connection,
2592 CONNECTION_UNLOCK (connection);
2596 * g_dbus_connection_send_message_with_reply_finish:
2597 * @connection: a #GDBusConnection
2598 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
2599 * g_dbus_connection_send_message_with_reply()
2600 * @error: teturn location for error or %NULL
2602 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2604 * Note that @error is only set if a local in-process error
2605 * occurred. That is to say that the returned #GDBusMessage object may
2606 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2607 * g_dbus_message_to_gerror() to transcode this to a #GError.
2609 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2610 * for an example of how to use this low-level API to send and receive
2611 * UNIX file descriptors.
2613 * Returns: (transfer full): a locked #GDBusMessage or %NULL if @error is set
2618 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2622 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2623 GDBusMessage *reply;
2625 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2626 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2630 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
2632 if (g_simple_async_result_propagate_error (simple, error))
2635 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
2641 /* ---------------------------------------------------------------------------------------------------- */
2646 GMainContext *context;
2648 } SendMessageSyncData;
2650 /* Called from a user thread, lock is not held */
2652 send_message_with_reply_sync_cb (GDBusConnection *connection,
2656 SendMessageSyncData *data = user_data;
2657 data->res = g_object_ref (res);
2658 g_main_loop_quit (data->loop);
2662 * g_dbus_connection_send_message_with_reply_sync:
2663 * @connection: a #GDBusConnection
2664 * @message: a #GDBusMessage
2665 * @flags: flags affecting how the message is sent.
2666 * @timeout_msec: the timeout in milliseconds, -1 to use the default
2667 * timeout or %G_MAXINT for no timeout
2668 * @out_serial: (out) (allow-none): return location for serial number
2669 * assigned to @message when sending it or %NULL
2670 * @cancellable: (allow-none): a #GCancellable or %NULL
2671 * @error: return location for error or %NULL
2673 * Synchronously sends @message to the peer represented by @connection
2674 * and blocks the calling thread until a reply is received or the
2675 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2676 * for the asynchronous version of this method.
2678 * Unless @flags contain the
2679 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2680 * will be assigned by @connection and set on @message via
2681 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2682 * serial number used will be written to this location prior to
2683 * submitting the message to the underlying transport.
2685 * If @connection is closed then the operation will fail with
2686 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2687 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2688 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2690 * Note that @error is only set if a local in-process error
2691 * occurred. That is to say that the returned #GDBusMessage object may
2692 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2693 * g_dbus_message_to_gerror() to transcode this to a #GError.
2695 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2696 * for an example of how to use this low-level API to send and receive
2697 * UNIX file descriptors.
2699 * Note that @message must be unlocked, unless @flags contain the
2700 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2702 * Returns: (transfer full): a locked #GDBusMessage that is the reply
2703 * to @message or %NULL if @error is set
2708 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2709 GDBusMessage *message,
2710 GDBusSendMessageFlags flags,
2712 volatile guint32 *out_serial,
2713 GCancellable *cancellable,
2716 SendMessageSyncData *data;
2717 GDBusMessage *reply;
2719 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2720 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2721 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2722 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2723 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2725 data = g_new0 (SendMessageSyncData, 1);
2727 if (connection->kdbus_worker)
2728 data->context = g_main_context_ref_thread_default ();
2730 data->context = g_main_context_new ();
2732 data->loop = g_main_loop_new (data->context, FALSE);
2734 g_main_context_push_thread_default (data->context);
2736 g_dbus_connection_send_message_with_reply (connection,
2742 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2744 g_main_loop_run (data->loop);
2745 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2749 g_main_context_pop_thread_default (data->context);
2751 g_main_context_unref (data->context);
2752 g_main_loop_unref (data->loop);
2753 g_object_unref (data->res);
2759 /* ---------------------------------------------------------------------------------------------------- */
2763 GDBusMessageFilterFunction func;
2770 GDBusMessageFilterFunction filter_function;
2772 GDestroyNotify user_data_free_func;
2775 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2777 on_worker_message_received (GDBusMessage *message,
2780 GDBusConnection *connection;
2781 FilterCallback *filters;
2786 G_LOCK (message_bus_lock);
2787 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2790 G_UNLOCK (message_bus_lock);
2793 connection = G_DBUS_CONNECTION (user_data);
2794 g_object_ref (connection);
2795 G_UNLOCK (message_bus_lock);
2797 //g_debug ("in on_worker_message_received");
2799 g_object_ref (message);
2800 g_dbus_message_lock (message);
2802 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2804 /* First collect the set of callback functions */
2805 CONNECTION_LOCK (connection);
2806 num_filters = connection->filters->len;
2807 filters = g_new0 (FilterCallback, num_filters);
2808 for (n = 0; n < num_filters; n++)
2810 FilterData *data = connection->filters->pdata[n];
2811 filters[n].func = data->filter_function;
2812 filters[n].user_data = data->user_data;
2814 CONNECTION_UNLOCK (connection);
2816 /* then call the filters in order (without holding the lock) */
2817 for (n = 0; n < num_filters; n++)
2819 message = filters[n].func (connection,
2822 filters[n].user_data);
2823 if (message == NULL)
2825 g_dbus_message_lock (message);
2828 /* Standard dispatch unless the filter ate the message - no need to
2829 * do anything if the message was altered
2831 if (message != NULL)
2833 GDBusMessageType message_type;
2835 message_type = g_dbus_message_get_message_type (message);
2836 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2838 guint32 reply_serial;
2839 SendMessageData *send_message_data;
2841 reply_serial = g_dbus_message_get_reply_serial (message);
2842 CONNECTION_LOCK (connection);
2843 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2844 GUINT_TO_POINTER (reply_serial));
2845 if (send_message_data != NULL)
2847 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2848 send_message_data_deliver_reply_unlocked (send_message_data, message);
2852 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2854 CONNECTION_UNLOCK (connection);
2856 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2858 CONNECTION_LOCK (connection);
2859 distribute_signals (connection, message);
2860 CONNECTION_UNLOCK (connection);
2862 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2864 CONNECTION_LOCK (connection);
2865 distribute_method_call (connection, message);
2866 CONNECTION_UNLOCK (connection);
2870 if (message != NULL)
2871 g_object_unref (message);
2872 g_object_unref (connection);
2876 /* Called in GDBusWorker's thread, lock is not held */
2877 static GDBusMessage *
2878 on_worker_message_about_to_be_sent (GDBusMessage *message,
2881 GDBusConnection *connection;
2882 FilterCallback *filters;
2887 G_LOCK (message_bus_lock);
2888 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2891 G_UNLOCK (message_bus_lock);
2894 connection = G_DBUS_CONNECTION (user_data);
2895 g_object_ref (connection);
2896 G_UNLOCK (message_bus_lock);
2898 //g_debug ("in on_worker_message_about_to_be_sent");
2900 /* First collect the set of callback functions */
2901 CONNECTION_LOCK (connection);
2902 num_filters = connection->filters->len;
2903 filters = g_new0 (FilterCallback, num_filters);
2904 for (n = 0; n < num_filters; n++)
2906 FilterData *data = connection->filters->pdata[n];
2907 filters[n].func = data->filter_function;
2908 filters[n].user_data = data->user_data;
2910 CONNECTION_UNLOCK (connection);
2912 /* then call the filters in order (without holding the lock) */
2913 for (n = 0; n < num_filters; n++)
2915 g_dbus_message_lock (message);
2916 message = filters[n].func (connection,
2919 filters[n].user_data);
2920 if (message == NULL)
2924 g_object_unref (connection);
2930 /* called with connection lock held, in GDBusWorker thread */
2932 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2934 SendMessageData *data = value;
2936 if (data->delivered)
2939 g_simple_async_result_set_error (data->simple,
2942 _("The connection is closed"));
2944 /* Ask send_message_with_reply_deliver not to remove the element from the
2945 * hash table - we're in the middle of a foreach; that would be unsafe.
2946 * Instead, return TRUE from this function so that it gets removed safely.
2948 send_message_with_reply_deliver (data, FALSE);
2952 /* Called in GDBusWorker's thread - we must not block - without lock held */
2954 on_worker_closed (gboolean remote_peer_vanished,
2958 GDBusConnection *connection;
2960 guint old_atomic_flags;
2962 G_LOCK (message_bus_lock);
2963 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2966 G_UNLOCK (message_bus_lock);
2969 connection = G_DBUS_CONNECTION (user_data);
2970 g_object_ref (connection);
2971 G_UNLOCK (message_bus_lock);
2973 //g_debug ("in on_worker_closed: %s", error->message);
2975 CONNECTION_LOCK (connection);
2976 /* Even though this is atomic, we do it inside the lock to avoid breaking
2977 * assumptions in remove_match_rule(). We'd need the lock in a moment
2978 * anyway, so, no loss.
2980 old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
2982 if (!(old_atomic_flags & FLAG_CLOSED))
2984 g_hash_table_foreach_remove (connection->map_method_serial_to_send_message_data, cancel_method_on_close, NULL);
2985 schedule_closed_unlocked (connection, remote_peer_vanished, error);
2987 CONNECTION_UNLOCK (connection);
2989 g_object_unref (connection);
2992 /* ---------------------------------------------------------------------------------------------------- */
2994 /* Determines the biggest set of capabilities we can support on this
2997 * Called with the init_lock held.
2999 static GDBusCapabilityFlags
3000 get_offered_capabilities_max (GDBusConnection *connection)
3002 GDBusCapabilityFlags ret;
3003 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
3005 //if (G_IS_UNIX_CONNECTION (connection->stream))
3006 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
3011 /* Called in a user thread, lock is not held */
3013 initable_init (GInitable *initable,
3014 GCancellable *cancellable,
3017 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
3018 gboolean initially_frozen;
3021 /* This method needs to be idempotent to work with the singleton
3022 * pattern. See the docs for g_initable_init(). We implement this by
3025 * Unfortunately we can't use the main lock since the on_worker_*()
3026 * callbacks above needs the lock during initialization (for message
3027 * bus connections we do a synchronous Hello() call on the bus).
3029 g_mutex_lock (&connection->init_lock);
3033 /* Make this a no-op if we're already initialized (successfully or
3036 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
3038 ret = (connection->initialization_error == NULL);
3042 /* Because of init_lock, we can't get here twice in different threads */
3043 g_assert (connection->initialization_error == NULL);
3045 /* The user can pass multiple (but mutally exclusive) construct
3048 * - stream (of type GIOStream)
3049 * - address (of type gchar*)
3051 * At the end of the day we end up with a non-NULL GIOStream
3052 * object in connection->stream.
3054 if (connection->address != NULL)
3058 g_assert (connection->stream == NULL);
3060 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
3061 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
3063 g_set_error_literal (&connection->initialization_error,
3065 G_IO_ERROR_INVALID_ARGUMENT,
3066 _("Unsupported flags encountered when constructing a client-side connection"));
3070 ret = g_dbus_address_get_stream_internal (connection->address, TRUE,
3071 NULL, /* TODO: out_guid */
3072 cancellable, &connection->initialization_error);
3076 if (G_IS_IO_STREAM (ret))
3077 connection->stream = G_IO_STREAM (ret);
3078 else if (G_IS_KDBUS_WORKER (ret))
3079 connection->kdbus_worker = G_KDBUS_WORKER (ret);
3081 g_assert_not_reached ();
3083 else if (connection->stream != NULL)
3089 g_assert_not_reached ();
3092 /* [KDBUS] Skip authentication process for kdbus transport */
3093 if (connection->kdbus_worker)
3095 connection->capabilities |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
3099 /* Authenticate the connection */
3100 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
3102 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
3103 g_assert (connection->guid != NULL);
3104 connection->auth = _g_dbus_auth_new (connection->stream);
3105 if (!_g_dbus_auth_run_server (connection->auth,
3106 connection->authentication_observer,
3108 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
3109 get_offered_capabilities_max (connection),
3110 &connection->capabilities,
3111 &connection->credentials,
3113 &connection->initialization_error))
3116 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
3118 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
3119 g_assert (connection->guid == NULL);
3120 connection->auth = _g_dbus_auth_new (connection->stream);
3121 connection->guid = _g_dbus_auth_run_client (connection->auth,
3122 connection->authentication_observer,
3123 get_offered_capabilities_max (connection),
3124 &connection->capabilities,
3126 &connection->initialization_error);
3127 if (connection->guid == NULL)
3131 if (connection->authentication_observer != NULL)
3133 g_object_unref (connection->authentication_observer);
3134 connection->authentication_observer = NULL;
3139 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
3141 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
3144 /* We want all IO operations to be non-blocking since they happen in
3145 * the worker thread which is shared by _all_ connections.
3147 if (G_IS_SOCKET_CONNECTION (connection->stream))
3149 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
3153 G_LOCK (message_bus_lock);
3154 if (alive_connections == NULL)
3155 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
3156 g_hash_table_insert (alive_connections, connection, connection);
3157 G_UNLOCK (message_bus_lock);
3159 initially_frozen = (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) != 0;
3161 if (connection->kdbus_worker)
3162 g_kdbus_worker_associate (connection->kdbus_worker,
3163 connection->capabilities,
3164 on_worker_message_received,
3165 on_worker_message_about_to_be_sent,
3169 connection->worker = _g_dbus_worker_new (connection->stream,
3170 connection->capabilities,
3172 on_worker_message_received,
3173 on_worker_message_about_to_be_sent,
3177 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
3178 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3180 GVariant *hello_result;
3182 /* we could lift this restriction by adding code in gdbusprivate.c */
3183 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
3185 g_set_error_literal (&connection->initialization_error,
3188 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
3192 if (connection->kdbus_worker)
3194 hello_result = _g_kdbus_Hello (connection->kdbus_worker, &connection->initialization_error);
3198 hello_result = g_dbus_connection_call_sync (connection,
3199 "org.freedesktop.DBus", /* name */
3200 "/org/freedesktop/DBus", /* path */
3201 "org.freedesktop.DBus", /* interface */
3203 NULL, /* parameters */
3204 G_VARIANT_TYPE ("(s)"),
3205 CALL_FLAGS_INITIALIZING,
3207 NULL, /* TODO: cancellable */
3208 &connection->initialization_error);
3211 if (hello_result == NULL)
3214 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
3215 g_variant_unref (hello_result);
3216 //g_debug ("unique name is '%s'", connection->bus_unique_name);
3219 if (connection->kdbus_worker && !initially_frozen)
3220 g_kdbus_worker_unfreeze (connection->kdbus_worker);
3226 g_assert (connection->initialization_error != NULL);
3227 g_propagate_error (error, g_error_copy (connection->initialization_error));
3230 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
3231 g_mutex_unlock (&connection->init_lock);
3237 initable_iface_init (GInitableIface *initable_iface)
3239 initable_iface->init = initable_init;
3242 /* ---------------------------------------------------------------------------------------------------- */
3245 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
3250 /* ---------------------------------------------------------------------------------------------------- */
3253 * g_dbus_connection_new:
3254 * @stream: a #GIOStream
3255 * @guid: (allow-none): the GUID to use if a authenticating as a server or %NULL
3256 * @flags: flags describing how to make the connection
3257 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3258 * @cancellable: (allow-none): a #GCancellable or %NULL
3259 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
3260 * @user_data: the data to pass to @callback
3262 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
3263 * with the end represented by @stream.
3265 * If @stream is a #GSocketConnection, then the corresponding #GSocket
3266 * will be put into non-blocking mode.
3268 * The D-Bus connection will interact with @stream from a worker thread.
3269 * As a result, the caller should not interact with @stream after this
3270 * method has been called, except by calling g_object_unref() on it.
3272 * If @observer is not %NULL it may be used to control the
3273 * authentication process.
3275 * When the operation is finished, @callback will be invoked. You can
3276 * then call g_dbus_connection_new_finish() to get the result of the
3279 * This is a asynchronous failable constructor. See
3280 * g_dbus_connection_new_sync() for the synchronous
3286 g_dbus_connection_new (GIOStream *stream,
3288 GDBusConnectionFlags flags,
3289 GDBusAuthObserver *observer,
3290 GCancellable *cancellable,
3291 GAsyncReadyCallback callback,
3294 g_return_if_fail (G_IS_IO_STREAM (stream));
3295 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
3303 "authentication-observer", observer,
3308 * g_dbus_connection_new_finish:
3309 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback
3310 * passed to g_dbus_connection_new().
3311 * @error: return location for error or %NULL
3313 * Finishes an operation started with g_dbus_connection_new().
3315 * Returns: a #GDBusConnection or %NULL if @error is set. Free
3316 * with g_object_unref().
3321 g_dbus_connection_new_finish (GAsyncResult *res,
3325 GObject *source_object;
3327 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
3328 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3330 source_object = g_async_result_get_source_object (res);
3331 g_assert (source_object != NULL);
3332 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
3335 g_object_unref (source_object);
3337 return G_DBUS_CONNECTION (object);
3343 * g_dbus_connection_new_sync:
3344 * @stream: a #GIOStream
3345 * @guid: (allow-none): the GUID to use if a authenticating as a server or %NULL
3346 * @flags: flags describing how to make the connection
3347 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3348 * @cancellable: (allow-none): a #GCancellable or %NULL
3349 * @error: return location for error or %NULL
3351 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
3352 * with the end represented by @stream.
3354 * If @stream is a #GSocketConnection, then the corresponding #GSocket
3355 * will be put into non-blocking mode.
3357 * The D-Bus connection will interact with @stream from a worker thread.
3358 * As a result, the caller should not interact with @stream after this
3359 * method has been called, except by calling g_object_unref() on it.
3361 * If @observer is not %NULL it may be used to control the
3362 * authentication process.
3364 * This is a synchronous failable constructor. See
3365 * g_dbus_connection_new() for the asynchronous version.
3367 * Returns: a #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
3372 g_dbus_connection_new_sync (GIOStream *stream,
3374 GDBusConnectionFlags flags,
3375 GDBusAuthObserver *observer,
3376 GCancellable *cancellable,
3379 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
3380 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3381 return g_initable_new (G_TYPE_DBUS_CONNECTION,
3387 "authentication-observer", observer,
3391 /* ---------------------------------------------------------------------------------------------------- */
3394 * g_dbus_connection_new_for_address:
3395 * @address: a D-Bus address
3396 * @flags: flags describing how to make the connection
3397 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3398 * @cancellable: (allow-none): a #GCancellable or %NULL
3399 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
3400 * @user_data: the data to pass to @callback
3402 * Asynchronously connects and sets up a D-Bus client connection for
3403 * exchanging D-Bus messages with an endpoint specified by @address
3404 * which must be in the D-Bus address format.
3406 * This constructor can only be used to initiate client-side
3407 * connections - use g_dbus_connection_new() if you need to act as the
3408 * server. In particular, @flags cannot contain the
3409 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
3410 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
3412 * When the operation is finished, @callback will be invoked. You can
3413 * then call g_dbus_connection_new_finish() to get the result of the
3416 * If @observer is not %NULL it may be used to control the
3417 * authentication process.
3419 * This is a asynchronous failable constructor. See
3420 * g_dbus_connection_new_for_address_sync() for the synchronous
3426 g_dbus_connection_new_for_address (const gchar *address,
3427 GDBusConnectionFlags flags,
3428 GDBusAuthObserver *observer,
3429 GCancellable *cancellable,
3430 GAsyncReadyCallback callback,
3433 g_return_if_fail (address != NULL);
3434 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
3441 "authentication-observer", observer,
3446 * g_dbus_connection_new_for_address_finish:
3447 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
3448 * to g_dbus_connection_new()
3449 * @error: return location for error or %NULL
3451 * Finishes an operation started with g_dbus_connection_new_for_address().
3453 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
3459 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
3463 GObject *source_object;
3465 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
3466 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3468 source_object = g_async_result_get_source_object (res);
3469 g_assert (source_object != NULL);
3470 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
3473 g_object_unref (source_object);
3475 return G_DBUS_CONNECTION (object);
3481 * g_dbus_connection_new_for_address_sync:
3482 * @address: a D-Bus address
3483 * @flags: flags describing how to make the connection
3484 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3485 * @cancellable: (allow-none): a #GCancellable or %NULL
3486 * @error: return location for error or %NULL
3488 * Synchronously connects and sets up a D-Bus client connection for
3489 * exchanging D-Bus messages with an endpoint specified by @address
3490 * which must be in the D-Bus address format.
3492 * This constructor can only be used to initiate client-side
3493 * connections - use g_dbus_connection_new_sync() if you need to act
3494 * as the server. In particular, @flags cannot contain the
3495 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
3496 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
3498 * This is a synchronous failable constructor. See
3499 * g_dbus_connection_new_for_address() for the asynchronous version.
3501 * If @observer is not %NULL it may be used to control the
3502 * authentication process.
3504 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
3510 g_dbus_connection_new_for_address_sync (const gchar *address,
3511 GDBusConnectionFlags flags,
3512 GDBusAuthObserver *observer,
3513 GCancellable *cancellable,
3516 g_return_val_if_fail (address != NULL, NULL);
3517 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3518 return g_initable_new (G_TYPE_DBUS_CONNECTION,
3523 "authentication-observer", observer,
3527 /* ---------------------------------------------------------------------------------------------------- */
3530 * g_dbus_connection_set_exit_on_close:
3531 * @connection: a #GDBusConnection
3532 * @exit_on_close: whether the process should be terminated
3533 * when @connection is closed by the remote peer
3535 * Sets whether the process should be terminated when @connection is
3536 * closed by the remote peer. See #GDBusConnection:exit-on-close for
3539 * Note that this function should be used with care. Most modern UNIX
3540 * desktops tie the notion of a user session the session bus, and expect
3541 * all of a users applications to quit when their bus connection goes away.
3542 * If you are setting @exit_on_close to %FALSE for the shared session
3543 * bus connection, you should make sure that your application exits
3544 * when the user session ends.
3549 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
3550 gboolean exit_on_close)
3552 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3555 g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
3557 g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
3562 * g_dbus_connection_get_exit_on_close:
3563 * @connection: a #GDBusConnection
3565 * Gets whether the process is terminated when @connection is
3566 * closed by the remote peer. See
3567 * #GDBusConnection:exit-on-close for more details.
3569 * Returns: whether the process is terminated when @connection is
3570 * closed by the remote peer
3575 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
3577 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3579 if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
3586 * g_dbus_connection_get_guid:
3587 * @connection: a #GDBusConnection
3589 * The GUID of the peer performing the role of server when
3590 * authenticating. See #GDBusConnection:guid for more details.
3592 * Returns: The GUID. Do not free this string, it is owned by
3598 g_dbus_connection_get_guid (GDBusConnection *connection)
3600 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3601 return connection->guid;
3605 * g_dbus_connection_get_unique_name:
3606 * @connection: a #GDBusConnection
3608 * Gets the unique name of @connection as assigned by the message
3609 * bus. This can also be used to figure out if @connection is a
3610 * message bus connection.
3612 * Returns: the unique name or %NULL if @connection is not a message
3613 * bus connection. Do not free this string, it is owned by
3619 g_dbus_connection_get_unique_name (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->bus_unique_name;
3631 * g_dbus_connection_get_peer_credentials:
3632 * @connection: a #GDBusConnection
3634 * Gets the credentials of the authenticated peer. This will always
3635 * return %NULL unless @connection acted as a server
3636 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3637 * when set up and the client passed credentials as part of the
3638 * authentication process.
3640 * In a message bus setup, the message bus is always the server and
3641 * each application is a client. So this method will always return
3642 * %NULL for message bus clients.
3644 * Returns: (transfer none): a #GCredentials or %NULL if not available.
3645 * Do not free this object, it is owned by @connection.
3650 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3652 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3654 /* do not use g_return_val_if_fail(), we want the memory barrier */
3655 if (!check_initialized (connection))
3658 return connection->credentials;
3661 /* ---------------------------------------------------------------------------------------------------- */
3663 static guint _global_filter_id = 1;
3666 * g_dbus_connection_add_filter:
3667 * @connection: a #GDBusConnection
3668 * @filter_function: a filter function
3669 * @user_data: user data to pass to @filter_function
3670 * @user_data_free_func: function to free @user_data with when filter
3671 * is removed or %NULL
3673 * Adds a message filter. Filters are handlers that are run on all
3674 * incoming and outgoing messages, prior to standard dispatch. Filters
3675 * are run in the order that they were added. The same handler can be
3676 * added as a filter more than once, in which case it will be run more
3677 * than once. Filters added during a filter callback won't be run on
3678 * the message being processed. Filter functions are allowed to modify
3679 * and even drop messages.
3681 * Note that filters are run in a dedicated message handling thread so
3682 * they can't block and, generally, can't do anything but signal a
3683 * worker thread. Also note that filters are rarely needed - use API
3684 * such as g_dbus_connection_send_message_with_reply(),
3685 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3687 * If a filter consumes an incoming message the message is not
3688 * dispatched anywhere else - not even the standard dispatch machinery
3689 * (that API such as g_dbus_connection_signal_subscribe() and
3690 * g_dbus_connection_send_message_with_reply() relies on) will see the
3691 * message. Similary, if a filter consumes an outgoing message, the
3692 * message will not be sent to the other peer.
3694 * Returns: a filter identifier that can be used with
3695 * g_dbus_connection_remove_filter()
3700 g_dbus_connection_add_filter (GDBusConnection *connection,
3701 GDBusMessageFilterFunction filter_function,
3703 GDestroyNotify user_data_free_func)
3707 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3708 g_return_val_if_fail (filter_function != NULL, 0);
3709 g_return_val_if_fail (check_initialized (connection), 0);
3711 CONNECTION_LOCK (connection);
3712 data = g_new0 (FilterData, 1);
3713 data->id = _global_filter_id++; /* TODO: overflow etc. */
3714 data->filter_function = filter_function;
3715 data->user_data = user_data;
3716 data->user_data_free_func = user_data_free_func;
3717 g_ptr_array_add (connection->filters, data);
3718 CONNECTION_UNLOCK (connection);
3723 /* only called from finalize(), removes all filters */
3725 purge_all_filters (GDBusConnection *connection)
3728 for (n = 0; n < connection->filters->len; n++)
3730 FilterData *data = connection->filters->pdata[n];
3731 if (data->user_data_free_func != NULL)
3732 data->user_data_free_func (data->user_data);
3738 * g_dbus_connection_remove_filter:
3739 * @connection: a #GDBusConnection
3740 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3747 g_dbus_connection_remove_filter (GDBusConnection *connection,
3751 FilterData *to_destroy;
3753 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3754 g_return_if_fail (check_initialized (connection));
3756 CONNECTION_LOCK (connection);
3758 for (n = 0; n < connection->filters->len; n++)
3760 FilterData *data = connection->filters->pdata[n];
3761 if (data->id == filter_id)
3763 g_ptr_array_remove_index (connection->filters, n);
3768 CONNECTION_UNLOCK (connection);
3770 /* do free without holding lock */
3771 if (to_destroy != NULL)
3773 if (to_destroy->user_data_free_func != NULL)
3774 to_destroy->user_data_free_func (to_destroy->user_data);
3775 g_free (to_destroy);
3779 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3783 /* ---------------------------------------------------------------------------------------------------- */
3789 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3790 gchar *interface_name;
3794 GDBusSignalFlags flags;
3795 GArray *subscribers;
3800 GDBusSignalCallback callback;
3802 GDestroyNotify user_data_free_func;
3804 GMainContext *context;
3808 signal_data_free (SignalData *signal_data)
3810 g_free (signal_data->rule);
3811 g_free (signal_data->sender);
3812 g_free (signal_data->sender_unique_name);
3813 g_free (signal_data->interface_name);
3814 g_free (signal_data->member);
3815 g_free (signal_data->object_path);
3816 g_free (signal_data->arg0);
3817 g_array_free (signal_data->subscribers, TRUE);
3818 g_free (signal_data);
3822 args_to_rule (const gchar *sender,
3823 const gchar *interface_name,
3824 const gchar *member,
3825 const gchar *object_path,
3827 GDBusSignalFlags flags)
3831 rule = g_string_new ("type='signal'");
3832 if (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE)
3833 g_string_prepend_c (rule, '-');
3835 g_string_append_printf (rule, ",sender='%s'", sender);
3836 if (interface_name != NULL)
3837 g_string_append_printf (rule, ",interface='%s'", interface_name);
3839 g_string_append_printf (rule, ",member='%s'", member);
3840 if (object_path != NULL)
3841 g_string_append_printf (rule, ",path='%s'", object_path);
3845 if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3846 g_string_append_printf (rule, ",arg0path='%s'", arg0);
3847 else if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3848 g_string_append_printf (rule, ",arg0namespace='%s'", arg0);
3850 g_string_append_printf (rule, ",arg0='%s'", arg0);
3853 return g_string_free (rule, FALSE);
3856 static guint _global_subscriber_id = 1;
3857 static guint _global_registration_id = 1;
3858 static guint _global_subtree_registration_id = 1;
3860 /* ---------------------------------------------------------------------------------------------------- */
3862 /* Called in a user thread, lock is held */
3864 add_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));
3879 if (!g_dbus_connection_send_message_unlocked (connection,
3881 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3885 g_critical ("Error while sending AddMatch() message: %s", error->message);
3886 g_error_free (error);
3888 g_object_unref (message);
3891 /* ---------------------------------------------------------------------------------------------------- */
3893 /* Called in a user thread, lock is held */
3895 remove_match_rule (GDBusConnection *connection,
3896 const gchar *match_rule)
3899 GDBusMessage *message;
3901 if (match_rule[0] == '-')
3904 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3905 "/org/freedesktop/DBus", /* path */
3906 "org.freedesktop.DBus", /* interface */
3908 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3911 if (!g_dbus_connection_send_message_unlocked (connection,
3913 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3917 /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
3918 * critical; but we're holding the lock, and our caller checked whether
3919 * we were already closed, so we can't get that error.
3921 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3922 g_error_free (error);
3924 g_object_unref (message);
3927 /* ---------------------------------------------------------------------------------------------------- */
3930 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3932 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3933 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3934 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3935 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3936 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3939 /* ---------------------------------------------------------------------------------------------------- */
3942 * g_dbus_connection_signal_subscribe:
3943 * @connection: a #GDBusConnection
3944 * @sender: (allow-none): sender name to match on (unique or well-known name)
3945 * or %NULL to listen from all senders
3946 * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3947 * match on all interfaces
3948 * @member: (allow-none): D-Bus signal name to match on or %NULL to match on
3950 * @object_path: (allow-none): object path to match on or %NULL to match on
3952 * @arg0: (allow-none): contents of first string argument to match on or %NULL
3953 * to match on all kinds of arguments
3954 * @flags: flags describing how to subscribe to the signal (currently unused)
3955 * @callback: callback to invoke when there is a signal matching the requested data
3956 * @user_data: user data to pass to @callback
3957 * @user_data_free_func: (allow-none): function to free @user_data with when
3958 * subscription is removed or %NULL
3960 * Subscribes to signals on @connection and invokes @callback with a whenever
3961 * the signal is received. Note that @callback will be invoked in the
3962 * [thread-default main context][g-main-context-push-thread-default]
3963 * of the thread you are calling this method from.
3965 * If @connection is not a message bus connection, @sender must be
3968 * If @sender is a well-known name note that @callback is invoked with
3969 * the unique name for the owner of @sender, not the well-known name
3970 * as one would expect. This is because the message bus rewrites the
3971 * name. As such, to avoid certain race conditions, users should be
3972 * tracking the name owner of the well-known name and use that when
3973 * processing the received signal.
3975 * If one of %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE or
3976 * %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH are given, @arg0 is
3977 * interpreted as part of a namespace or path. The first argument
3978 * of a signal is matched against that part as specified by D-Bus.
3980 * Returns: a subscription identifier that can be used with g_dbus_connection_signal_unsubscribe()
3985 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3986 const gchar *sender,
3987 const gchar *interface_name,
3988 const gchar *member,
3989 const gchar *object_path,
3991 GDBusSignalFlags flags,
3992 GDBusSignalCallback callback,
3994 GDestroyNotify user_data_free_func)
3997 SignalData *signal_data;
3998 SignalSubscriber subscriber;
3999 GPtrArray *signal_data_array;
4000 const gchar *sender_unique_name;
4002 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
4003 * an OOM condition. We might want to change that but that would involve making
4004 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
4005 * handle that. And there's really no sensible way of handling this short of retrying
4006 * to add the match rule... and then there's the little thing that, hey, maybe there's
4007 * a reason the bus in an OOM condition.
4009 * Doable, but not really sure it's worth it...
4012 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4013 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
4014 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
4015 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
4016 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
4017 g_return_val_if_fail (callback != NULL, 0);
4018 g_return_val_if_fail (check_initialized (connection), 0);
4019 g_return_val_if_fail (!((flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH) && (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)), 0);
4020 g_return_val_if_fail (!(arg0 == NULL && (flags & (G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH | G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE))), 0);
4022 CONNECTION_LOCK (connection);
4024 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
4025 * with a '-' character to prefix the rule (which will otherwise be
4028 * This allows us to hash the rule and do our lifecycle tracking in
4029 * the usual way, but the '-' prevents the match rule from ever
4030 * actually being send to the bus (either for add or remove).
4032 rule = args_to_rule (sender, interface_name, member, object_path, arg0, flags);
4034 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
4035 sender_unique_name = sender;
4037 sender_unique_name = "";
4039 subscriber.callback = callback;
4040 subscriber.user_data = user_data;
4041 subscriber.user_data_free_func = user_data_free_func;
4042 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
4043 subscriber.context = g_main_context_ref_thread_default ();
4045 /* see if we've already have this rule */
4046 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
4047 if (signal_data != NULL)
4049 g_array_append_val (signal_data->subscribers, subscriber);
4054 signal_data = g_new0 (SignalData, 1);
4055 signal_data->rule = rule;
4056 signal_data->sender = g_strdup (sender);
4057 signal_data->sender_unique_name = g_strdup (sender_unique_name);
4058 signal_data->interface_name = g_strdup (interface_name);
4059 signal_data->member = g_strdup (member);
4060 signal_data->object_path = g_strdup (object_path);
4061 signal_data->arg0 = g_strdup (arg0);
4062 signal_data->flags = flags;
4063 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
4064 g_array_append_val (signal_data->subscribers, subscriber);
4066 g_hash_table_insert (connection->map_rule_to_signal_data,
4070 /* Add the match rule to the bus...
4072 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
4073 * always send such messages to us.
4075 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
4077 if (connection->kdbus_worker)
4079 if (g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
4080 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
4081 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
4082 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
4083 g_strcmp0 (signal_data->member, "NameAcquired") == 0 ||
4084 g_strcmp0 (signal_data->member, "NameOwnerChanged") == 0))
4086 if (g_strcmp0 (signal_data->member, "NameAcquired") == 0)
4087 _g_kdbus_subscribe_name_acquired (connection->kdbus_worker, arg0, (guint64) subscriber.id);
4088 else if (g_strcmp0 (signal_data->member, "NameLost") == 0)
4089 _g_kdbus_subscribe_name_lost (connection->kdbus_worker, arg0, (guint64) subscriber.id);
4090 else if (g_strcmp0 (signal_data->member, "NameOwnerChanged") == 0)
4091 _g_kdbus_subscribe_name_owner_changed (connection->kdbus_worker, arg0, (guint64) subscriber.id);
4094 _g_kdbus_AddMatch (connection->kdbus_worker, signal_data->rule, subscriber.id);
4098 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
4099 add_match_rule (connection, signal_data->rule);
4103 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
4104 signal_data->sender_unique_name);
4105 if (signal_data_array == NULL)
4107 signal_data_array = g_ptr_array_new ();
4108 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
4109 g_strdup (signal_data->sender_unique_name),
4112 g_ptr_array_add (signal_data_array, signal_data);
4115 g_hash_table_insert (connection->map_id_to_signal_data,
4116 GUINT_TO_POINTER (subscriber.id),
4119 CONNECTION_UNLOCK (connection);
4121 return subscriber.id;
4124 /* ---------------------------------------------------------------------------------------------------- */
4126 /* called in any thread */
4127 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
4129 unsubscribe_id_internal (GDBusConnection *connection,
4130 guint subscription_id,
4131 GArray *out_removed_subscribers)
4133 SignalData *signal_data;
4134 GPtrArray *signal_data_array;
4137 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
4138 GUINT_TO_POINTER (subscription_id));
4139 if (signal_data == NULL)
4141 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
4145 for (n = 0; n < signal_data->subscribers->len; n++)
4147 SignalSubscriber *subscriber;
4149 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
4150 if (subscriber->id != subscription_id)
4153 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
4154 GUINT_TO_POINTER (subscription_id)));
4155 g_array_append_val (out_removed_subscribers, *subscriber);
4156 g_array_remove_index (signal_data->subscribers, n);
4158 if (signal_data->subscribers->len == 0)
4160 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
4162 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
4163 signal_data->sender_unique_name);
4164 g_warn_if_fail (signal_data_array != NULL);
4165 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
4167 if (signal_data_array->len == 0)
4169 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
4170 signal_data->sender_unique_name));
4173 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
4174 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
4175 !g_dbus_connection_is_closed (connection) &&
4176 !connection->finalizing)
4178 /* The check for g_dbus_connection_is_closed() means that
4179 * sending the RemoveMatch message can't fail with
4180 * G_IO_ERROR_CLOSED, because we're holding the lock,
4181 * so on_worker_closed() can't happen between the check we just
4182 * did, and releasing the lock later.
4184 if (connection->kdbus_worker)
4185 _g_kdbus_RemoveMatch (connection->kdbus_worker, subscription_id);
4187 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
4188 remove_match_rule (connection, signal_data->rule);
4191 signal_data_free (signal_data);
4197 g_assert_not_reached ();
4204 * g_dbus_connection_signal_unsubscribe:
4205 * @connection: a #GDBusConnection
4206 * @subscription_id: a subscription id obtained from
4207 * g_dbus_connection_signal_subscribe()
4209 * Unsubscribes from signals.
4214 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
4215 guint subscription_id)
4217 GArray *subscribers;
4220 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4221 g_return_if_fail (check_initialized (connection));
4223 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
4225 CONNECTION_LOCK (connection);
4226 unsubscribe_id_internal (connection,
4229 CONNECTION_UNLOCK (connection);
4232 g_assert (subscribers->len == 0 || subscribers->len == 1);
4234 /* call GDestroyNotify without lock held */
4235 for (n = 0; n < subscribers->len; n++)
4237 SignalSubscriber *subscriber;
4238 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
4239 call_destroy_notify (subscriber->context,
4240 subscriber->user_data_free_func,
4241 subscriber->user_data);
4242 g_main_context_unref (subscriber->context);
4245 g_array_free (subscribers, TRUE);
4248 /* ---------------------------------------------------------------------------------------------------- */
4252 guint subscription_id;
4253 GDBusSignalCallback callback;
4255 GDBusMessage *message;
4256 GDBusConnection *connection;
4257 const gchar *sender;
4259 const gchar *interface;
4260 const gchar *member;
4263 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
4267 emit_signal_instance_in_idle_cb (gpointer data)
4269 SignalInstance *signal_instance = data;
4270 GVariant *parameters;
4271 gboolean has_subscription;
4273 parameters = g_dbus_message_get_body (signal_instance->message);
4274 if (parameters == NULL)
4276 parameters = g_variant_new ("()");
4277 g_variant_ref_sink (parameters);
4281 g_variant_ref (parameters);
4285 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
4286 signal_instance->subscription_id,
4287 signal_instance->sender,
4288 signal_instance->path,
4289 signal_instance->interface,
4290 signal_instance->member,
4291 g_variant_print (parameters, TRUE));
4294 /* Careful here, don't do the callback if we no longer has the subscription */
4295 CONNECTION_LOCK (signal_instance->connection);
4296 has_subscription = FALSE;
4297 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
4298 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
4299 has_subscription = TRUE;
4300 CONNECTION_UNLOCK (signal_instance->connection);
4302 if (has_subscription)
4303 signal_instance->callback (signal_instance->connection,
4304 signal_instance->sender,
4305 signal_instance->path,
4306 signal_instance->interface,
4307 signal_instance->member,
4309 signal_instance->user_data);
4311 g_variant_unref (parameters);
4317 signal_instance_free (SignalInstance *signal_instance)
4319 g_object_unref (signal_instance->message);
4320 g_object_unref (signal_instance->connection);
4321 g_free (signal_instance);
4325 namespace_rule_matches (const gchar *namespace,
4331 len_namespace = strlen (namespace);
4332 len_name = strlen (name);
4334 if (len_name < len_namespace)
4337 if (memcmp (namespace, name, len_namespace) != 0)
4340 return len_namespace == len_name || name[len_namespace] == '.';
4344 path_rule_matches (const gchar *path_a,
4345 const gchar *path_b)
4349 len_a = strlen (path_a);
4350 len_b = strlen (path_b);
4352 if (len_a < len_b && path_a[len_a - 1] != '/')
4355 if (len_b < len_a && path_b[len_b - 1] != '/')
4358 return memcmp (path_a, path_b, MIN (len_a, len_b)) == 0;
4361 /* called in GDBusWorker thread WITH lock held */
4363 schedule_callbacks (GDBusConnection *connection,
4364 GPtrArray *signal_data_array,
4365 GDBusMessage *message,
4366 const gchar *sender)
4369 const gchar *interface;
4370 const gchar *member;
4379 interface = g_dbus_message_get_interface (message);
4380 member = g_dbus_message_get_member (message);
4381 path = g_dbus_message_get_path (message);
4382 arg0 = g_dbus_message_get_arg0 (message);
4385 g_print ("In schedule_callbacks:\n"
4387 " interface = '%s'\n"
4398 /* TODO: if this is slow, then we can change signal_data_array into
4399 * map_object_path_to_signal_data_array or something.
4401 for (n = 0; n < signal_data_array->len; n++)
4403 SignalData *signal_data = signal_data_array->pdata[n];
4405 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
4408 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
4411 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
4414 if (signal_data->arg0 != NULL)
4419 if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
4421 if (!namespace_rule_matches (signal_data->arg0, arg0))
4424 else if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
4426 if (!path_rule_matches (signal_data->arg0, arg0))
4429 else if (!g_str_equal (signal_data->arg0, arg0))
4433 for (m = 0; m < signal_data->subscribers->len; m++)
4435 SignalSubscriber *subscriber;
4436 GSource *idle_source;
4437 SignalInstance *signal_instance;
4439 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
4441 signal_instance = g_new0 (SignalInstance, 1);
4442 signal_instance->subscription_id = subscriber->id;
4443 signal_instance->callback = subscriber->callback;
4444 signal_instance->user_data = subscriber->user_data;
4445 signal_instance->message = g_object_ref (message);
4446 signal_instance->connection = g_object_ref (connection);
4447 signal_instance->sender = sender;
4448 signal_instance->path = path;
4449 signal_instance->interface = interface;
4450 signal_instance->member = member;
4452 idle_source = g_idle_source_new ();
4453 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4454 g_source_set_callback (idle_source,
4455 emit_signal_instance_in_idle_cb,
4457 (GDestroyNotify) signal_instance_free);
4458 g_source_set_name (idle_source, "[gio] emit_signal_instance_in_idle_cb");
4459 g_source_attach (idle_source, subscriber->context);
4460 g_source_unref (idle_source);
4465 /* called in GDBusWorker thread with lock held */
4467 distribute_signals (GDBusConnection *connection,
4468 GDBusMessage *message)
4470 GPtrArray *signal_data_array;
4471 const gchar *sender;
4473 sender = g_dbus_message_get_sender (message);
4475 if (G_UNLIKELY (_g_dbus_debug_signal ()))
4477 _g_dbus_debug_print_lock ();
4478 g_print ("========================================================================\n"
4479 "GDBus-debug:Signal:\n"
4480 " <<<< RECEIVED SIGNAL %s.%s\n"
4482 " sent by name %s\n",
4483 g_dbus_message_get_interface (message),
4484 g_dbus_message_get_member (message),
4485 g_dbus_message_get_path (message),
4486 sender != NULL ? sender : "(none)");
4487 _g_dbus_debug_print_unlock ();
4490 /* collect subscribers that match on sender */
4493 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
4494 if (signal_data_array != NULL)
4495 schedule_callbacks (connection, signal_data_array, message, sender);
4498 /* collect subscribers not matching on sender */
4499 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
4500 if (signal_data_array != NULL)
4501 schedule_callbacks (connection, signal_data_array, message, sender);
4504 /* ---------------------------------------------------------------------------------------------------- */
4506 /* only called from finalize(), removes all subscriptions */
4508 purge_all_signal_subscriptions (GDBusConnection *connection)
4510 GHashTableIter iter;
4513 GArray *subscribers;
4516 ids = g_array_new (FALSE, FALSE, sizeof (guint));
4517 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
4518 while (g_hash_table_iter_next (&iter, &key, NULL))
4520 guint subscription_id = GPOINTER_TO_UINT (key);
4521 g_array_append_val (ids, subscription_id);
4524 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
4525 for (n = 0; n < ids->len; n++)
4527 guint subscription_id = g_array_index (ids, guint, n);
4528 unsubscribe_id_internal (connection,
4532 g_array_free (ids, TRUE);
4534 /* call GDestroyNotify without lock held */
4535 for (n = 0; n < subscribers->len; n++)
4537 SignalSubscriber *subscriber;
4538 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
4539 call_destroy_notify (subscriber->context,
4540 subscriber->user_data_free_func,
4541 subscriber->user_data);
4542 g_main_context_unref (subscriber->context);
4545 g_array_free (subscribers, TRUE);
4548 /* ---------------------------------------------------------------------------------------------------- */
4550 static GDBusInterfaceVTable *
4551 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
4553 /* Don't waste memory by copying padding - remember to update this
4554 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
4556 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4560 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
4565 /* ---------------------------------------------------------------------------------------------------- */
4567 static GDBusSubtreeVTable *
4568 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
4570 /* Don't waste memory by copying padding - remember to update this
4571 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
4573 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4577 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
4582 /* ---------------------------------------------------------------------------------------------------- */
4584 struct ExportedObject
4587 GDBusConnection *connection;
4589 /* maps gchar* -> ExportedInterface* */
4590 GHashTable *map_if_name_to_ei;
4593 /* only called with lock held */
4595 exported_object_free (ExportedObject *eo)
4597 g_free (eo->object_path);
4598 g_hash_table_unref (eo->map_if_name_to_ei);
4607 gchar *interface_name;
4608 GDBusInterfaceVTable *vtable;
4609 GDBusInterfaceInfo *interface_info;
4611 GMainContext *context;
4613 GDestroyNotify user_data_free_func;
4614 } ExportedInterface;
4616 /* called with lock held */
4618 exported_interface_free (ExportedInterface *ei)
4620 g_dbus_interface_info_cache_release (ei->interface_info);
4621 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
4623 call_destroy_notify (ei->context,
4624 ei->user_data_free_func,
4627 g_main_context_unref (ei->context);
4629 g_free (ei->interface_name);
4630 _g_dbus_interface_vtable_free (ei->vtable);
4634 /* ---------------------------------------------------------------------------------------------------- */
4636 /* Convenience function to check if @registration_id (if not zero) or
4637 * @subtree_registration_id (if not zero) has been unregistered. If
4638 * so, returns %TRUE.
4640 * May be called by any thread. Caller must *not* hold lock.
4643 has_object_been_unregistered (GDBusConnection *connection,
4644 guint registration_id,
4645 guint subtree_registration_id)
4649 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4653 CONNECTION_LOCK (connection);
4654 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
4655 GUINT_TO_POINTER (registration_id)) == NULL)
4659 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
4660 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
4664 CONNECTION_UNLOCK (connection);
4669 /* ---------------------------------------------------------------------------------------------------- */
4673 GDBusConnection *connection;
4674 GDBusMessage *message;
4676 const gchar *property_name;
4677 const GDBusInterfaceVTable *vtable;
4678 GDBusInterfaceInfo *interface_info;
4679 const GDBusPropertyInfo *property_info;
4680 guint registration_id;
4681 guint subtree_registration_id;
4685 property_data_free (PropertyData *data)
4687 g_object_unref (data->connection);
4688 g_object_unref (data->message);
4692 /* called in thread where object was registered - no locks held */
4694 invoke_get_property_in_idle_cb (gpointer _data)
4696 PropertyData *data = _data;
4699 GDBusMessage *reply;
4701 if (has_object_been_unregistered (data->connection,
4702 data->registration_id,
4703 data->subtree_registration_id))
4705 reply = g_dbus_message_new_method_error (data->message,
4706 "org.freedesktop.DBus.Error.UnknownMethod",
4707 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4708 g_dbus_message_get_path (data->message));
4709 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4710 g_object_unref (reply);
4715 value = data->vtable->get_property (data->connection,
4716 g_dbus_message_get_sender (data->message),
4717 g_dbus_message_get_path (data->message),
4718 data->interface_info->name,
4719 data->property_name,
4726 g_assert_no_error (error);
4728 g_variant_take_ref (value);
4729 reply = g_dbus_message_new_method_reply (data->message);
4730 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4731 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4732 g_variant_unref (value);
4733 g_object_unref (reply);
4737 gchar *dbus_error_name;
4738 g_assert (error != NULL);
4739 dbus_error_name = g_dbus_error_encode_gerror (error);
4740 reply = g_dbus_message_new_method_error_literal (data->message,
4743 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4744 g_free (dbus_error_name);
4745 g_error_free (error);
4746 g_object_unref (reply);
4753 /* called in thread where object was registered - no locks held */
4755 invoke_set_property_in_idle_cb (gpointer _data)
4757 PropertyData *data = _data;
4759 GDBusMessage *reply;
4765 g_variant_get (g_dbus_message_get_body (data->message),
4771 if (!data->vtable->set_property (data->connection,
4772 g_dbus_message_get_sender (data->message),
4773 g_dbus_message_get_path (data->message),
4774 data->interface_info->name,
4775 data->property_name,
4780 gchar *dbus_error_name;
4781 g_assert (error != NULL);
4782 dbus_error_name = g_dbus_error_encode_gerror (error);
4783 reply = g_dbus_message_new_method_error_literal (data->message,
4786 g_free (dbus_error_name);
4787 g_error_free (error);
4791 reply = g_dbus_message_new_method_reply (data->message);
4794 g_assert (reply != NULL);
4795 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4796 g_object_unref (reply);
4797 g_variant_unref (value);
4802 /* called in any thread with connection's lock held */
4804 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4805 GDBusMessage *message,
4806 guint registration_id,
4807 guint subtree_registration_id,
4809 GDBusInterfaceInfo *interface_info,
4810 const GDBusInterfaceVTable *vtable,
4811 GMainContext *main_context,
4815 const char *interface_name;
4816 const char *property_name;
4817 const GDBusPropertyInfo *property_info;
4818 GSource *idle_source;
4819 PropertyData *property_data;
4820 GDBusMessage *reply;
4825 g_variant_get (g_dbus_message_get_body (message),
4830 g_variant_get (g_dbus_message_get_body (message),
4839 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4841 property_info = NULL;
4843 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4844 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4845 if (property_info == NULL)
4847 reply = g_dbus_message_new_method_error (message,
4848 "org.freedesktop.DBus.Error.InvalidArgs",
4849 _("No such property '%s'"),
4851 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4852 g_object_unref (reply);
4857 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4859 reply = g_dbus_message_new_method_error (message,
4860 "org.freedesktop.DBus.Error.InvalidArgs",
4861 _("Property '%s' is not readable"),
4863 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4864 g_object_unref (reply);
4868 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4870 reply = g_dbus_message_new_method_error (message,
4871 "org.freedesktop.DBus.Error.InvalidArgs",
4872 _("Property '%s' is not writable"),
4874 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4875 g_object_unref (reply);
4884 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4885 * of the given value is wrong
4887 g_variant_get_child (g_dbus_message_get_body (message), 2, "v", &value);
4888 if (g_strcmp0 (g_variant_get_type_string (value), property_info->signature) != 0)
4890 reply = g_dbus_message_new_method_error (message,
4891 "org.freedesktop.DBus.Error.InvalidArgs",
4892 _("Error setting property '%s': Expected type '%s' but got '%s'"),
4893 property_name, property_info->signature,
4894 g_variant_get_type_string (value));
4895 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4896 g_variant_unref (value);
4897 g_object_unref (reply);
4902 g_variant_unref (value);
4905 /* If the vtable pointer for get_property() resp. set_property() is
4906 * NULL then dispatch the call via the method_call() handler.
4910 if (vtable->get_property == NULL)
4912 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4913 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4914 vtable, main_context, user_data);
4921 if (vtable->set_property == NULL)
4923 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4924 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4925 vtable, main_context, user_data);
4931 /* ok, got the property info - call user code in an idle handler */
4932 property_data = g_new0 (PropertyData, 1);
4933 property_data->connection = g_object_ref (connection);
4934 property_data->message = g_object_ref (message);
4935 property_data->user_data = user_data;
4936 property_data->property_name = property_name;
4937 property_data->vtable = vtable;
4938 property_data->interface_info = interface_info;
4939 property_data->property_info = property_info;
4940 property_data->registration_id = registration_id;
4941 property_data->subtree_registration_id = subtree_registration_id;
4943 idle_source = g_idle_source_new ();
4944 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4945 g_source_set_callback (idle_source,
4946 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4948 (GDestroyNotify) property_data_free);
4950 g_source_set_name (idle_source, "[gio] invoke_get_property_in_idle_cb");
4952 g_source_set_name (idle_source, "[gio] invoke_set_property_in_idle_cb");
4953 g_source_attach (idle_source, main_context);
4954 g_source_unref (idle_source);
4962 /* called in GDBusWorker thread with connection's lock held */
4964 handle_getset_property (GDBusConnection *connection,
4966 GDBusMessage *message,
4969 ExportedInterface *ei;
4971 const char *interface_name;
4972 const char *property_name;
4977 g_variant_get (g_dbus_message_get_body (message),
4982 g_variant_get (g_dbus_message_get_body (message),
4988 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4989 * no such interface registered
4991 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4994 GDBusMessage *reply;
4995 reply = g_dbus_message_new_method_error (message,
4996 "org.freedesktop.DBus.Error.InvalidArgs",
4997 _("No such interface '%s'"),
4999 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5000 g_object_unref (reply);
5005 handled = validate_and_maybe_schedule_property_getset (eo->connection,
5018 /* ---------------------------------------------------------------------------------------------------- */
5022 GDBusConnection *connection;
5023 GDBusMessage *message;
5025 const GDBusInterfaceVTable *vtable;
5026 GDBusInterfaceInfo *interface_info;
5027 guint registration_id;
5028 guint subtree_registration_id;
5029 } PropertyGetAllData;
5032 property_get_all_data_free (PropertyData *data)
5034 g_object_unref (data->connection);
5035 g_object_unref (data->message);
5039 /* called in thread where object was registered - no locks held */
5041 invoke_get_all_properties_in_idle_cb (gpointer _data)
5043 PropertyGetAllData *data = _data;
5044 GVariantBuilder builder;
5045 GDBusMessage *reply;
5048 if (has_object_been_unregistered (data->connection,
5049 data->registration_id,
5050 data->subtree_registration_id))
5052 reply = g_dbus_message_new_method_error (data->message,
5053 "org.freedesktop.DBus.Error.UnknownMethod",
5054 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
5055 g_dbus_message_get_path (data->message));
5056 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5057 g_object_unref (reply);
5061 /* TODO: Right now we never fail this call - we just omit values if
5062 * a get_property() call is failing.
5064 * We could fail the whole call if just a single get_property() call
5065 * returns an error. We need clarification in the D-Bus spec about this.
5067 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
5068 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
5069 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
5071 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
5074 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
5077 value = data->vtable->get_property (data->connection,
5078 g_dbus_message_get_sender (data->message),
5079 g_dbus_message_get_path (data->message),
5080 data->interface_info->name,
5081 property_info->name,
5088 g_variant_take_ref (value);
5089 g_variant_builder_add (&builder,
5091 property_info->name,
5093 g_variant_unref (value);
5095 g_variant_builder_close (&builder);
5097 reply = g_dbus_message_new_method_reply (data->message);
5098 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
5099 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5100 g_object_unref (reply);
5107 interface_has_readable_properties (GDBusInterfaceInfo *interface_info)
5111 if (!interface_info->properties)
5114 for (i = 0; interface_info->properties[i]; i++)
5115 if (interface_info->properties[i]->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE)
5121 /* called in any thread with connection's lock held */
5123 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
5124 GDBusMessage *message,
5125 guint registration_id,
5126 guint subtree_registration_id,
5127 GDBusInterfaceInfo *interface_info,
5128 const GDBusInterfaceVTable *vtable,
5129 GMainContext *main_context,
5133 GSource *idle_source;
5134 PropertyGetAllData *property_get_all_data;
5141 /* If the vtable pointer for get_property() is NULL but we have a
5142 * non-zero number of readable properties, then dispatch the call via
5143 * the method_call() handler.
5145 if (vtable->get_property == NULL && interface_has_readable_properties (interface_info))
5147 schedule_method_call (connection, message, registration_id, subtree_registration_id,
5148 interface_info, NULL, NULL, g_dbus_message_get_body (message),
5149 vtable, main_context, user_data);
5154 /* ok, got the property info - call user in an idle handler */
5155 property_get_all_data = g_new0 (PropertyGetAllData, 1);
5156 property_get_all_data->connection = g_object_ref (connection);
5157 property_get_all_data->message = g_object_ref (message);
5158 property_get_all_data->user_data = user_data;
5159 property_get_all_data->vtable = vtable;
5160 property_get_all_data->interface_info = interface_info;
5161 property_get_all_data->registration_id = registration_id;
5162 property_get_all_data->subtree_registration_id = subtree_registration_id;
5164 idle_source = g_idle_source_new ();
5165 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
5166 g_source_set_callback (idle_source,
5167 invoke_get_all_properties_in_idle_cb,
5168 property_get_all_data,
5169 (GDestroyNotify) property_get_all_data_free);
5170 g_source_set_name (idle_source, "[gio] invoke_get_all_properties_in_idle_cb");
5171 g_source_attach (idle_source, main_context);
5172 g_source_unref (idle_source);
5180 /* called in GDBusWorker thread with connection's lock held */
5182 handle_get_all_properties (GDBusConnection *connection,
5184 GDBusMessage *message)
5186 ExportedInterface *ei;
5188 const char *interface_name;
5192 g_variant_get (g_dbus_message_get_body (message),
5196 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
5197 * no such interface registered
5199 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5202 GDBusMessage *reply;
5203 reply = g_dbus_message_new_method_error (message,
5204 "org.freedesktop.DBus.Error.InvalidArgs",
5205 _("No such interface"),
5207 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5208 g_object_unref (reply);
5213 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
5225 /* ---------------------------------------------------------------------------------------------------- */
5227 static const gchar introspect_header[] =
5228 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
5229 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
5230 "<!-- GDBus " PACKAGE_VERSION " -->\n"
5233 static const gchar introspect_tail[] =
5236 static const gchar introspect_properties_interface[] =
5237 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
5238 " <method name=\"Get\">\n"
5239 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5240 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
5241 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
5243 " <method name=\"GetAll\">\n"
5244 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5245 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
5247 " <method name=\"Set\">\n"
5248 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5249 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
5250 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
5252 " <signal name=\"PropertiesChanged\">\n"
5253 " <arg type=\"s\" name=\"interface_name\"/>\n"
5254 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
5255 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
5259 static const gchar introspect_introspectable_interface[] =
5260 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
5261 " <method name=\"Introspect\">\n"
5262 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
5265 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
5266 " <method name=\"Ping\"/>\n"
5267 " <method name=\"GetMachineId\">\n"
5268 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
5273 introspect_append_header (GString *s)
5275 g_string_append (s, introspect_header);
5279 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
5281 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
5287 begin = object_path + path_len;
5288 end = strchr (begin, '/');
5290 s = g_strndup (begin, end - begin);
5292 s = g_strdup (begin);
5294 if (g_hash_table_lookup (set, s) == NULL)
5295 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
5301 /* TODO: we want a nicer public interface for this */
5302 /* called in any thread with connection's lock held */
5304 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
5309 GHashTableIter hash_iter;
5310 const gchar *object_path;
5316 CONNECTION_ENSURE_LOCK (connection);
5318 path_len = strlen (path);
5322 set = g_hash_table_new (g_str_hash, g_str_equal);
5324 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
5325 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
5326 maybe_add_path (path, path_len, object_path, set);
5328 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
5329 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
5330 maybe_add_path (path, path_len, object_path, set);
5332 p = g_ptr_array_new ();
5333 keys = g_hash_table_get_keys (set);
5334 for (l = keys; l != NULL; l = l->next)
5335 g_ptr_array_add (p, l->data);
5336 g_hash_table_unref (set);
5339 g_ptr_array_add (p, NULL);
5340 ret = (gchar **) g_ptr_array_free (p, FALSE);
5344 /* called in any thread with connection's lock not held */
5346 g_dbus_connection_list_registered (GDBusConnection *connection,
5350 CONNECTION_LOCK (connection);
5351 ret = g_dbus_connection_list_registered_unlocked (connection, path);
5352 CONNECTION_UNLOCK (connection);
5356 /* called in GDBusWorker thread with connection's lock held */
5358 handle_introspect (GDBusConnection *connection,
5360 GDBusMessage *message)
5364 GDBusMessage *reply;
5365 GHashTableIter hash_iter;
5366 ExportedInterface *ei;
5369 /* first the header with the standard interfaces */
5370 s = g_string_sized_new (sizeof (introspect_header) +
5371 sizeof (introspect_properties_interface) +
5372 sizeof (introspect_introspectable_interface) +
5373 sizeof (introspect_tail));
5374 introspect_append_header (s);
5375 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
5376 "org.freedesktop.DBus.Properties"))
5377 g_string_append (s, introspect_properties_interface);
5379 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
5380 "org.freedesktop.DBus.Introspectable"))
5381 g_string_append (s, introspect_introspectable_interface);
5383 /* then include the registered interfaces */
5384 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
5385 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
5386 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
5388 /* finally include nodes registered below us */
5389 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
5390 for (n = 0; registered != NULL && registered[n] != NULL; n++)
5391 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
5392 g_strfreev (registered);
5393 g_string_append (s, introspect_tail);
5395 reply = g_dbus_message_new_method_reply (message);
5396 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5397 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5398 g_object_unref (reply);
5399 g_string_free (s, TRUE);
5404 /* called in thread where object was registered - no locks held */
5406 call_in_idle_cb (gpointer user_data)
5408 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
5409 GDBusInterfaceVTable *vtable;
5410 guint registration_id;
5411 guint subtree_registration_id;
5413 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
5414 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
5416 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
5418 subtree_registration_id))
5420 GDBusMessage *reply;
5421 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
5422 "org.freedesktop.DBus.Error.UnknownMethod",
5423 _("No such interface '%s' on object at path %s"),
5424 g_dbus_method_invocation_get_interface_name (invocation),
5425 g_dbus_method_invocation_get_object_path (invocation));
5426 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5427 g_object_unref (reply);
5431 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
5432 g_assert (vtable != NULL && vtable->method_call != NULL);
5434 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
5435 g_dbus_method_invocation_get_sender (invocation),
5436 g_dbus_method_invocation_get_object_path (invocation),
5437 g_dbus_method_invocation_get_interface_name (invocation),
5438 g_dbus_method_invocation_get_method_name (invocation),
5439 g_dbus_method_invocation_get_parameters (invocation),
5440 g_object_ref (invocation),
5441 g_dbus_method_invocation_get_user_data (invocation));
5447 /* called in GDBusWorker thread with connection's lock held */
5449 schedule_method_call (GDBusConnection *connection,
5450 GDBusMessage *message,
5451 guint registration_id,
5452 guint subtree_registration_id,
5453 const GDBusInterfaceInfo *interface_info,
5454 const GDBusMethodInfo *method_info,
5455 const GDBusPropertyInfo *property_info,
5456 GVariant *parameters,
5457 const GDBusInterfaceVTable *vtable,
5458 GMainContext *main_context,
5461 GDBusMethodInvocation *invocation;
5462 GSource *idle_source;
5464 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
5465 g_dbus_message_get_path (message),
5466 g_dbus_message_get_interface (message),
5467 g_dbus_message_get_member (message),
5475 /* TODO: would be nicer with a real MethodData like we already
5476 * have PropertyData and PropertyGetAllData... */
5477 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
5478 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
5479 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
5481 idle_source = g_idle_source_new ();
5482 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
5483 g_source_set_callback (idle_source,
5487 g_source_set_name (idle_source, "[gio] call_in_idle_cb");
5488 g_source_attach (idle_source, main_context);
5489 g_source_unref (idle_source);
5492 /* called in GDBusWorker thread with connection's lock held */
5494 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
5495 GDBusMessage *message,
5496 guint registration_id,
5497 guint subtree_registration_id,
5498 GDBusInterfaceInfo *interface_info,
5499 const GDBusInterfaceVTable *vtable,
5500 GMainContext *main_context,
5503 GDBusMethodInfo *method_info;
5504 GDBusMessage *reply;
5505 GVariant *parameters;
5507 GVariantType *in_type;
5511 /* TODO: the cost of this is O(n) - it might be worth caching the result */
5512 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
5514 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
5515 * error to the caller
5517 if (method_info == NULL)
5519 reply = g_dbus_message_new_method_error (message,
5520 "org.freedesktop.DBus.Error.UnknownMethod",
5521 _("No such method '%s'"),
5522 g_dbus_message_get_member (message));
5523 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5524 g_object_unref (reply);
5529 parameters = g_dbus_message_get_body (message);
5530 if (parameters == NULL)
5532 parameters = g_variant_new ("()");
5533 g_variant_ref_sink (parameters);
5537 g_variant_ref (parameters);
5540 /* Check that the incoming args are of the right type - if they are not, return
5541 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
5543 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
5544 if (!g_variant_is_of_type (parameters, in_type))
5548 type_string = g_variant_type_dup_string (in_type);
5550 reply = g_dbus_message_new_method_error (message,
5551 "org.freedesktop.DBus.Error.InvalidArgs",
5552 _("Type of message, '%s', does not match expected type '%s'"),
5553 g_variant_get_type_string (parameters),
5555 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5556 g_variant_type_free (in_type);
5557 g_variant_unref (parameters);
5558 g_object_unref (reply);
5559 g_free (type_string);
5563 g_variant_type_free (in_type);
5565 /* schedule the call in idle */
5566 schedule_method_call (connection, message, registration_id, subtree_registration_id,
5567 interface_info, method_info, NULL, parameters,
5568 vtable, main_context, user_data);
5569 g_variant_unref (parameters);
5576 /* ---------------------------------------------------------------------------------------------------- */
5578 /* called in GDBusWorker thread with connection's lock held */
5580 obj_message_func (GDBusConnection *connection,
5582 GDBusMessage *message)
5584 const gchar *interface_name;
5585 const gchar *member;
5586 const gchar *signature;
5591 interface_name = g_dbus_message_get_interface (message);
5592 member = g_dbus_message_get_member (message);
5593 signature = g_dbus_message_get_signature (message);
5595 /* see if we have an interface for handling this call */
5596 if (interface_name != NULL)
5598 ExportedInterface *ei;
5599 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5602 /* we do - invoke the handler in idle in the right thread */
5604 /* handle no vtable or handler being present */
5605 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
5608 handled = validate_and_maybe_schedule_method_call (connection,
5620 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5621 g_strcmp0 (member, "Introspect") == 0 &&
5622 g_strcmp0 (signature, "") == 0)
5624 handled = handle_introspect (connection, eo, message);
5627 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5628 g_strcmp0 (member, "Get") == 0 &&
5629 g_strcmp0 (signature, "ss") == 0)
5631 handled = handle_getset_property (connection, eo, message, TRUE);
5634 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5635 g_strcmp0 (member, "Set") == 0 &&
5636 g_strcmp0 (signature, "ssv") == 0)
5638 handled = handle_getset_property (connection, eo, message, FALSE);
5641 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5642 g_strcmp0 (member, "GetAll") == 0 &&
5643 g_strcmp0 (signature, "s") == 0)
5645 handled = handle_get_all_properties (connection, eo, message);
5654 * g_dbus_connection_register_object:
5655 * @connection: a #GDBusConnection
5656 * @object_path: the object path to register at
5657 * @interface_info: introspection data for the interface
5658 * @vtable: (allow-none): a #GDBusInterfaceVTable to call into or %NULL
5659 * @user_data: (allow-none): data to pass to functions in @vtable
5660 * @user_data_free_func: function to call when the object path is unregistered
5661 * @error: return location for error or %NULL
5663 * Registers callbacks for exported objects at @object_path with the
5664 * D-Bus interface that is described in @interface_info.
5666 * Calls to functions in @vtable (and @user_data_free_func) will happen
5668 * [thread-default main context][g-main-context-push-thread-default]
5669 * of the thread you are calling this method from.
5671 * Note that all #GVariant values passed to functions in @vtable will match
5672 * the signature given in @interface_info - if a remote caller passes
5673 * incorrect values, the `org.freedesktop.DBus.Error.InvalidArgs`
5674 * is returned to the remote caller.
5676 * Additionally, if the remote caller attempts to invoke methods or
5677 * access properties not mentioned in @interface_info the
5678 * `org.freedesktop.DBus.Error.UnknownMethod` resp.
5679 * `org.freedesktop.DBus.Error.InvalidArgs` errors
5680 * are returned to the caller.
5682 * It is considered a programming error if the
5683 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
5684 * #GVariant of incorrect type.
5686 * If an existing callback is already registered at @object_path and
5687 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
5689 * GDBus automatically implements the standard D-Bus interfaces
5690 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
5691 * and org.freedesktop.Peer, so you don't have to implement those for the
5692 * objects you export. You can implement org.freedesktop.DBus.Properties
5693 * yourself, e.g. to handle getting and setting of properties asynchronously.
5695 * Note that the reference count on @interface_info will be
5696 * incremented by 1 (unless allocated statically, e.g. if the
5697 * reference count is -1, see g_dbus_interface_info_ref()) for as long
5698 * as the object is exported. Also note that @vtable will be copied.
5700 * See this [server][gdbus-server] for an example of how to use this method.
5702 * Returns: 0 if @error is set, otherwise a registration id (never 0)
5703 * that can be used with g_dbus_connection_unregister_object()
5708 g_dbus_connection_register_object (GDBusConnection *connection,
5709 const gchar *object_path,
5710 GDBusInterfaceInfo *interface_info,
5711 const GDBusInterfaceVTable *vtable,
5713 GDestroyNotify user_data_free_func,
5717 ExportedInterface *ei;
5720 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5721 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5722 g_return_val_if_fail (interface_info != NULL, 0);
5723 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
5724 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5725 g_return_val_if_fail (check_initialized (connection), 0);
5729 CONNECTION_LOCK (connection);
5731 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5734 eo = g_new0 (ExportedObject, 1);
5735 eo->object_path = g_strdup (object_path);
5736 eo->connection = connection;
5737 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
5740 (GDestroyNotify) exported_interface_free);
5741 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
5744 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
5750 _("An object is already exported for the interface %s at %s"),
5751 interface_info->name,
5756 ei = g_new0 (ExportedInterface, 1);
5757 ei->id = _global_registration_id++; /* TODO: overflow etc. */
5759 ei->user_data = user_data;
5760 ei->user_data_free_func = user_data_free_func;
5761 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
5762 ei->interface_info = g_dbus_interface_info_ref (interface_info);
5763 g_dbus_interface_info_cache_build (ei->interface_info);
5764 ei->interface_name = g_strdup (interface_info->name);
5765 ei->context = g_main_context_ref_thread_default ();
5767 g_hash_table_insert (eo->map_if_name_to_ei,
5768 (gpointer) ei->interface_name,
5770 g_hash_table_insert (connection->map_id_to_ei,
5771 GUINT_TO_POINTER (ei->id),
5777 CONNECTION_UNLOCK (connection);
5783 * g_dbus_connection_unregister_object:
5784 * @connection: a #GDBusConnection
5785 * @registration_id: a registration id obtained from
5786 * g_dbus_connection_register_object()
5788 * Unregisters an object.
5790 * Returns: %TRUE if the object was unregistered, %FALSE otherwise
5795 g_dbus_connection_unregister_object (GDBusConnection *connection,
5796 guint registration_id)
5798 ExportedInterface *ei;
5802 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5803 g_return_val_if_fail (check_initialized (connection), FALSE);
5807 CONNECTION_LOCK (connection);
5809 ei = g_hash_table_lookup (connection->map_id_to_ei,
5810 GUINT_TO_POINTER (registration_id));
5816 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5817 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5818 /* unregister object path if we have no more exported interfaces */
5819 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5820 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5826 CONNECTION_UNLOCK (connection);
5831 /* ---------------------------------------------------------------------------------------------------- */
5834 * g_dbus_connection_emit_signal:
5835 * @connection: a #GDBusConnection
5836 * @destination_bus_name: (allow-none): the unique bus name for the destination
5837 * for the signal or %NULL to emit to all listeners
5838 * @object_path: path of remote object
5839 * @interface_name: D-Bus interface to emit a signal on
5840 * @signal_name: the name of the signal to emit
5841 * @parameters: (allow-none): a #GVariant tuple with parameters for the signal
5842 * or %NULL if not passing parameters
5843 * @error: Return location for error or %NULL
5847 * If the parameters GVariant is floating, it is consumed.
5849 * This can only fail if @parameters is not compatible with the D-Bus protocol.
5851 * Returns: %TRUE unless @error is set
5856 g_dbus_connection_emit_signal (GDBusConnection *connection,
5857 const gchar *destination_bus_name,
5858 const gchar *object_path,
5859 const gchar *interface_name,
5860 const gchar *signal_name,
5861 GVariant *parameters,
5864 GDBusMessage *message;
5870 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5871 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5872 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5873 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5874 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5875 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5876 g_return_val_if_fail (check_initialized (connection), FALSE);
5878 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5880 _g_dbus_debug_print_lock ();
5881 g_print ("========================================================================\n"
5882 "GDBus-debug:Emission:\n"
5883 " >>>> SIGNAL EMISSION %s.%s()\n"
5885 " destination %s\n",
5886 interface_name, signal_name,
5888 destination_bus_name != NULL ? destination_bus_name : "(none)");
5889 _g_dbus_debug_print_unlock ();
5892 message = g_dbus_message_new_signal (object_path,
5896 if (destination_bus_name != NULL)
5897 g_dbus_message_set_header (message,
5898 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5899 g_variant_new_string (destination_bus_name));
5901 if (parameters != NULL)
5902 g_dbus_message_set_body (message, parameters);
5904 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5905 g_object_unref (message);
5911 add_call_flags (GDBusMessage *message,
5912 GDBusCallFlags flags)
5914 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5915 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
5919 decode_method_reply (GDBusMessage *reply,
5920 const gchar *method_name,
5921 const GVariantType *reply_type,
5922 GUnixFDList **out_fd_list,
5928 switch (g_dbus_message_get_message_type (reply))
5930 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5931 result = g_dbus_message_get_body (reply);
5934 result = g_variant_new ("()");
5935 g_variant_ref_sink (result);
5939 g_variant_ref (result);
5942 if (!g_variant_is_of_type (result, reply_type))
5944 gchar *type_string = g_variant_type_dup_string (reply_type);
5948 G_IO_ERROR_INVALID_ARGUMENT,
5949 _("Method '%s' returned type '%s', but expected '%s'"),
5950 method_name, g_variant_get_type_string (result), type_string);
5952 g_variant_unref (result);
5953 g_free (type_string);
5960 if (out_fd_list != NULL)
5962 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5963 if (*out_fd_list != NULL)
5964 g_object_ref (*out_fd_list);
5970 case G_DBUS_MESSAGE_TYPE_ERROR:
5971 g_dbus_message_to_gerror (reply, error);
5975 g_assert_not_reached ();
5985 GSimpleAsyncResult *simple;
5986 GVariantType *reply_type;
5987 gchar *method_name; /* for error message */
5991 GUnixFDList *fd_list;
5995 call_state_free (CallState *state)
5997 g_variant_type_free (state->reply_type);
5998 g_free (state->method_name);
6000 if (state->value != NULL)
6001 g_variant_unref (state->value);
6002 if (state->fd_list != NULL)
6003 g_object_unref (state->fd_list);
6004 g_slice_free (CallState, state);
6007 /* called in any thread, with the connection's lock not held */
6009 g_dbus_connection_call_done (GObject *source,
6010 GAsyncResult *result,
6013 GSimpleAsyncResult *simple;
6014 GDBusConnection *connection = G_DBUS_CONNECTION (source);
6015 CallState *state = user_data;
6017 GDBusMessage *reply;
6020 reply = g_dbus_connection_send_message_with_reply_finish (connection,
6024 if (G_UNLIKELY (_g_dbus_debug_call ()))
6026 _g_dbus_debug_print_lock ();
6027 g_print ("========================================================================\n"
6028 "GDBus-debug:Call:\n"
6029 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
6035 g_print ("SUCCESS\n");
6039 g_print ("FAILED: %s\n",
6042 _g_dbus_debug_print_unlock ();
6046 state->value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
6048 simple = state->simple; /* why? because state is freed before we unref simple.. */
6051 g_simple_async_result_take_error (state->simple, error);
6052 g_simple_async_result_complete (state->simple);
6053 call_state_free (state);
6057 g_simple_async_result_set_op_res_gpointer (state->simple, state, (GDestroyNotify) call_state_free);
6058 g_simple_async_result_complete (state->simple);
6060 g_clear_object (&reply);
6061 g_object_unref (simple);
6064 /* called in any thread, with the connection's lock not held */
6066 g_dbus_connection_call_internal (GDBusConnection *connection,
6067 const gchar *bus_name,
6068 const gchar *object_path,
6069 const gchar *interface_name,
6070 const gchar *method_name,
6071 GVariant *parameters,
6072 const GVariantType *reply_type,
6073 GDBusCallFlags flags,
6075 GUnixFDList *fd_list,
6076 GCancellable *cancellable,
6077 GAsyncReadyCallback callback,
6080 GDBusMessage *message;
6083 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
6084 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
6085 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
6086 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
6087 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
6088 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
6089 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
6090 g_return_if_fail (check_initialized (connection));
6092 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
6094 g_return_if_fail (fd_list == NULL);
6097 message = g_dbus_message_new_method_call (bus_name,
6101 add_call_flags (message, flags);
6102 if (parameters != NULL)
6103 g_dbus_message_set_body (message, parameters);
6106 if (fd_list != NULL)
6107 g_dbus_message_set_unix_fd_list (message, fd_list);
6110 /* If the user has no callback then we can just send the message with
6111 * the G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set and skip all
6112 * the logic for processing the reply. If the service sends the reply
6113 * anyway then it will just be ignored.
6115 if (callback != NULL)
6119 state = g_slice_new0 (CallState);
6120 state->simple = g_simple_async_result_new (G_OBJECT (connection),
6121 callback, user_data,
6122 g_dbus_connection_call_internal);
6123 g_simple_async_result_set_check_cancellable (state->simple, cancellable);
6124 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
6126 if (reply_type == NULL)
6127 reply_type = G_VARIANT_TYPE_ANY;
6129 state->reply_type = g_variant_type_copy (reply_type);
6131 g_dbus_connection_send_message_with_reply (connection,
6133 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
6137 g_dbus_connection_call_done,
6139 serial = state->serial;
6143 GDBusMessageFlags flags;
6145 flags = g_dbus_message_get_flags (message);
6146 flags |= G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
6147 g_dbus_message_set_flags (message, flags);
6149 g_dbus_connection_send_message (connection,
6151 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
6155 if (G_UNLIKELY (_g_dbus_debug_call ()))
6157 _g_dbus_debug_print_lock ();
6158 g_print ("========================================================================\n"
6159 "GDBus-debug:Call:\n"
6160 " >>>> ASYNC %s.%s()\n"
6162 " owned by name %s (serial %d)\n",
6166 bus_name != NULL ? bus_name : "(none)",
6168 _g_dbus_debug_print_unlock ();
6171 if (message != NULL)
6172 g_object_unref (message);
6175 /* called in any thread, with the connection's lock not held */
6177 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
6178 GUnixFDList **out_fd_list,
6182 GSimpleAsyncResult *simple;
6185 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
6186 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
6187 g_dbus_connection_call_internal), NULL);
6188 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6190 simple = G_SIMPLE_ASYNC_RESULT (res);
6192 if (g_simple_async_result_propagate_error (simple, error))
6195 state = g_simple_async_result_get_op_res_gpointer (simple);
6196 if (out_fd_list != NULL)
6197 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
6198 return g_variant_ref (state->value);
6201 /* called in any user thread, with the connection's lock not held */
6203 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
6204 const gchar *bus_name,
6205 const gchar *object_path,
6206 const gchar *interface_name,
6207 const gchar *method_name,
6208 GVariant *parameters,
6209 const GVariantType *reply_type,
6210 GDBusCallFlags flags,
6212 GUnixFDList *fd_list,
6213 GUnixFDList **out_fd_list,
6214 GCancellable *cancellable,
6217 GDBusMessage *message;
6218 GDBusMessage *reply;
6220 GError *local_error;
6221 GDBusSendMessageFlags send_flags;
6227 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
6228 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
6229 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
6230 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
6231 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
6232 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
6233 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
6235 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
6237 g_return_val_if_fail (fd_list == NULL, NULL);
6239 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6241 if (!(flags & CALL_FLAGS_INITIALIZING))
6242 g_return_val_if_fail (check_initialized (connection), FALSE);
6244 if (reply_type == NULL)
6245 reply_type = G_VARIANT_TYPE_ANY;
6247 message = g_dbus_message_new_method_call (bus_name,
6251 add_call_flags (message, flags);
6252 if (parameters != NULL)
6253 g_dbus_message_set_body (message, parameters);
6256 if (fd_list != NULL)
6257 g_dbus_message_set_unix_fd_list (message, fd_list);
6260 if (G_UNLIKELY (_g_dbus_debug_call ()))
6262 _g_dbus_debug_print_lock ();
6263 g_print ("========================================================================\n"
6264 "GDBus-debug:Call:\n"
6265 " >>>> SYNC %s.%s()\n"
6267 " owned by name %s\n",
6271 bus_name != NULL ? bus_name : "(none)");
6272 _g_dbus_debug_print_unlock ();
6277 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
6279 /* translate from one flavour of flags to another... */
6280 if (flags & CALL_FLAGS_INITIALIZING)
6281 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
6283 reply = g_dbus_connection_send_message_with_reply_sync (connection,
6287 NULL, /* volatile guint32 *out_serial */
6291 if (G_UNLIKELY (_g_dbus_debug_call ()))
6293 _g_dbus_debug_print_lock ();
6294 g_print ("========================================================================\n"
6295 "GDBus-debug:Call:\n"
6296 " <<<< SYNC COMPLETE %s.%s()\n"
6302 g_print ("SUCCESS\n");
6306 g_print ("FAILED: %s\n",
6307 local_error->message);
6309 _g_dbus_debug_print_unlock ();
6315 *error = local_error;
6317 g_error_free (local_error);
6321 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
6324 if (message != NULL)
6325 g_object_unref (message);
6327 g_object_unref (reply);
6332 /* ---------------------------------------------------------------------------------------------------- */
6335 * g_dbus_connection_call:
6336 * @connection: a #GDBusConnection
6337 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6338 * @connection is not a message bus connection
6339 * @object_path: path of remote object
6340 * @interface_name: D-Bus interface to invoke method on
6341 * @method_name: the name of the method to invoke
6342 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6343 * or %NULL if not passing parameters
6344 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6345 * @flags: flags from the #GDBusCallFlags enumeration
6346 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6347 * timeout or %G_MAXINT for no timeout
6348 * @cancellable: (allow-none): a #GCancellable or %NULL
6349 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request
6350 * is satisfied or %NULL if you don't care about the result of the
6352 * @user_data: the data to pass to @callback
6354 * Asynchronously invokes the @method_name method on the
6355 * @interface_name D-Bus interface on the remote object at
6356 * @object_path owned by @bus_name.
6358 * If @connection is closed then the operation will fail with
6359 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
6360 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
6361 * not compatible with the D-Bus protocol, the operation fails with
6362 * %G_IO_ERROR_INVALID_ARGUMENT.
6364 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
6365 * error will be raised if it does not match. Said another way, if you give a @reply_type
6366 * then any non-%NULL return value will be of this type.
6368 * If the @parameters #GVariant is floating, it is consumed. This allows
6369 * convenient 'inline' use of g_variant_new(), e.g.:
6370 * |[<!-- language="C" -->
6371 * g_dbus_connection_call (connection,
6372 * "org.freedesktop.StringThings",
6373 * "/org/freedesktop/StringThings",
6374 * "org.freedesktop.StringThings",
6376 * g_variant_new ("(ss)",
6380 * G_DBUS_CALL_FLAGS_NONE,
6383 * (GAsyncReadyCallback) two_strings_done,
6387 * This is an asynchronous method. When the operation is finished,
6388 * @callback will be invoked in the
6389 * [thread-default main context][g-main-context-push-thread-default]
6390 * of the thread you are calling this method from. You can then call
6391 * g_dbus_connection_call_finish() to get the result of the operation.
6392 * See g_dbus_connection_call_sync() for the synchronous version of this
6395 * If @callback is %NULL then the D-Bus method call message will be sent with
6396 * the %G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set.
6401 g_dbus_connection_call (GDBusConnection *connection,
6402 const gchar *bus_name,
6403 const gchar *object_path,
6404 const gchar *interface_name,
6405 const gchar *method_name,
6406 GVariant *parameters,
6407 const GVariantType *reply_type,
6408 GDBusCallFlags flags,
6410 GCancellable *cancellable,
6411 GAsyncReadyCallback callback,
6414 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);
6418 * g_dbus_connection_call_finish:
6419 * @connection: a #GDBusConnection
6420 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call()
6421 * @error: return location for error or %NULL
6423 * Finishes an operation started with g_dbus_connection_call().
6425 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6426 * return values. Free with g_variant_unref().
6431 g_dbus_connection_call_finish (GDBusConnection *connection,
6435 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
6439 * g_dbus_connection_call_sync:
6440 * @connection: a #GDBusConnection
6441 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6442 * @connection is not a message bus connection
6443 * @object_path: path of remote object
6444 * @interface_name: D-Bus interface to invoke method on
6445 * @method_name: the name of the method to invoke
6446 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6447 * or %NULL if not passing parameters
6448 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6449 * @flags: flags from the #GDBusCallFlags enumeration
6450 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6451 * timeout or %G_MAXINT for no timeout
6452 * @cancellable: (allow-none): a #GCancellable or %NULL
6453 * @error: return location for error or %NULL
6455 * Synchronously invokes the @method_name method on the
6456 * @interface_name D-Bus interface on the remote object at
6457 * @object_path owned by @bus_name.
6459 * If @connection is closed then the operation will fail with
6460 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
6461 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
6462 * contains a value not compatible with the D-Bus protocol, the operation
6463 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
6465 * If @reply_type is non-%NULL then the reply will be checked for having
6466 * this type and an error will be raised if it does not match. Said
6467 * another way, if you give a @reply_type then any non-%NULL return
6468 * value will be of this type.
6470 * If the @parameters #GVariant is floating, it is consumed.
6471 * This allows convenient 'inline' use of g_variant_new(), e.g.:
6472 * |[<!-- language="C" -->
6473 * g_dbus_connection_call_sync (connection,
6474 * "org.freedesktop.StringThings",
6475 * "/org/freedesktop/StringThings",
6476 * "org.freedesktop.StringThings",
6478 * g_variant_new ("(ss)",
6482 * G_DBUS_CALL_FLAGS_NONE,
6488 * The calling thread is blocked until a reply is received. See
6489 * g_dbus_connection_call() for the asynchronous version of
6492 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6493 * return values. Free with g_variant_unref().
6498 g_dbus_connection_call_sync (GDBusConnection *connection,
6499 const gchar *bus_name,
6500 const gchar *object_path,
6501 const gchar *interface_name,
6502 const gchar *method_name,
6503 GVariant *parameters,
6504 const GVariantType *reply_type,
6505 GDBusCallFlags flags,
6507 GCancellable *cancellable,
6510 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);
6513 /* ---------------------------------------------------------------------------------------------------- */
6518 * g_dbus_connection_call_with_unix_fd_list:
6519 * @connection: a #GDBusConnection
6520 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6521 * @connection is not a message bus connection
6522 * @object_path: path of remote object
6523 * @interface_name: D-Bus interface to invoke method on
6524 * @method_name: the name of the method to invoke
6525 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6526 * or %NULL if not passing parameters
6527 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6528 * @flags: flags from the #GDBusCallFlags enumeration
6529 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6530 * timeout or %G_MAXINT for no timeout
6531 * @fd_list: (allow-none): a #GUnixFDList or %NULL
6532 * @cancellable: (allow-none): a #GCancellable or %NULL
6533 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request is
6534 * satisfied or %NULL if you don't * care about the result of the
6536 * @user_data: The data to pass to @callback.
6538 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
6540 * This method is only available on UNIX.
6545 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
6546 const gchar *bus_name,
6547 const gchar *object_path,
6548 const gchar *interface_name,
6549 const gchar *method_name,
6550 GVariant *parameters,
6551 const GVariantType *reply_type,
6552 GDBusCallFlags flags,
6554 GUnixFDList *fd_list,
6555 GCancellable *cancellable,
6556 GAsyncReadyCallback callback,
6559 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);
6563 * g_dbus_connection_call_with_unix_fd_list_finish:
6564 * @connection: a #GDBusConnection
6565 * @out_fd_list: (out) (allow-none): return location for a #GUnixFDList or %NULL
6566 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
6567 * g_dbus_connection_call_with_unix_fd_list()
6568 * @error: return location for error or %NULL
6570 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
6572 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6573 * return values. Free with g_variant_unref().
6578 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
6579 GUnixFDList **out_fd_list,
6583 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
6587 * g_dbus_connection_call_with_unix_fd_list_sync:
6588 * @connection: a #GDBusConnection
6589 * @bus_name: (allow-none): a unique or well-known bus name or %NULL
6590 * if @connection is not a message bus connection
6591 * @object_path: path of remote object
6592 * @interface_name: D-Bus interface to invoke method on
6593 * @method_name: the name of the method to invoke
6594 * @parameters: (allow-none): a #GVariant tuple with parameters for
6595 * the method or %NULL if not passing parameters
6596 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6597 * @flags: flags from the #GDBusCallFlags enumeration
6598 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6599 * timeout or %G_MAXINT for no timeout
6600 * @fd_list: (allow-none): a #GUnixFDList or %NULL
6601 * @out_fd_list: (out) (allow-none): return location for a #GUnixFDList or %NULL
6602 * @cancellable: (allow-none): a #GCancellable or %NULL
6603 * @error: return location for error or %NULL
6605 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
6607 * This method is only available on UNIX.
6609 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6610 * return values. Free with g_variant_unref().
6615 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
6616 const gchar *bus_name,
6617 const gchar *object_path,
6618 const gchar *interface_name,
6619 const gchar *method_name,
6620 GVariant *parameters,
6621 const GVariantType *reply_type,
6622 GDBusCallFlags flags,
6624 GUnixFDList *fd_list,
6625 GUnixFDList **out_fd_list,
6626 GCancellable *cancellable,
6629 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);
6632 #endif /* G_OS_UNIX */
6634 /* ---------------------------------------------------------------------------------------------------- */
6636 struct ExportedSubtree
6640 GDBusConnection *connection;
6641 GDBusSubtreeVTable *vtable;
6642 GDBusSubtreeFlags flags;
6644 GMainContext *context;
6646 GDestroyNotify user_data_free_func;
6650 exported_subtree_free (ExportedSubtree *es)
6652 call_destroy_notify (es->context,
6653 es->user_data_free_func,
6656 g_main_context_unref (es->context);
6658 _g_dbus_subtree_vtable_free (es->vtable);
6659 g_free (es->object_path);
6663 /* called without lock held in the thread where the caller registered
6667 handle_subtree_introspect (GDBusConnection *connection,
6668 ExportedSubtree *es,
6669 GDBusMessage *message)
6673 GDBusMessage *reply;
6676 const gchar *sender;
6677 const gchar *requested_object_path;
6678 const gchar *requested_node;
6679 GDBusInterfaceInfo **interfaces;
6681 gchar **subnode_paths;
6682 gboolean has_properties_interface;
6683 gboolean has_introspectable_interface;
6687 requested_object_path = g_dbus_message_get_path (message);
6688 sender = g_dbus_message_get_sender (message);
6689 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6691 s = g_string_new (NULL);
6692 introspect_append_header (s);
6694 /* Strictly we don't need the children in dynamic mode, but we avoid the
6695 * conditionals to preserve code clarity
6697 children = es->vtable->enumerate (es->connection,
6704 requested_node = strrchr (requested_object_path, '/') + 1;
6706 /* Assert existence of object if we are not dynamic */
6707 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
6708 !_g_strv_has_string ((const gchar * const *) children, requested_node))
6713 requested_node = NULL;
6716 interfaces = es->vtable->introspect (es->connection,
6721 if (interfaces != NULL)
6723 has_properties_interface = FALSE;
6724 has_introspectable_interface = FALSE;
6726 for (n = 0; interfaces[n] != NULL; n++)
6728 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
6729 has_properties_interface = TRUE;
6730 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
6731 has_introspectable_interface = TRUE;
6733 if (!has_properties_interface)
6734 g_string_append (s, introspect_properties_interface);
6735 if (!has_introspectable_interface)
6736 g_string_append (s, introspect_introspectable_interface);
6738 for (n = 0; interfaces[n] != NULL; n++)
6740 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
6741 g_dbus_interface_info_unref (interfaces[n]);
6743 g_free (interfaces);
6746 /* then include <node> entries from the Subtree for the root */
6749 for (n = 0; children != NULL && children[n] != NULL; n++)
6750 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
6753 /* finally include nodes registered below us */
6754 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
6755 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
6756 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
6757 g_strfreev (subnode_paths);
6759 g_string_append (s, "</node>\n");
6761 reply = g_dbus_message_new_method_reply (message);
6762 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6763 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6764 g_object_unref (reply);
6769 g_string_free (s, TRUE);
6770 g_strfreev (children);
6774 /* called without lock held in the thread where the caller registered
6778 handle_subtree_method_invocation (GDBusConnection *connection,
6779 ExportedSubtree *es,
6780 GDBusMessage *message)
6783 const gchar *sender;
6784 const gchar *interface_name;
6785 const gchar *member;
6786 const gchar *signature;
6787 const gchar *requested_object_path;
6788 const gchar *requested_node;
6790 GDBusInterfaceInfo *interface_info;
6791 const GDBusInterfaceVTable *interface_vtable;
6792 gpointer interface_user_data;
6794 GDBusInterfaceInfo **interfaces;
6795 gboolean is_property_get;
6796 gboolean is_property_set;
6797 gboolean is_property_get_all;
6802 requested_object_path = g_dbus_message_get_path (message);
6803 sender = g_dbus_message_get_sender (message);
6804 interface_name = g_dbus_message_get_interface (message);
6805 member = g_dbus_message_get_member (message);
6806 signature = g_dbus_message_get_signature (message);
6807 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6809 is_property_get = FALSE;
6810 is_property_set = FALSE;
6811 is_property_get_all = FALSE;
6812 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6814 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6815 is_property_get = TRUE;
6816 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6817 is_property_set = TRUE;
6818 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6819 is_property_get_all = TRUE;
6824 requested_node = strrchr (requested_object_path, '/') + 1;
6826 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6828 /* We don't want to dispatch to unenumerated
6829 * nodes, so ensure that the child exists.
6834 children = es->vtable->enumerate (es->connection,
6839 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6840 g_strfreev (children);
6848 requested_node = NULL;
6851 /* get introspection data for the node */
6852 interfaces = es->vtable->introspect (es->connection,
6854 requested_object_path,
6858 if (interfaces == NULL)
6861 interface_info = NULL;
6862 for (n = 0; interfaces[n] != NULL; n++)
6864 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6865 interface_info = interfaces[n];
6868 /* dispatch the call if the user wants to handle it */
6869 if (interface_info != NULL)
6871 /* figure out where to dispatch the method call */
6872 interface_user_data = NULL;
6873 interface_vtable = es->vtable->dispatch (es->connection,
6878 &interface_user_data,
6880 if (interface_vtable == NULL)
6883 CONNECTION_LOCK (connection);
6884 handled = validate_and_maybe_schedule_method_call (es->connection,
6891 interface_user_data);
6892 CONNECTION_UNLOCK (connection);
6894 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6895 else if (is_property_get || is_property_set || is_property_get_all)
6897 if (is_property_get)
6898 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6899 else if (is_property_set)
6900 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6901 else if (is_property_get_all)
6902 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6904 g_assert_not_reached ();
6906 /* see if the object supports this interface at all */
6907 for (n = 0; interfaces[n] != NULL; n++)
6909 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6910 interface_info = interfaces[n];
6913 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6914 * claims it won't support the interface
6916 if (interface_info == NULL)
6918 GDBusMessage *reply;
6919 reply = g_dbus_message_new_method_error (message,
6920 "org.freedesktop.DBus.Error.InvalidArgs",
6921 _("No such interface '%s'"),
6923 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6924 g_object_unref (reply);
6929 /* figure out where to dispatch the property get/set/getall calls */
6930 interface_user_data = NULL;
6931 interface_vtable = es->vtable->dispatch (es->connection,
6936 &interface_user_data,
6938 if (interface_vtable == NULL)
6940 g_warning ("The subtree introspection function indicates that '%s' "
6941 "is a valid interface name, but calling the dispatch "
6942 "function on that interface gave us NULL", interface_name);
6946 if (is_property_get || is_property_set)
6948 CONNECTION_LOCK (connection);
6949 handled = validate_and_maybe_schedule_property_getset (es->connection,
6957 interface_user_data);
6958 CONNECTION_UNLOCK (connection);
6960 else if (is_property_get_all)
6962 CONNECTION_LOCK (connection);
6963 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6970 interface_user_data);
6971 CONNECTION_UNLOCK (connection);
6976 if (interfaces != NULL)
6978 for (n = 0; interfaces[n] != NULL; n++)
6979 g_dbus_interface_info_unref (interfaces[n]);
6980 g_free (interfaces);
6988 GDBusMessage *message;
6989 ExportedSubtree *es;
6990 } SubtreeDeferredData;
6993 subtree_deferred_data_free (SubtreeDeferredData *data)
6995 g_object_unref (data->message);
6999 /* called without lock held in the thread where the caller registered the subtree */
7001 process_subtree_vtable_message_in_idle_cb (gpointer _data)
7003 SubtreeDeferredData *data = _data;
7008 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
7009 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
7010 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
7011 handled = handle_subtree_introspect (data->es->connection,
7015 handled = handle_subtree_method_invocation (data->es->connection,
7021 CONNECTION_LOCK (data->es->connection);
7022 handled = handle_generic_unlocked (data->es->connection, data->message);
7023 CONNECTION_UNLOCK (data->es->connection);
7026 /* if we couldn't handle the request, just bail with the UnknownMethod error */
7029 GDBusMessage *reply;
7030 reply = g_dbus_message_new_method_error (data->message,
7031 "org.freedesktop.DBus.Error.UnknownMethod",
7032 _("Method '%s' on interface '%s' with signature '%s' does not exist"),
7033 g_dbus_message_get_member (data->message),
7034 g_dbus_message_get_interface (data->message),
7035 g_dbus_message_get_signature (data->message));
7036 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7037 g_object_unref (reply);
7043 /* called in GDBusWorker thread with connection's lock held */
7045 subtree_message_func (GDBusConnection *connection,
7046 ExportedSubtree *es,
7047 GDBusMessage *message)
7049 GSource *idle_source;
7050 SubtreeDeferredData *data;
7052 data = g_new0 (SubtreeDeferredData, 1);
7053 data->message = g_object_ref (message);
7056 /* defer this call to an idle handler in the right thread */
7057 idle_source = g_idle_source_new ();
7058 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
7059 g_source_set_callback (idle_source,
7060 process_subtree_vtable_message_in_idle_cb,
7062 (GDestroyNotify) subtree_deferred_data_free);
7063 g_source_set_name (idle_source, "[gio] process_subtree_vtable_message_in_idle_cb");
7064 g_source_attach (idle_source, es->context);
7065 g_source_unref (idle_source);
7067 /* since we own the entire subtree, handlers for objects not in the subtree have been
7068 * tried already by libdbus-1 - so we just need to ensure that we're always going
7069 * to reply to the message
7075 * g_dbus_connection_register_subtree:
7076 * @connection: a #GDBusConnection
7077 * @object_path: the object path to register the subtree at
7078 * @vtable: a #GDBusSubtreeVTable to enumerate, introspect and
7079 * dispatch nodes in the subtree
7080 * @flags: flags used to fine tune the behavior of the subtree
7081 * @user_data: data to pass to functions in @vtable
7082 * @user_data_free_func: function to call when the subtree is unregistered
7083 * @error: return location for error or %NULL
7085 * Registers a whole subtree of dynamic objects.
7087 * The @enumerate and @introspection functions in @vtable are used to
7088 * convey, to remote callers, what nodes exist in the subtree rooted
7091 * When handling remote calls into any node in the subtree, first the
7092 * @enumerate function is used to check if the node exists. If the node exists
7093 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
7094 * the @introspection function is used to check if the node supports the
7095 * requested method. If so, the @dispatch function is used to determine
7096 * where to dispatch the call. The collected #GDBusInterfaceVTable and
7097 * #gpointer will be used to call into the interface vtable for processing
7100 * All calls into user-provided code will be invoked in the
7101 * [thread-default main context][g-main-context-push-thread-default]
7102 * of the thread you are calling this method from.
7104 * If an existing subtree is already registered at @object_path or
7105 * then @error is set to #G_IO_ERROR_EXISTS.
7107 * Note that it is valid to register regular objects (using
7108 * g_dbus_connection_register_object()) in a subtree registered with
7109 * g_dbus_connection_register_subtree() - if so, the subtree handler
7110 * is tried as the last resort. One way to think about a subtree
7111 * handler is to consider it a fallback handler for object paths not
7112 * registered via g_dbus_connection_register_object() or other bindings.
7114 * Note that @vtable will be copied so you cannot change it after
7117 * See this [server][gdbus-subtree-server] for an example of how to use
7120 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
7121 * that can be used with g_dbus_connection_unregister_subtree() .
7126 g_dbus_connection_register_subtree (GDBusConnection *connection,
7127 const gchar *object_path,
7128 const GDBusSubtreeVTable *vtable,
7129 GDBusSubtreeFlags flags,
7131 GDestroyNotify user_data_free_func,
7135 ExportedSubtree *es;
7137 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
7138 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
7139 g_return_val_if_fail (vtable != NULL, 0);
7140 g_return_val_if_fail (error == NULL || *error == NULL, 0);
7141 g_return_val_if_fail (check_initialized (connection), 0);
7145 CONNECTION_LOCK (connection);
7147 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
7153 _("A subtree is already exported for %s"),
7158 es = g_new0 (ExportedSubtree, 1);
7159 es->object_path = g_strdup (object_path);
7160 es->connection = connection;
7162 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
7164 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
7165 es->user_data = user_data;
7166 es->user_data_free_func = user_data_free_func;
7167 es->context = g_main_context_ref_thread_default ();
7169 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
7170 g_hash_table_insert (connection->map_id_to_es,
7171 GUINT_TO_POINTER (es->id),
7177 CONNECTION_UNLOCK (connection);
7182 /* ---------------------------------------------------------------------------------------------------- */
7185 * g_dbus_connection_unregister_subtree:
7186 * @connection: a #GDBusConnection
7187 * @registration_id: a subtree registration id obtained from
7188 * g_dbus_connection_register_subtree()
7190 * Unregisters a subtree.
7192 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise
7197 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
7198 guint registration_id)
7200 ExportedSubtree *es;
7203 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
7204 g_return_val_if_fail (check_initialized (connection), FALSE);
7208 CONNECTION_LOCK (connection);
7210 es = g_hash_table_lookup (connection->map_id_to_es,
7211 GUINT_TO_POINTER (registration_id));
7215 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
7216 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
7221 CONNECTION_UNLOCK (connection);
7226 /* ---------------------------------------------------------------------------------------------------- */
7228 /* may be called in any thread, with connection's lock held */
7230 handle_generic_ping_unlocked (GDBusConnection *connection,
7231 const gchar *object_path,
7232 GDBusMessage *message)
7234 GDBusMessage *reply;
7235 reply = g_dbus_message_new_method_reply (message);
7236 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7237 g_object_unref (reply);
7240 /* may be called in any thread, with connection's lock held */
7242 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
7243 const gchar *object_path,
7244 GDBusMessage *message)
7246 GDBusMessage *reply;
7249 if (connection->machine_id == NULL)
7254 connection->machine_id = _g_dbus_get_machine_id (&error);
7255 if (connection->machine_id == NULL)
7257 reply = g_dbus_message_new_method_error_literal (message,
7258 "org.freedesktop.DBus.Error.Failed",
7260 g_error_free (error);
7266 reply = g_dbus_message_new_method_reply (message);
7267 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
7269 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7270 g_object_unref (reply);
7273 /* may be called in any thread, with connection's lock held */
7275 handle_generic_introspect_unlocked (GDBusConnection *connection,
7276 const gchar *object_path,
7277 GDBusMessage *message)
7282 GDBusMessage *reply;
7284 /* first the header */
7285 s = g_string_new (NULL);
7286 introspect_append_header (s);
7288 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
7289 for (n = 0; registered != NULL && registered[n] != NULL; n++)
7290 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
7291 g_strfreev (registered);
7292 g_string_append (s, "</node>\n");
7294 reply = g_dbus_message_new_method_reply (message);
7295 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
7296 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7297 g_object_unref (reply);
7298 g_string_free (s, TRUE);
7301 /* may be called in any thread, with connection's lock held */
7303 handle_generic_unlocked (GDBusConnection *connection,
7304 GDBusMessage *message)
7307 const gchar *interface_name;
7308 const gchar *member;
7309 const gchar *signature;
7312 CONNECTION_ENSURE_LOCK (connection);
7316 interface_name = g_dbus_message_get_interface (message);
7317 member = g_dbus_message_get_member (message);
7318 signature = g_dbus_message_get_signature (message);
7319 path = g_dbus_message_get_path (message);
7321 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
7322 g_strcmp0 (member, "Introspect") == 0 &&
7323 g_strcmp0 (signature, "") == 0)
7325 handle_generic_introspect_unlocked (connection, path, message);
7328 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7329 g_strcmp0 (member, "Ping") == 0 &&
7330 g_strcmp0 (signature, "") == 0)
7332 handle_generic_ping_unlocked (connection, path, message);
7335 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7336 g_strcmp0 (member, "GetMachineId") == 0 &&
7337 g_strcmp0 (signature, "") == 0)
7339 handle_generic_get_machine_id_unlocked (connection, path, message);
7346 /* ---------------------------------------------------------------------------------------------------- */
7348 /* called in GDBusWorker thread with connection's lock held */
7350 distribute_method_call (GDBusConnection *connection,
7351 GDBusMessage *message)
7353 GDBusMessage *reply;
7355 ExportedSubtree *es;
7356 const gchar *object_path;
7357 const gchar *interface_name;
7358 const gchar *member;
7360 gchar *subtree_path;
7363 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
7365 interface_name = g_dbus_message_get_interface (message);
7366 member = g_dbus_message_get_member (message);
7367 path = g_dbus_message_get_path (message);
7368 subtree_path = g_strdup (path);
7369 needle = strrchr (subtree_path, '/');
7370 if (needle != NULL && needle != subtree_path)
7376 g_free (subtree_path);
7377 subtree_path = NULL;
7381 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
7383 _g_dbus_debug_print_lock ();
7384 g_print ("========================================================================\n"
7385 "GDBus-debug:Incoming:\n"
7386 " <<<< METHOD INVOCATION %s.%s()\n"
7388 " invoked by name %s\n"
7390 interface_name, member,
7392 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
7393 g_dbus_message_get_serial (message));
7394 _g_dbus_debug_print_unlock ();
7397 object_path = g_dbus_message_get_path (message);
7398 g_assert (object_path != NULL);
7400 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
7403 if (obj_message_func (connection, eo, message))
7407 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
7410 if (subtree_message_func (connection, es, message))
7414 if (subtree_path != NULL)
7416 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
7419 if (subtree_message_func (connection, es, message))
7424 if (handle_generic_unlocked (connection, message))
7427 /* if we end up here, the message has not been not handled - so return an error saying this */
7428 reply = g_dbus_message_new_method_error (message,
7429 "org.freedesktop.DBus.Error.UnknownMethod",
7430 _("No such interface '%s' on object at path %s"),
7433 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7434 g_object_unref (reply);
7437 g_free (subtree_path);
7440 /* ---------------------------------------------------------------------------------------------------- */
7442 /* Called in any user thread, with the message_bus_lock held. */
7444 message_bus_get_singleton (GBusType bus_type,
7448 const gchar *starter_bus;
7454 case G_BUS_TYPE_SESSION:
7455 ret = &the_session_bus;
7458 case G_BUS_TYPE_SYSTEM:
7459 ret = &the_system_bus;
7462 case G_BUS_TYPE_USER:
7463 ret = &the_user_bus;
7466 case G_BUS_TYPE_MACHINE:
7467 ret = &the_machine_bus;
7470 case G_BUS_TYPE_STARTER:
7471 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
7472 if (g_strcmp0 (starter_bus, "session") == 0)
7474 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
7477 else if (g_strcmp0 (starter_bus, "system") == 0)
7479 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
7484 if (starter_bus != NULL)
7488 G_IO_ERROR_INVALID_ARGUMENT,
7489 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
7490 " - unknown value '%s'"),
7495 g_set_error_literal (error,
7497 G_IO_ERROR_INVALID_ARGUMENT,
7498 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
7499 "variable is not set"));
7505 g_assert_not_reached ();
7513 /* Called in any user thread, without holding locks. */
7514 static GDBusConnection *
7515 get_uninitialized_connection (GBusType bus_type,
7516 GCancellable *cancellable,
7519 GWeakRef *singleton;
7520 GDBusConnection *ret;
7524 G_LOCK (message_bus_lock);
7525 singleton = message_bus_get_singleton (bus_type, error);
7526 if (singleton == NULL)
7529 ret = g_weak_ref_get (singleton);
7534 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
7535 if (address == NULL)
7537 ret = g_object_new (G_TYPE_DBUS_CONNECTION,
7539 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
7540 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
7541 "exit-on-close", TRUE,
7544 g_weak_ref_set (singleton, ret);
7548 g_assert (ret != NULL);
7551 G_UNLOCK (message_bus_lock);
7555 /* May be called from any thread. Must not hold message_bus_lock. */
7557 _g_bus_get_singleton_if_exists (GBusType bus_type)
7559 GWeakRef *singleton;
7560 GDBusConnection *ret = NULL;
7562 G_LOCK (message_bus_lock);
7563 singleton = message_bus_get_singleton (bus_type, NULL);
7564 if (singleton == NULL)
7567 ret = g_weak_ref_get (singleton);
7570 G_UNLOCK (message_bus_lock);
7576 * @bus_type: a #GBusType
7577 * @cancellable: (allow-none): a #GCancellable or %NULL
7578 * @error: return location for error or %NULL
7580 * Synchronously connects to the message bus specified by @bus_type.
7581 * Note that the returned object may shared with other callers,
7582 * e.g. if two separate parts of a process calls this function with
7583 * the same @bus_type, they will share the same object.
7585 * This is a synchronous failable function. See g_bus_get() and
7586 * g_bus_get_finish() for the asynchronous version.
7588 * The returned object is a singleton, that is, shared with other
7589 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7590 * event that you need a private message bus connection, use
7591 * g_dbus_address_get_for_bus_sync() and
7592 * g_dbus_connection_new_for_address().
7594 * Note that the returned #GDBusConnection object will (usually) have
7595 * the #GDBusConnection:exit-on-close property set to %TRUE.
7597 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7598 * Free with g_object_unref().
7603 g_bus_get_sync (GBusType bus_type,
7604 GCancellable *cancellable,
7607 GDBusConnection *connection;
7609 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7611 connection = get_uninitialized_connection (bus_type, cancellable, error);
7612 if (connection == NULL)
7615 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
7617 g_object_unref (connection);
7626 bus_get_async_initable_cb (GObject *source_object,
7630 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
7634 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
7638 g_assert (error != NULL);
7639 g_simple_async_result_take_error (simple, error);
7640 g_object_unref (source_object);
7644 g_simple_async_result_set_op_res_gpointer (simple,
7648 g_simple_async_result_complete_in_idle (simple);
7649 g_object_unref (simple);
7654 * @bus_type: a #GBusType
7655 * @cancellable: (allow-none): a #GCancellable or %NULL
7656 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
7657 * @user_data: the data to pass to @callback
7659 * Asynchronously connects to the message bus specified by @bus_type.
7661 * When the operation is finished, @callback will be invoked. You can
7662 * then call g_bus_get_finish() to get the result of the operation.
7664 * This is a asynchronous failable function. See g_bus_get_sync() for
7665 * the synchronous version.
7670 g_bus_get (GBusType bus_type,
7671 GCancellable *cancellable,
7672 GAsyncReadyCallback callback,
7675 GDBusConnection *connection;
7676 GSimpleAsyncResult *simple;
7679 simple = g_simple_async_result_new (NULL,
7683 g_simple_async_result_set_check_cancellable (simple, cancellable);
7686 connection = get_uninitialized_connection (bus_type, cancellable, &error);
7687 if (connection == NULL)
7689 g_assert (error != NULL);
7690 g_simple_async_result_take_error (simple, error);
7691 g_simple_async_result_complete_in_idle (simple);
7692 g_object_unref (simple);
7696 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
7699 bus_get_async_initable_cb,
7706 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
7708 * @error: return location for error or %NULL
7710 * Finishes an operation started with g_bus_get().
7712 * The returned object is a singleton, that is, shared with other
7713 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7714 * event that you need a private message bus connection, use
7715 * g_dbus_address_get_for_bus_sync() and
7716 * g_dbus_connection_new_for_address().
7718 * Note that the returned #GDBusConnection object will (usually) have
7719 * the #GDBusConnection:exit-on-close property set to %TRUE.
7721 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7722 * Free with g_object_unref().
7727 g_bus_get_finish (GAsyncResult *res,
7730 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
7732 GDBusConnection *ret;
7734 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7736 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
7740 if (g_simple_async_result_propagate_error (simple, error))
7743 object = g_simple_async_result_get_op_res_gpointer (simple);
7744 g_assert (object != NULL);
7745 ret = g_object_ref (G_DBUS_CONNECTION (object));
7751 /* ---------------------------------------------------------------------------------------------------- */