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"
125 #include "gunixconnection.h"
126 #include "gunixfdmessage.h"
129 #include "glibintl.h"
132 * SECTION:gdbusconnection
133 * @short_description: D-Bus Connections
134 * @include: gio/gio.h
136 * The #GDBusConnection type is used for D-Bus connections to remote
137 * peers such as a message buses. It is a low-level API that offers a
138 * lot of flexibility. For instance, it lets you establish a connection
139 * over any transport that can by represented as an #GIOStream.
141 * This class is rarely used directly in D-Bus clients. If you are writing
142 * an D-Bus client, it is often easier to use the g_bus_own_name(),
143 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
145 * As an exception to the usual GLib rule that a particular object must not
146 * be used by two threads at the same time, #GDBusConnection's methods may be
147 * called from any thread. This is so that g_bus_get() and g_bus_get_sync()
148 * can safely return the same #GDBusConnection when called from any thread.
150 * Most of the ways to obtain a #GDBusConnection automatically initialize it
151 * (i.e. connect to D-Bus): for instance, g_dbus_connection_new() and
152 * g_bus_get(), and the synchronous versions of those methods, give you an
153 * initialized connection. Language bindings for GIO should use
154 * g_initable_new() or g_async_initable_new_async(), which also initialize the
157 * If you construct an uninitialized #GDBusConnection, such as via
158 * g_object_new(), you must initialize it via g_initable_init() or
159 * g_async_initable_init_async() before using its methods or properties.
160 * Calling methods or accessing properties on a #GDBusConnection that has not
161 * completed initialization successfully is considered to be invalid, and leads
162 * to undefined behaviour. In particular, if initialization fails with a
163 * #GError, the only valid thing you can do with that #GDBusConnection is to
164 * free it with g_object_unref().
166 * ## An example D-Bus server # {#gdbus-server}
168 * Here is an example for a D-Bus server:
169 * [gdbus-example-server.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-server.c)
171 * ## An example for exporting a subtree # {#gdbus-subtree-server}
173 * Here is an example for exporting a subtree:
174 * [gdbus-example-subtree.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-subtree.c)
176 * ## An example for file descriptor passing # {#gdbus-unix-fd-client}
178 * Here is an example for passing UNIX file descriptors:
179 * [gdbus-unix-fd-client.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-unix-fd-client.c)
181 * ## An example for exporting a GObject # {#gdbus-export}
183 * Here is an example for exporting a #GObject:
184 * [gdbus-example-export.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-export.c)
187 /* ---------------------------------------------------------------------------------------------------- */
189 typedef struct _GDBusConnectionClass GDBusConnectionClass;
192 * GDBusConnectionClass:
193 * @closed: Signal class handler for the #GDBusConnection::closed signal.
195 * Class structure for #GDBusConnection.
199 struct _GDBusConnectionClass
202 GObjectClass parent_class;
206 void (*closed) (GDBusConnection *connection,
207 gboolean remote_peer_vanished,
211 G_LOCK_DEFINE_STATIC (message_bus_lock);
213 static GWeakRef the_session_bus;
214 static GWeakRef the_system_bus;
216 /* Extra pseudo-member of GDBusSendMessageFlags.
217 * Set by initable_init() to indicate that despite not being initialized yet,
218 * enough of the only-valid-after-init members are set that we can send a
219 * message, and we're being called from its thread, so no memory barrier is
220 * required before accessing them.
222 #define SEND_MESSAGE_FLAGS_INITIALIZING (1<<31)
224 /* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
225 #define CALL_FLAGS_INITIALIZING (1<<31)
227 /* ---------------------------------------------------------------------------------------------------- */
231 GDestroyNotify callback;
233 GMainContext *context;
234 } CallDestroyNotifyData;
237 call_destroy_notify_data_in_idle (gpointer user_data)
239 CallDestroyNotifyData *data = user_data;
240 data->callback (data->user_data);
245 call_destroy_notify_data_free (CallDestroyNotifyData *data)
247 if (data->context != NULL)
248 g_main_context_unref (data->context);
253 * call_destroy_notify: <internal>
254 * @context: (allow-none): A #GMainContext or %NULL.
255 * @callback: (allow-none): A #GDestroyNotify or %NULL.
256 * @user_data: Data to pass to @callback.
258 * Schedules @callback to run in @context.
261 call_destroy_notify (GMainContext *context,
262 GDestroyNotify callback,
265 GSource *idle_source;
266 CallDestroyNotifyData *data;
268 if (callback == NULL)
271 data = g_new0 (CallDestroyNotifyData, 1);
272 data->callback = callback;
273 data->user_data = user_data;
274 data->context = context;
275 if (data->context != NULL)
276 g_main_context_ref (data->context);
278 idle_source = g_idle_source_new ();
279 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
280 g_source_set_callback (idle_source,
281 call_destroy_notify_data_in_idle,
283 (GDestroyNotify) call_destroy_notify_data_free);
284 g_source_attach (idle_source, data->context);
285 g_source_unref (idle_source);
291 /* ---------------------------------------------------------------------------------------------------- */
294 _g_strv_has_string (const gchar* const *haystack,
299 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
301 if (g_strcmp0 (haystack[n], needle) == 0)
307 /* ---------------------------------------------------------------------------------------------------- */
310 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
312 // TODO: for some reason this doesn't work on Windows
313 #define CONNECTION_ENSURE_LOCK(obj) do { \
314 if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock))) \
316 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
317 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
322 #define CONNECTION_LOCK(obj) do { \
323 g_mutex_lock (&(obj)->lock); \
326 #define CONNECTION_UNLOCK(obj) do { \
327 g_mutex_unlock (&(obj)->lock); \
330 /* Flags in connection->atomic_flags */
332 FLAG_INITIALIZED = 1 << 0,
333 FLAG_EXIT_ON_CLOSE = 1 << 1,
340 * The #GDBusConnection structure contains only private data and
341 * should only be accessed using the provided API.
345 struct _GDBusConnection
348 GObject parent_instance;
350 /* ------------------------------------------------------------------------ */
351 /* -- General object state ------------------------------------------------ */
352 /* ------------------------------------------------------------------------ */
354 /* General-purpose lock for most fields */
357 /* A lock used in the init() method of the GInitable interface - see comments
358 * in initable_init() for why a separate lock is needed.
360 * If you need both @lock and @init_lock, you must take @init_lock first.
364 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
365 * someone calls org.freedesktop.DBus.Peer.GetMachineId(). Protected by @lock.
369 /* The underlying stream used for communication
370 * Read-only after initable_init(), so it may be read if you either
371 * hold @init_lock or check for initialization first.
375 /* The object used for authentication (if any).
376 * Read-only after initable_init(), so it may be read if you either
377 * hold @init_lock or check for initialization first.
381 /* Last serial used. Protected by @lock. */
384 /* The object used to send/receive messages.
385 * Read-only after initable_init(), so it may be read if you either
386 * hold @init_lock or check for initialization first.
390 /* If connected to a message bus, this contains the unique name assigned to
391 * us by the bus (e.g. ":1.42").
392 * Read-only after initable_init(), so it may be read if you either
393 * hold @init_lock or check for initialization first.
395 gchar *bus_unique_name;
397 /* The GUID returned by the other side if we authenticed as a client or
398 * the GUID to use if authenticating as a server.
399 * Read-only after initable_init(), so it may be read if you either
400 * hold @init_lock or check for initialization first.
404 /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
405 * Inspect @initialization_error to see whether it succeeded or failed.
407 * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
409 * FLAG_CLOSED is the closed property. It may be read at any time, but
410 * may only be written while holding @lock.
412 volatile gint atomic_flags;
414 /* If the connection could not be established during initable_init(),
415 * this GError will be set.
416 * Read-only after initable_init(), so it may be read if you either
417 * hold @init_lock or check for initialization first.
419 GError *initialization_error;
421 /* The result of g_main_context_ref_thread_default() when the object
422 * was created (the GObject _init() function) - this is used for delivery
423 * of the :closed GObject signal.
425 * Only set in the GObject init function, so no locks are needed.
427 GMainContext *main_context_at_construction;
429 /* Read-only construct properties, no locks needed */
431 GDBusConnectionFlags flags;
433 /* Map used for managing method replies, protected by @lock */
434 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
436 /* Maps used for managing signal subscription, protected by @lock */
437 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
438 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
439 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
441 /* Maps used for managing exported objects and subtrees,
444 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
445 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
446 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
447 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
449 /* Map used for storing last used serials for each thread, protected by @lock */
450 GHashTable *map_thread_to_last_serial;
452 /* Structure used for message filters, protected by @lock */
455 /* Capabilities negotiated during authentication
456 * Read-only after initable_init(), so it may be read without holding a
457 * lock, if you check for initialization first.
459 GDBusCapabilityFlags capabilities;
461 /* Protected by @init_lock */
462 GDBusAuthObserver *authentication_observer;
464 /* Read-only after initable_init(), so it may be read if you either
465 * hold @init_lock or check for initialization first.
467 GCredentials *credentials;
469 /* set to TRUE when finalizing */
473 typedef struct ExportedObject ExportedObject;
474 static void exported_object_free (ExportedObject *eo);
476 typedef struct ExportedSubtree ExportedSubtree;
477 static void exported_subtree_free (ExportedSubtree *es);
495 PROP_CAPABILITY_FLAGS,
496 PROP_AUTHENTICATION_OBSERVER,
499 static void distribute_signals (GDBusConnection *connection,
500 GDBusMessage *message);
502 static void distribute_method_call (GDBusConnection *connection,
503 GDBusMessage *message);
505 static gboolean handle_generic_unlocked (GDBusConnection *connection,
506 GDBusMessage *message);
509 static void purge_all_signal_subscriptions (GDBusConnection *connection);
510 static void purge_all_filters (GDBusConnection *connection);
512 static void schedule_method_call (GDBusConnection *connection,
513 GDBusMessage *message,
514 guint registration_id,
515 guint subtree_registration_id,
516 const GDBusInterfaceInfo *interface_info,
517 const GDBusMethodInfo *method_info,
518 const GDBusPropertyInfo *property_info,
519 GVariant *parameters,
520 const GDBusInterfaceVTable *vtable,
521 GMainContext *main_context,
524 #define _G_ENSURE_LOCK(name) do { \
525 if (G_UNLIKELY (G_TRYLOCK(name))) \
527 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
528 "_G_ENSURE_LOCK: Lock '" #name "' is not locked"); \
532 static guint signals[LAST_SIGNAL] = { 0 };
534 static void initable_iface_init (GInitableIface *initable_iface);
535 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
537 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
538 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
539 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
543 * Check that all members of @connection that can only be accessed after
544 * the connection is initialized can safely be accessed. If not,
545 * log a critical warning. This function is a memory barrier.
547 * Returns: %TRUE if initialized
550 check_initialized (GDBusConnection *connection)
552 /* The access to @atomic_flags isn't conditional, so that this function
553 * provides a memory barrier for thread-safety even if checks are disabled.
554 * (If you don't want this stricter guarantee, you can call
555 * g_return_if_fail (check_initialized (c)).)
557 * This isn't strictly necessary now that we've decided use of an
558 * uninitialized GDBusConnection is undefined behaviour, but it seems
559 * better to be as deterministic as is feasible.
561 * (Anything that could suffer a crash from seeing undefined values
562 * must have a race condition - thread A initializes the connection while
563 * thread B calls a method without initialization, hoping that thread A will
564 * win the race - so its behaviour is undefined anyway.)
566 gint flags = g_atomic_int_get (&connection->atomic_flags);
568 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
570 /* We can safely access this, due to the memory barrier above */
571 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
577 MAY_BE_UNINITIALIZED = (1<<1)
578 } CheckUnclosedFlags;
581 * Check the same thing as check_initialized(), and also that the
582 * connection is not closed. If the connection is uninitialized,
583 * raise a critical warning (it's programmer error); if it's closed,
584 * raise a recoverable GError (it's a runtime error).
586 * This function is a memory barrier.
588 * Returns: %TRUE if initialized and not closed
591 check_unclosed (GDBusConnection *connection,
592 CheckUnclosedFlags check,
595 /* check_initialized() is effectively inlined, so we don't waste time
596 * doing two memory barriers
598 gint flags = g_atomic_int_get (&connection->atomic_flags);
600 if (!(check & MAY_BE_UNINITIALIZED))
602 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
603 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
606 if (flags & FLAG_CLOSED)
608 g_set_error_literal (error,
611 _("The connection is closed"));
618 static GHashTable *alive_connections = NULL;
621 g_dbus_connection_dispose (GObject *object)
623 GDBusConnection *connection = G_DBUS_CONNECTION (object);
625 G_LOCK (message_bus_lock);
626 CONNECTION_LOCK (connection);
627 if (connection->worker != NULL)
629 _g_dbus_worker_stop (connection->worker);
630 connection->worker = NULL;
631 if (alive_connections != NULL)
632 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
636 if (alive_connections != NULL)
637 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
639 CONNECTION_UNLOCK (connection);
640 G_UNLOCK (message_bus_lock);
642 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
643 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
647 g_dbus_connection_finalize (GObject *object)
649 GDBusConnection *connection = G_DBUS_CONNECTION (object);
651 connection->finalizing = TRUE;
653 purge_all_signal_subscriptions (connection);
655 purge_all_filters (connection);
656 g_ptr_array_unref (connection->filters);
658 if (connection->authentication_observer != NULL)
659 g_object_unref (connection->authentication_observer);
661 if (connection->auth != NULL)
662 g_object_unref (connection->auth);
664 if (connection->credentials)
665 g_object_unref (connection->credentials);
667 if (connection->stream != NULL)
669 g_object_unref (connection->stream);
670 connection->stream = NULL;
673 g_free (connection->address);
675 g_free (connection->guid);
676 g_free (connection->bus_unique_name);
678 if (connection->initialization_error != NULL)
679 g_error_free (connection->initialization_error);
681 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
683 g_hash_table_unref (connection->map_rule_to_signal_data);
684 g_hash_table_unref (connection->map_id_to_signal_data);
685 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
687 g_hash_table_unref (connection->map_id_to_ei);
688 g_hash_table_unref (connection->map_object_path_to_eo);
689 g_hash_table_unref (connection->map_id_to_es);
690 g_hash_table_unref (connection->map_object_path_to_es);
692 g_hash_table_unref (connection->map_thread_to_last_serial);
694 g_main_context_unref (connection->main_context_at_construction);
696 g_free (connection->machine_id);
698 g_mutex_clear (&connection->init_lock);
699 g_mutex_clear (&connection->lock);
701 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
704 /* called in any user thread, with the connection's lock not held */
706 g_dbus_connection_get_property (GObject *object,
711 GDBusConnection *connection = G_DBUS_CONNECTION (object);
716 g_value_set_object (value, g_dbus_connection_get_stream (connection));
720 g_value_set_string (value, g_dbus_connection_get_guid (connection));
723 case PROP_UNIQUE_NAME:
724 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
728 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
731 case PROP_EXIT_ON_CLOSE:
732 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
735 case PROP_CAPABILITY_FLAGS:
736 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
740 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
745 /* called in any user thread, with the connection's lock not held */
747 g_dbus_connection_set_property (GObject *object,
752 GDBusConnection *connection = G_DBUS_CONNECTION (object);
757 connection->stream = g_value_dup_object (value);
761 connection->guid = g_value_dup_string (value);
765 connection->address = g_value_dup_string (value);
769 connection->flags = g_value_get_flags (value);
772 case PROP_EXIT_ON_CLOSE:
773 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
776 case PROP_AUTHENTICATION_OBSERVER:
777 connection->authentication_observer = g_value_dup_object (value);
781 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
786 /* Base-class implementation of GDBusConnection::closed.
788 * Called in a user thread, by the main context that was thread-default when
789 * the object was constructed.
792 g_dbus_connection_real_closed (GDBusConnection *connection,
793 gboolean remote_peer_vanished,
796 gint flags = g_atomic_int_get (&connection->atomic_flags);
798 /* Because atomic int access is a memory barrier, we can safely read
799 * initialization_error without a lock, as long as we do it afterwards.
801 if (remote_peer_vanished &&
802 (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
803 (flags & FLAG_INITIALIZED) != 0 &&
804 connection->initialization_error == NULL)
808 g_printerr ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
811 g_quark_to_string (error->domain), error->code);
815 g_printerr ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
822 g_dbus_connection_class_init (GDBusConnectionClass *klass)
824 GObjectClass *gobject_class;
826 gobject_class = G_OBJECT_CLASS (klass);
828 gobject_class->finalize = g_dbus_connection_finalize;
829 gobject_class->dispose = g_dbus_connection_dispose;
830 gobject_class->set_property = g_dbus_connection_set_property;
831 gobject_class->get_property = g_dbus_connection_get_property;
833 klass->closed = g_dbus_connection_real_closed;
836 * GDBusConnection:stream:
838 * The underlying #GIOStream used for I/O.
840 * If this is passed on construction and is a #GSocketConnection,
841 * then the corresponding #GSocket will be put into non-blocking mode.
843 * While the #GDBusConnection is active, it will interact with this
844 * stream from a worker thread, so it is not safe to interact with
845 * the stream directly.
849 g_object_class_install_property (gobject_class,
851 g_param_spec_object ("stream",
853 P_("The underlying streams used for I/O"),
857 G_PARAM_CONSTRUCT_ONLY |
858 G_PARAM_STATIC_NAME |
859 G_PARAM_STATIC_BLURB |
860 G_PARAM_STATIC_NICK));
863 * GDBusConnection:address:
865 * A D-Bus address specifying potential endpoints that can be used
866 * when establishing the connection.
870 g_object_class_install_property (gobject_class,
872 g_param_spec_string ("address",
874 P_("D-Bus address specifying potential socket endpoints"),
877 G_PARAM_CONSTRUCT_ONLY |
878 G_PARAM_STATIC_NAME |
879 G_PARAM_STATIC_BLURB |
880 G_PARAM_STATIC_NICK));
883 * GDBusConnection:flags:
885 * Flags from the #GDBusConnectionFlags enumeration.
889 g_object_class_install_property (gobject_class,
891 g_param_spec_flags ("flags",
894 G_TYPE_DBUS_CONNECTION_FLAGS,
895 G_DBUS_CONNECTION_FLAGS_NONE,
897 G_PARAM_CONSTRUCT_ONLY |
898 G_PARAM_STATIC_NAME |
899 G_PARAM_STATIC_BLURB |
900 G_PARAM_STATIC_NICK));
903 * GDBusConnection:guid:
905 * The GUID of the peer performing the role of server when
908 * If you are constructing a #GDBusConnection and pass
909 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
910 * #GDBusConnection:flags property then you MUST also set this
911 * property to a valid guid.
913 * If you are constructing a #GDBusConnection and pass
914 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
915 * #GDBusConnection:flags property you will be able to read the GUID
916 * of the other peer here after the connection has been successfully
921 g_object_class_install_property (gobject_class,
923 g_param_spec_string ("guid",
925 P_("GUID of the server peer"),
929 G_PARAM_CONSTRUCT_ONLY |
930 G_PARAM_STATIC_NAME |
931 G_PARAM_STATIC_BLURB |
932 G_PARAM_STATIC_NICK));
935 * GDBusConnection:unique-name:
937 * The unique name as assigned by the message bus or %NULL if the
938 * connection is not open or not a message bus connection.
942 g_object_class_install_property (gobject_class,
944 g_param_spec_string ("unique-name",
946 P_("Unique name of bus connection"),
949 G_PARAM_STATIC_NAME |
950 G_PARAM_STATIC_BLURB |
951 G_PARAM_STATIC_NICK));
954 * GDBusConnection:closed:
956 * A boolean specifying whether the connection has been closed.
960 g_object_class_install_property (gobject_class,
962 g_param_spec_boolean ("closed",
964 P_("Whether the connection is closed"),
967 G_PARAM_STATIC_NAME |
968 G_PARAM_STATIC_BLURB |
969 G_PARAM_STATIC_NICK));
972 * GDBusConnection:exit-on-close:
974 * A boolean specifying whether the process will be terminated (by
975 * calling `raise(SIGTERM)`) if the connection is closed by the
978 * Note that #GDBusConnection objects returned by g_bus_get_finish()
979 * and g_bus_get_sync() will (usually) have this property set to %TRUE.
983 g_object_class_install_property (gobject_class,
985 g_param_spec_boolean ("exit-on-close",
987 P_("Whether the process is terminated when the connection is closed"),
991 G_PARAM_STATIC_NAME |
992 G_PARAM_STATIC_BLURB |
993 G_PARAM_STATIC_NICK));
996 * GDBusConnection:capabilities:
998 * Flags from the #GDBusCapabilityFlags enumeration
999 * representing connection features negotiated with the other peer.
1003 g_object_class_install_property (gobject_class,
1004 PROP_CAPABILITY_FLAGS,
1005 g_param_spec_flags ("capabilities",
1008 G_TYPE_DBUS_CAPABILITY_FLAGS,
1009 G_DBUS_CAPABILITY_FLAGS_NONE,
1011 G_PARAM_STATIC_NAME |
1012 G_PARAM_STATIC_BLURB |
1013 G_PARAM_STATIC_NICK));
1016 * GDBusConnection:authentication-observer:
1018 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
1022 g_object_class_install_property (gobject_class,
1023 PROP_AUTHENTICATION_OBSERVER,
1024 g_param_spec_object ("authentication-observer",
1025 P_("Authentication Observer"),
1026 P_("Object used to assist in the authentication process"),
1027 G_TYPE_DBUS_AUTH_OBSERVER,
1029 G_PARAM_CONSTRUCT_ONLY |
1030 G_PARAM_STATIC_NAME |
1031 G_PARAM_STATIC_BLURB |
1032 G_PARAM_STATIC_NICK));
1035 * GDBusConnection::closed:
1036 * @connection: the #GDBusConnection emitting the signal
1037 * @remote_peer_vanished: %TRUE if @connection is closed because the
1038 * remote peer closed its end of the connection
1039 * @error: (allow-none): a #GError with more details about the event or %NULL
1041 * Emitted when the connection is closed.
1043 * The cause of this event can be
1045 * - If g_dbus_connection_close() is called. In this case
1046 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
1048 * - If the remote peer closes the connection. In this case
1049 * @remote_peer_vanished is set to %TRUE and @error is set.
1051 * - If the remote peer sends invalid or malformed data. In this
1052 * case @remote_peer_vanished is set to %FALSE and @error is set.
1054 * Upon receiving this signal, you should give up your reference to
1055 * @connection. You are guaranteed that this signal is emitted only
1060 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
1061 G_TYPE_DBUS_CONNECTION,
1063 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1074 g_dbus_connection_init (GDBusConnection *connection)
1076 g_mutex_init (&connection->lock);
1077 g_mutex_init (&connection->init_lock);
1079 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
1081 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1083 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1085 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1088 (GDestroyNotify) g_ptr_array_unref);
1090 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1093 (GDestroyNotify) exported_object_free);
1095 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1098 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1101 (GDestroyNotify) exported_subtree_free);
1103 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1106 connection->map_thread_to_last_serial = g_hash_table_new (g_direct_hash,
1109 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1111 connection->filters = g_ptr_array_new ();
1115 * g_dbus_connection_get_stream:
1116 * @connection: a #GDBusConnection
1118 * Gets the underlying stream used for IO.
1120 * While the #GDBusConnection is active, it will interact with this
1121 * stream from a worker thread, so it is not safe to interact with
1122 * the stream directly.
1124 * Returns: (transfer none): the stream used for IO
1129 g_dbus_connection_get_stream (GDBusConnection *connection)
1131 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1133 /* do not use g_return_val_if_fail(), we want the memory barrier */
1134 if (!check_initialized (connection))
1137 return connection->stream;
1141 * g_dbus_connection_start_message_processing:
1142 * @connection: a #GDBusConnection
1144 * If @connection was created with
1145 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1146 * starts processing messages. Does nothing on if @connection wasn't
1147 * created with this flag or if the method has already been called.
1152 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1154 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1156 /* do not use g_return_val_if_fail(), we want the memory barrier */
1157 if (!check_initialized (connection))
1160 g_assert (connection->worker != NULL);
1161 _g_dbus_worker_unfreeze (connection->worker);
1165 * g_dbus_connection_is_closed:
1166 * @connection: a #GDBusConnection
1168 * Gets whether @connection is closed.
1170 * Returns: %TRUE if the connection is closed, %FALSE otherwise
1175 g_dbus_connection_is_closed (GDBusConnection *connection)
1179 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1181 flags = g_atomic_int_get (&connection->atomic_flags);
1183 return (flags & FLAG_CLOSED) ? TRUE : FALSE;
1187 * g_dbus_connection_get_capabilities:
1188 * @connection: a #GDBusConnection
1190 * Gets the capabilities negotiated with the remote peer
1192 * Returns: zero or more flags from the #GDBusCapabilityFlags enumeration
1196 GDBusCapabilityFlags
1197 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1199 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1201 /* do not use g_return_val_if_fail(), we want the memory barrier */
1202 if (!check_initialized (connection))
1203 return G_DBUS_CAPABILITY_FLAGS_NONE;
1205 return connection->capabilities;
1208 /* ---------------------------------------------------------------------------------------------------- */
1210 /* Called in a temporary thread without holding locks. */
1212 flush_in_thread_func (GSimpleAsyncResult *res,
1214 GCancellable *cancellable)
1219 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1222 g_simple_async_result_take_error (res, error);
1226 * g_dbus_connection_flush:
1227 * @connection: a #GDBusConnection
1228 * @cancellable: (allow-none): a #GCancellable or %NULL
1229 * @callback: (allow-none): a #GAsyncReadyCallback to call when the
1230 * request is satisfied or %NULL if you don't care about the result
1231 * @user_data: The data to pass to @callback
1233 * Asynchronously flushes @connection, that is, writes all queued
1234 * outgoing message to the transport and then flushes the transport
1235 * (using g_output_stream_flush_async()). This is useful in programs
1236 * that wants to emit a D-Bus signal and then exit immediately. Without
1237 * flushing the connection, there is no guaranteed that the message has
1238 * been sent to the networking buffers in the OS kernel.
1240 * This is an asynchronous method. When the operation is finished,
1241 * @callback will be invoked in the
1242 * [thread-default main context][g-main-context-push-thread-default]
1243 * of the thread you are calling this method from. You can
1244 * then call g_dbus_connection_flush_finish() to get the result of the
1245 * operation. See g_dbus_connection_flush_sync() for the synchronous
1251 g_dbus_connection_flush (GDBusConnection *connection,
1252 GCancellable *cancellable,
1253 GAsyncReadyCallback callback,
1256 GSimpleAsyncResult *simple;
1258 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1260 simple = g_simple_async_result_new (G_OBJECT (connection),
1263 g_dbus_connection_flush);
1264 g_simple_async_result_set_check_cancellable (simple, cancellable);
1265 g_simple_async_result_run_in_thread (simple,
1266 flush_in_thread_func,
1269 g_object_unref (simple);
1273 * g_dbus_connection_flush_finish:
1274 * @connection: a #GDBusConnection
1275 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1276 * to g_dbus_connection_flush()
1277 * @error: return location for error or %NULL
1279 * Finishes an operation started with g_dbus_connection_flush().
1281 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1286 g_dbus_connection_flush_finish (GDBusConnection *connection,
1290 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1295 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1296 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1297 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1299 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1301 if (g_simple_async_result_propagate_error (simple, error))
1311 * g_dbus_connection_flush_sync:
1312 * @connection: a #GDBusConnection
1313 * @cancellable: (allow-none): a #GCancellable or %NULL
1314 * @error: return location for error or %NULL
1316 * Synchronously flushes @connection. The calling thread is blocked
1317 * until this is done. See g_dbus_connection_flush() for the
1318 * asynchronous version of this method and more details about what it
1321 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1326 g_dbus_connection_flush_sync (GDBusConnection *connection,
1327 GCancellable *cancellable,
1332 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1333 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1337 /* This is only a best-effort attempt to see whether the connection is
1338 * closed, so it doesn't need the lock. If the connection closes just
1339 * after this check, but before scheduling the flush operation, the
1340 * result will be more or less the same as if the connection closed while
1341 * the flush operation was pending - it'll fail with either CLOSED or
1344 if (!check_unclosed (connection, 0, error))
1347 g_assert (connection->worker != NULL);
1349 ret = _g_dbus_worker_flush_sync (connection->worker,
1357 /* ---------------------------------------------------------------------------------------------------- */
1361 GDBusConnection *connection;
1363 gboolean remote_peer_vanished;
1367 emit_closed_data_free (EmitClosedData *data)
1369 g_object_unref (data->connection);
1370 if (data->error != NULL)
1371 g_error_free (data->error);
1375 /* Called in a user thread that has acquired the main context that was
1376 * thread-default when the object was constructed
1379 emit_closed_in_idle (gpointer user_data)
1381 EmitClosedData *data = user_data;
1384 g_object_notify (G_OBJECT (data->connection), "closed");
1385 g_signal_emit (data->connection,
1386 signals[CLOSED_SIGNAL],
1388 data->remote_peer_vanished,
1394 /* Can be called from any thread, must hold lock.
1395 * FLAG_CLOSED must already have been set.
1398 schedule_closed_unlocked (GDBusConnection *connection,
1399 gboolean remote_peer_vanished,
1402 GSource *idle_source;
1403 EmitClosedData *data;
1405 CONNECTION_ENSURE_LOCK (connection);
1407 data = g_new0 (EmitClosedData, 1);
1408 data->connection = g_object_ref (connection);
1409 data->remote_peer_vanished = remote_peer_vanished;
1410 data->error = error != NULL ? g_error_copy (error) : NULL;
1412 idle_source = g_idle_source_new ();
1413 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1414 g_source_set_callback (idle_source,
1415 emit_closed_in_idle,
1417 (GDestroyNotify) emit_closed_data_free);
1418 g_source_attach (idle_source, connection->main_context_at_construction);
1419 g_source_unref (idle_source);
1422 /* ---------------------------------------------------------------------------------------------------- */
1425 * g_dbus_connection_close:
1426 * @connection: a #GDBusConnection
1427 * @cancellable: (allow-none): a #GCancellable or %NULL
1428 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request is
1429 * satisfied or %NULL if you don't care about the result
1430 * @user_data: The data to pass to @callback
1432 * Closes @connection. Note that this never causes the process to
1433 * exit (this might only happen if the other end of a shared message
1434 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1436 * Once the connection is closed, operations such as sending a message
1437 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1438 * will not automatically flush the connection so queued messages may
1439 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1441 * If @connection is already closed, this method fails with
1442 * %G_IO_ERROR_CLOSED.
1444 * When @connection has been closed, the #GDBusConnection::closed
1445 * signal is emitted in the
1446 * [thread-default main context][g-main-context-push-thread-default]
1447 * of the thread that @connection was constructed in.
1449 * This is an asynchronous method. When the operation is finished,
1450 * @callback will be invoked in the
1451 * [thread-default main context][g-main-context-push-thread-default]
1452 * of the thread you are calling this method from. You can
1453 * then call g_dbus_connection_close_finish() to get the result of the
1454 * operation. See g_dbus_connection_close_sync() for the synchronous
1460 g_dbus_connection_close (GDBusConnection *connection,
1461 GCancellable *cancellable,
1462 GAsyncReadyCallback callback,
1465 GSimpleAsyncResult *simple;
1467 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1469 /* do not use g_return_val_if_fail(), we want the memory barrier */
1470 if (!check_initialized (connection))
1473 g_assert (connection->worker != NULL);
1475 simple = g_simple_async_result_new (G_OBJECT (connection),
1478 g_dbus_connection_close);
1479 g_simple_async_result_set_check_cancellable (simple, cancellable);
1480 _g_dbus_worker_close (connection->worker, cancellable, simple);
1481 g_object_unref (simple);
1485 * g_dbus_connection_close_finish:
1486 * @connection: a #GDBusConnection
1487 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1488 * to g_dbus_connection_close()
1489 * @error: return location for error or %NULL
1491 * Finishes an operation started with g_dbus_connection_close().
1493 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1498 g_dbus_connection_close_finish (GDBusConnection *connection,
1502 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1507 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1508 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1509 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1511 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1513 if (g_simple_async_result_propagate_error (simple, error))
1524 GAsyncResult *result;
1527 /* Can be called by any thread, without the connection lock */
1529 sync_close_cb (GObject *source_object,
1533 SyncCloseData *data = user_data;
1535 data->result = g_object_ref (res);
1536 g_main_loop_quit (data->loop);
1540 * g_dbus_connection_close_sync:
1541 * @connection: a #GDBusConnection
1542 * @cancellable: (allow-none): a #GCancellable or %NULL
1543 * @error: return location for error or %NULL
1545 * Synchronously closees @connection. The calling thread is blocked
1546 * until this is done. See g_dbus_connection_close() for the
1547 * asynchronous version of this method and more details about what it
1550 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1555 g_dbus_connection_close_sync (GDBusConnection *connection,
1556 GCancellable *cancellable,
1561 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1562 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1566 if (check_unclosed (connection, 0, error))
1568 GMainContext *context;
1571 context = g_main_context_new ();
1572 g_main_context_push_thread_default (context);
1573 data.loop = g_main_loop_new (context, TRUE);
1576 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1577 g_main_loop_run (data.loop);
1578 ret = g_dbus_connection_close_finish (connection, data.result, error);
1580 g_object_unref (data.result);
1581 g_main_loop_unref (data.loop);
1582 g_main_context_pop_thread_default (context);
1583 g_main_context_unref (context);
1589 /* ---------------------------------------------------------------------------------------------------- */
1592 * g_dbus_connection_get_last_serial:
1593 * @connection: a #GDBusConnection
1595 * Retrieves the last serial number assigned to a #GDBusMessage on
1596 * the current thread. This includes messages sent via both low-level
1597 * API such as g_dbus_connection_send_message() as well as
1598 * high-level API such as g_dbus_connection_emit_signal(),
1599 * g_dbus_connection_call() or g_dbus_proxy_call().
1601 * Returns: the last used serial or zero when no message has been sent
1602 * within the current thread
1607 g_dbus_connection_get_last_serial (GDBusConnection *connection)
1611 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
1613 CONNECTION_LOCK (connection);
1614 ret = GPOINTER_TO_UINT (g_hash_table_lookup (connection->map_thread_to_last_serial,
1616 CONNECTION_UNLOCK (connection);
1621 /* ---------------------------------------------------------------------------------------------------- */
1623 /* Can be called by any thread, with the connection lock held */
1625 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1626 GDBusMessage *message,
1627 GDBusSendMessageFlags flags,
1628 volatile guint32 *out_serial,
1633 guint32 serial_to_use;
1636 CONNECTION_ENSURE_LOCK (connection);
1638 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1639 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1641 /* TODO: check all necessary headers are present */
1646 if (out_serial != NULL)
1649 /* If we're in initable_init(), don't check for being initialized, to avoid
1650 * chicken-and-egg problems. initable_init() is responsible for setting up
1651 * our prerequisites (mainly connection->worker), and only calling us
1652 * from its own thread (so no memory barrier is needed).
1654 if (!check_unclosed (connection,
1655 (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
1659 blob = g_dbus_message_to_blob (message,
1661 connection->capabilities,
1666 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1667 serial_to_use = g_dbus_message_get_serial (message);
1669 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1674 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1677 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1680 g_assert_not_reached ();
1685 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1686 blob_size, serial_to_use, connection);
1687 g_printerr ("----\n");
1688 hexdump (blob, blob_size);
1689 g_printerr ("----\n");
1692 /* TODO: use connection->auth to encode the blob */
1694 if (out_serial != NULL)
1695 *out_serial = serial_to_use;
1697 /* store used serial for the current thread */
1698 /* TODO: watch the thread disposal and remove associated record
1700 * - see https://bugzilla.gnome.org/show_bug.cgi?id=676825#c7
1702 g_hash_table_replace (connection->map_thread_to_last_serial,
1704 GUINT_TO_POINTER (serial_to_use));
1706 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
1707 g_dbus_message_set_serial (message, serial_to_use);
1709 g_dbus_message_lock (message);
1710 _g_dbus_worker_send_message (connection->worker,
1714 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1725 * g_dbus_connection_send_message:
1726 * @connection: a #GDBusConnection
1727 * @message: a #GDBusMessage
1728 * @flags: flags affecting how the message is sent
1729 * @out_serial: (out) (allow-none): return location for serial number assigned
1730 * to @message when sending it or %NULL
1731 * @error: Return location for error or %NULL
1733 * Asynchronously sends @message to the peer represented by @connection.
1735 * Unless @flags contain the
1736 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1737 * will be assigned by @connection and set on @message via
1738 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1739 * serial number used will be written to this location prior to
1740 * submitting the message to the underlying transport.
1742 * If @connection is closed then the operation will fail with
1743 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1744 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1746 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
1747 * for an example of how to use this low-level API to send and receive
1748 * UNIX file descriptors.
1750 * Note that @message must be unlocked, unless @flags contain the
1751 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1753 * Returns: %TRUE if the message was well-formed and queued for
1754 * transmission, %FALSE if @error is set
1759 g_dbus_connection_send_message (GDBusConnection *connection,
1760 GDBusMessage *message,
1761 GDBusSendMessageFlags flags,
1762 volatile guint32 *out_serial,
1767 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1768 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1769 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1770 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1772 CONNECTION_LOCK (connection);
1773 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1774 CONNECTION_UNLOCK (connection);
1778 /* ---------------------------------------------------------------------------------------------------- */
1782 volatile gint ref_count;
1783 GDBusConnection *connection;
1785 GSimpleAsyncResult *simple;
1787 GMainContext *main_context;
1789 GCancellable *cancellable;
1791 gulong cancellable_handler_id;
1793 GSource *timeout_source;
1798 /* Can be called from any thread with or without lock held */
1799 static SendMessageData *
1800 send_message_data_ref (SendMessageData *data)
1802 g_atomic_int_inc (&data->ref_count);
1806 /* Can be called from any thread with or without lock held */
1808 send_message_data_unref (SendMessageData *data)
1810 if (g_atomic_int_dec_and_test (&data->ref_count))
1812 g_assert (data->timeout_source == NULL);
1813 g_assert (data->simple == NULL);
1814 g_assert (data->cancellable_handler_id == 0);
1815 g_object_unref (data->connection);
1816 if (data->cancellable != NULL)
1817 g_object_unref (data->cancellable);
1818 g_main_context_unref (data->main_context);
1823 /* ---------------------------------------------------------------------------------------------------- */
1825 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1827 send_message_with_reply_deliver (SendMessageData *data, gboolean remove)
1829 CONNECTION_ENSURE_LOCK (data->connection);
1831 g_assert (!data->delivered);
1833 data->delivered = TRUE;
1835 g_simple_async_result_complete_in_idle (data->simple);
1836 g_object_unref (data->simple);
1837 data->simple = NULL;
1839 if (data->timeout_source != NULL)
1841 g_source_destroy (data->timeout_source);
1842 data->timeout_source = NULL;
1844 if (data->cancellable_handler_id > 0)
1846 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1847 data->cancellable_handler_id = 0;
1852 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
1853 GUINT_TO_POINTER (data->serial)));
1856 send_message_data_unref (data);
1859 /* ---------------------------------------------------------------------------------------------------- */
1861 /* Can be called from any thread with lock held */
1863 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1864 GDBusMessage *reply)
1866 if (data->delivered)
1869 g_simple_async_result_set_op_res_gpointer (data->simple,
1870 g_object_ref (reply),
1873 send_message_with_reply_deliver (data, TRUE);
1879 /* ---------------------------------------------------------------------------------------------------- */
1881 /* Called from a user thread, lock is not held */
1883 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1885 SendMessageData *data = user_data;
1887 CONNECTION_LOCK (data->connection);
1888 if (data->delivered)
1891 g_simple_async_result_set_error (data->simple,
1893 G_IO_ERROR_CANCELLED,
1894 _("Operation was cancelled"));
1896 send_message_with_reply_deliver (data, TRUE);
1899 CONNECTION_UNLOCK (data->connection);
1903 /* Can be called from any thread with or without lock held */
1905 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1908 SendMessageData *data = user_data;
1909 GSource *idle_source;
1911 /* postpone cancellation to idle handler since we may be called directly
1912 * via g_cancellable_connect() (e.g. holding lock)
1914 idle_source = g_idle_source_new ();
1915 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1916 g_source_set_callback (idle_source,
1917 send_message_with_reply_cancelled_idle_cb,
1918 send_message_data_ref (data),
1919 (GDestroyNotify) send_message_data_unref);
1920 g_source_attach (idle_source, data->main_context);
1921 g_source_unref (idle_source);
1924 /* ---------------------------------------------------------------------------------------------------- */
1926 /* Called from a user thread, lock is not held */
1928 send_message_with_reply_timeout_cb (gpointer user_data)
1930 SendMessageData *data = user_data;
1932 CONNECTION_LOCK (data->connection);
1933 if (data->delivered)
1936 g_simple_async_result_set_error (data->simple,
1938 G_IO_ERROR_TIMED_OUT,
1939 _("Timeout was reached"));
1941 send_message_with_reply_deliver (data, TRUE);
1944 CONNECTION_UNLOCK (data->connection);
1949 /* ---------------------------------------------------------------------------------------------------- */
1951 /* Called from a user thread, connection's lock is held */
1953 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1954 GDBusMessage *message,
1955 GDBusSendMessageFlags flags,
1957 volatile guint32 *out_serial,
1958 GCancellable *cancellable,
1959 GAsyncReadyCallback callback,
1962 GSimpleAsyncResult *simple;
1963 SendMessageData *data;
1965 volatile guint32 serial;
1969 if (out_serial == NULL)
1970 out_serial = &serial;
1972 if (timeout_msec == -1)
1973 timeout_msec = 25 * 1000;
1975 simple = g_simple_async_result_new (G_OBJECT (connection),
1978 g_dbus_connection_send_message_with_reply);
1979 g_simple_async_result_set_check_cancellable (simple, cancellable);
1981 if (g_cancellable_is_cancelled (cancellable))
1983 g_simple_async_result_set_error (simple,
1985 G_IO_ERROR_CANCELLED,
1986 _("Operation was cancelled"));
1987 g_simple_async_result_complete_in_idle (simple);
1988 g_object_unref (simple);
1993 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1995 g_simple_async_result_take_error (simple, error);
1996 g_simple_async_result_complete_in_idle (simple);
1997 g_object_unref (simple);
2001 data = g_new0 (SendMessageData, 1);
2002 data->ref_count = 1;
2003 data->connection = g_object_ref (connection);
2004 data->simple = simple;
2005 data->serial = *out_serial;
2006 data->main_context = g_main_context_ref_thread_default ();
2008 if (cancellable != NULL)
2010 data->cancellable = g_object_ref (cancellable);
2011 data->cancellable_handler_id = g_cancellable_connect (cancellable,
2012 G_CALLBACK (send_message_with_reply_cancelled_cb),
2013 send_message_data_ref (data),
2014 (GDestroyNotify) send_message_data_unref);
2017 if (timeout_msec != G_MAXINT)
2019 data->timeout_source = g_timeout_source_new (timeout_msec);
2020 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
2021 g_source_set_callback (data->timeout_source,
2022 send_message_with_reply_timeout_cb,
2023 send_message_data_ref (data),
2024 (GDestroyNotify) send_message_data_unref);
2025 g_source_attach (data->timeout_source, data->main_context);
2026 g_source_unref (data->timeout_source);
2029 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
2030 GUINT_TO_POINTER (*out_serial),
2038 * g_dbus_connection_send_message_with_reply:
2039 * @connection: a #GDBusConnection
2040 * @message: a #GDBusMessage
2041 * @flags: flags affecting how the message is sent
2042 * @timeout_msec: the timeout in milliseconds, -1 to use the default
2043 * timeout or %G_MAXINT for no timeout
2044 * @out_serial: (out) (allow-none): return location for serial number assigned
2045 * to @message when sending it or %NULL
2046 * @cancellable: (allow-none): a #GCancellable or %NULL
2047 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request
2048 * is satisfied or %NULL if you don't care about the result
2049 * @user_data: The data to pass to @callback
2051 * Asynchronously sends @message to the peer represented by @connection.
2053 * Unless @flags contain the
2054 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2055 * will be assigned by @connection and set on @message via
2056 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2057 * serial number used will be written to this location prior to
2058 * submitting the message to the underlying transport.
2060 * If @connection is closed then the operation will fail with
2061 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2062 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2063 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2065 * This is an asynchronous method. When the operation is finished, @callback
2066 * will be invoked in the
2067 * [thread-default main context][g-main-context-push-thread-default]
2068 * of the thread you are calling this method from. You can then call
2069 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
2070 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
2072 * Note that @message must be unlocked, unless @flags contain the
2073 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2075 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2076 * for an example of how to use this low-level API to send and receive
2077 * UNIX file descriptors.
2082 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
2083 GDBusMessage *message,
2084 GDBusSendMessageFlags flags,
2086 volatile guint32 *out_serial,
2087 GCancellable *cancellable,
2088 GAsyncReadyCallback callback,
2091 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2092 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2093 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2094 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2096 CONNECTION_LOCK (connection);
2097 g_dbus_connection_send_message_with_reply_unlocked (connection,
2105 CONNECTION_UNLOCK (connection);
2109 * g_dbus_connection_send_message_with_reply_finish:
2110 * @connection: a #GDBusConnection
2111 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
2112 * g_dbus_connection_send_message_with_reply()
2113 * @error: teturn location for error or %NULL
2115 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2117 * Note that @error is only set if a local in-process error
2118 * occurred. That is to say that the returned #GDBusMessage object may
2119 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2120 * g_dbus_message_to_gerror() to transcode this to a #GError.
2122 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2123 * for an example of how to use this low-level API to send and receive
2124 * UNIX file descriptors.
2126 * Returns: (transfer full): a locked #GDBusMessage or %NULL if @error is set
2131 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2135 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2136 GDBusMessage *reply;
2138 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2139 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2143 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
2145 if (g_simple_async_result_propagate_error (simple, error))
2148 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
2154 /* ---------------------------------------------------------------------------------------------------- */
2159 GMainContext *context;
2161 } SendMessageSyncData;
2163 /* Called from a user thread, lock is not held */
2165 send_message_with_reply_sync_cb (GDBusConnection *connection,
2169 SendMessageSyncData *data = user_data;
2170 data->res = g_object_ref (res);
2171 g_main_loop_quit (data->loop);
2175 * g_dbus_connection_send_message_with_reply_sync:
2176 * @connection: a #GDBusConnection
2177 * @message: a #GDBusMessage
2178 * @flags: flags affecting how the message is sent.
2179 * @timeout_msec: the timeout in milliseconds, -1 to use the default
2180 * timeout or %G_MAXINT for no timeout
2181 * @out_serial: (out) (allow-none): return location for serial number
2182 * assigned to @message when sending it or %NULL
2183 * @cancellable: (allow-none): a #GCancellable or %NULL
2184 * @error: return location for error or %NULL
2186 * Synchronously sends @message to the peer represented by @connection
2187 * and blocks the calling thread until a reply is received or the
2188 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2189 * for the asynchronous version of this method.
2191 * Unless @flags contain the
2192 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2193 * will be assigned by @connection and set on @message via
2194 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2195 * serial number used will be written to this location prior to
2196 * submitting the message to the underlying transport.
2198 * If @connection is closed then the operation will fail with
2199 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2200 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2201 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2203 * Note that @error is only set if a local in-process error
2204 * occurred. That is to say that the returned #GDBusMessage object may
2205 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2206 * g_dbus_message_to_gerror() to transcode this to a #GError.
2208 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2209 * for an example of how to use this low-level API to send and receive
2210 * UNIX file descriptors.
2212 * Note that @message must be unlocked, unless @flags contain the
2213 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2215 * Returns: (transfer full): a locked #GDBusMessage that is the reply
2216 * to @message or %NULL if @error is set
2221 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2222 GDBusMessage *message,
2223 GDBusSendMessageFlags flags,
2225 volatile guint32 *out_serial,
2226 GCancellable *cancellable,
2229 SendMessageSyncData *data;
2230 GDBusMessage *reply;
2232 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2233 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2234 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2235 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2236 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2238 data = g_new0 (SendMessageSyncData, 1);
2239 data->context = g_main_context_new ();
2240 data->loop = g_main_loop_new (data->context, FALSE);
2242 g_main_context_push_thread_default (data->context);
2244 g_dbus_connection_send_message_with_reply (connection,
2250 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2252 g_main_loop_run (data->loop);
2253 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2257 g_main_context_pop_thread_default (data->context);
2259 g_main_context_unref (data->context);
2260 g_main_loop_unref (data->loop);
2261 g_object_unref (data->res);
2267 /* ---------------------------------------------------------------------------------------------------- */
2271 GDBusMessageFilterFunction func;
2278 GDBusMessageFilterFunction filter_function;
2280 GDestroyNotify user_data_free_func;
2283 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2285 on_worker_message_received (GDBusWorker *worker,
2286 GDBusMessage *message,
2289 GDBusConnection *connection;
2290 FilterCallback *filters;
2295 G_LOCK (message_bus_lock);
2296 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2299 G_UNLOCK (message_bus_lock);
2302 connection = G_DBUS_CONNECTION (user_data);
2303 g_object_ref (connection);
2304 G_UNLOCK (message_bus_lock);
2306 //g_debug ("in on_worker_message_received");
2308 g_object_ref (message);
2309 g_dbus_message_lock (message);
2311 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2313 /* First collect the set of callback functions */
2314 CONNECTION_LOCK (connection);
2315 num_filters = connection->filters->len;
2316 filters = g_new0 (FilterCallback, num_filters);
2317 for (n = 0; n < num_filters; n++)
2319 FilterData *data = connection->filters->pdata[n];
2320 filters[n].func = data->filter_function;
2321 filters[n].user_data = data->user_data;
2323 CONNECTION_UNLOCK (connection);
2325 /* then call the filters in order (without holding the lock) */
2326 for (n = 0; n < num_filters; n++)
2328 message = filters[n].func (connection,
2331 filters[n].user_data);
2332 if (message == NULL)
2334 g_dbus_message_lock (message);
2337 /* Standard dispatch unless the filter ate the message - no need to
2338 * do anything if the message was altered
2340 if (message != NULL)
2342 GDBusMessageType message_type;
2344 message_type = g_dbus_message_get_message_type (message);
2345 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2347 guint32 reply_serial;
2348 SendMessageData *send_message_data;
2350 reply_serial = g_dbus_message_get_reply_serial (message);
2351 CONNECTION_LOCK (connection);
2352 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2353 GUINT_TO_POINTER (reply_serial));
2354 if (send_message_data != NULL)
2356 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2357 send_message_data_deliver_reply_unlocked (send_message_data, message);
2361 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2363 CONNECTION_UNLOCK (connection);
2365 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2367 CONNECTION_LOCK (connection);
2368 distribute_signals (connection, message);
2369 CONNECTION_UNLOCK (connection);
2371 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2373 CONNECTION_LOCK (connection);
2374 distribute_method_call (connection, message);
2375 CONNECTION_UNLOCK (connection);
2379 if (message != NULL)
2380 g_object_unref (message);
2381 g_object_unref (connection);
2385 /* Called in GDBusWorker's thread, lock is not held */
2386 static GDBusMessage *
2387 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2388 GDBusMessage *message,
2391 GDBusConnection *connection;
2392 FilterCallback *filters;
2397 G_LOCK (message_bus_lock);
2398 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2401 G_UNLOCK (message_bus_lock);
2404 connection = G_DBUS_CONNECTION (user_data);
2405 g_object_ref (connection);
2406 G_UNLOCK (message_bus_lock);
2408 //g_debug ("in on_worker_message_about_to_be_sent");
2410 /* First collect the set of callback functions */
2411 CONNECTION_LOCK (connection);
2412 num_filters = connection->filters->len;
2413 filters = g_new0 (FilterCallback, num_filters);
2414 for (n = 0; n < num_filters; n++)
2416 FilterData *data = connection->filters->pdata[n];
2417 filters[n].func = data->filter_function;
2418 filters[n].user_data = data->user_data;
2420 CONNECTION_UNLOCK (connection);
2422 /* then call the filters in order (without holding the lock) */
2423 for (n = 0; n < num_filters; n++)
2425 g_dbus_message_lock (message);
2426 message = filters[n].func (connection,
2429 filters[n].user_data);
2430 if (message == NULL)
2434 g_object_unref (connection);
2440 /* called with connection lock held, in GDBusWorker thread */
2442 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2444 SendMessageData *data = value;
2446 if (data->delivered)
2449 g_simple_async_result_set_error (data->simple,
2452 _("The connection is closed"));
2454 /* Ask send_message_with_reply_deliver not to remove the element from the
2455 * hash table - we're in the middle of a foreach; that would be unsafe.
2456 * Instead, return TRUE from this function so that it gets removed safely.
2458 send_message_with_reply_deliver (data, FALSE);
2462 /* Called in GDBusWorker's thread - we must not block - without lock held */
2464 on_worker_closed (GDBusWorker *worker,
2465 gboolean remote_peer_vanished,
2469 GDBusConnection *connection;
2471 guint old_atomic_flags;
2473 G_LOCK (message_bus_lock);
2474 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2477 G_UNLOCK (message_bus_lock);
2480 connection = G_DBUS_CONNECTION (user_data);
2481 g_object_ref (connection);
2482 G_UNLOCK (message_bus_lock);
2484 //g_debug ("in on_worker_closed: %s", error->message);
2486 CONNECTION_LOCK (connection);
2487 /* Even though this is atomic, we do it inside the lock to avoid breaking
2488 * assumptions in remove_match_rule(). We'd need the lock in a moment
2489 * anyway, so, no loss.
2491 old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
2493 if (!(old_atomic_flags & FLAG_CLOSED))
2495 g_hash_table_foreach_remove (connection->map_method_serial_to_send_message_data, cancel_method_on_close, NULL);
2496 schedule_closed_unlocked (connection, remote_peer_vanished, error);
2498 CONNECTION_UNLOCK (connection);
2500 g_object_unref (connection);
2503 /* ---------------------------------------------------------------------------------------------------- */
2505 /* Determines the biggest set of capabilities we can support on this
2508 * Called with the init_lock held.
2510 static GDBusCapabilityFlags
2511 get_offered_capabilities_max (GDBusConnection *connection)
2513 GDBusCapabilityFlags ret;
2514 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2516 if (G_IS_UNIX_CONNECTION (connection->stream))
2517 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2522 /* Called in a user thread, lock is not held */
2524 initable_init (GInitable *initable,
2525 GCancellable *cancellable,
2528 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2531 /* This method needs to be idempotent to work with the singleton
2532 * pattern. See the docs for g_initable_init(). We implement this by
2535 * Unfortunately we can't use the main lock since the on_worker_*()
2536 * callbacks above needs the lock during initialization (for message
2537 * bus connections we do a synchronous Hello() call on the bus).
2539 g_mutex_lock (&connection->init_lock);
2543 /* Make this a no-op if we're already initialized (successfully or
2546 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
2548 ret = (connection->initialization_error == NULL);
2552 /* Because of init_lock, we can't get here twice in different threads */
2553 g_assert (connection->initialization_error == NULL);
2555 /* The user can pass multiple (but mutally exclusive) construct
2558 * - stream (of type GIOStream)
2559 * - address (of type gchar*)
2561 * At the end of the day we end up with a non-NULL GIOStream
2562 * object in connection->stream.
2564 if (connection->address != NULL)
2566 g_assert (connection->stream == NULL);
2568 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2569 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2571 g_set_error_literal (&connection->initialization_error,
2573 G_IO_ERROR_INVALID_ARGUMENT,
2574 _("Unsupported flags encountered when constructing a client-side connection"));
2578 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2579 NULL, /* TODO: out_guid */
2581 &connection->initialization_error);
2582 if (connection->stream == NULL)
2585 else if (connection->stream != NULL)
2591 g_assert_not_reached ();
2594 /* Authenticate the connection */
2595 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2597 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2598 g_assert (connection->guid != NULL);
2599 connection->auth = _g_dbus_auth_new (connection->stream);
2600 if (!_g_dbus_auth_run_server (connection->auth,
2601 connection->authentication_observer,
2603 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2604 get_offered_capabilities_max (connection),
2605 &connection->capabilities,
2606 &connection->credentials,
2608 &connection->initialization_error))
2611 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2613 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2614 g_assert (connection->guid == NULL);
2615 connection->auth = _g_dbus_auth_new (connection->stream);
2616 connection->guid = _g_dbus_auth_run_client (connection->auth,
2617 connection->authentication_observer,
2618 get_offered_capabilities_max (connection),
2619 &connection->capabilities,
2621 &connection->initialization_error);
2622 if (connection->guid == NULL)
2626 if (connection->authentication_observer != NULL)
2628 g_object_unref (connection->authentication_observer);
2629 connection->authentication_observer = NULL;
2632 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2634 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2637 /* We want all IO operations to be non-blocking since they happen in
2638 * the worker thread which is shared by _all_ connections.
2640 if (G_IS_SOCKET_CONNECTION (connection->stream))
2642 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2646 G_LOCK (message_bus_lock);
2647 if (alive_connections == NULL)
2648 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2649 g_hash_table_insert (alive_connections, connection, connection);
2650 G_UNLOCK (message_bus_lock);
2652 connection->worker = _g_dbus_worker_new (connection->stream,
2653 connection->capabilities,
2654 ((connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) != 0),
2655 on_worker_message_received,
2656 on_worker_message_about_to_be_sent,
2660 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2661 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2663 GVariant *hello_result;
2665 /* we could lift this restriction by adding code in gdbusprivate.c */
2666 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2668 g_set_error_literal (&connection->initialization_error,
2671 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2675 hello_result = g_dbus_connection_call_sync (connection,
2676 "org.freedesktop.DBus", /* name */
2677 "/org/freedesktop/DBus", /* path */
2678 "org.freedesktop.DBus", /* interface */
2680 NULL, /* parameters */
2681 G_VARIANT_TYPE ("(s)"),
2682 CALL_FLAGS_INITIALIZING,
2684 NULL, /* TODO: cancellable */
2685 &connection->initialization_error);
2686 if (hello_result == NULL)
2689 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2690 g_variant_unref (hello_result);
2691 //g_debug ("unique name is '%s'", connection->bus_unique_name);
2698 g_assert (connection->initialization_error != NULL);
2699 g_propagate_error (error, g_error_copy (connection->initialization_error));
2702 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
2703 g_mutex_unlock (&connection->init_lock);
2709 initable_iface_init (GInitableIface *initable_iface)
2711 initable_iface->init = initable_init;
2714 /* ---------------------------------------------------------------------------------------------------- */
2717 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2722 /* ---------------------------------------------------------------------------------------------------- */
2725 * g_dbus_connection_new:
2726 * @stream: a #GIOStream
2727 * @guid: (allow-none): the GUID to use if a authenticating as a server or %NULL
2728 * @flags: flags describing how to make the connection
2729 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
2730 * @cancellable: (allow-none): a #GCancellable or %NULL
2731 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
2732 * @user_data: the data to pass to @callback
2734 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2735 * with the end represented by @stream.
2737 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2738 * will be put into non-blocking mode.
2740 * The D-Bus connection will interact with @stream from a worker thread.
2741 * As a result, the caller should not interact with @stream after this
2742 * method has been called, except by calling g_object_unref() on it.
2744 * If @observer is not %NULL it may be used to control the
2745 * authentication process.
2747 * When the operation is finished, @callback will be invoked. You can
2748 * then call g_dbus_connection_new_finish() to get the result of the
2751 * This is a asynchronous failable constructor. See
2752 * g_dbus_connection_new_sync() for the synchronous
2758 g_dbus_connection_new (GIOStream *stream,
2760 GDBusConnectionFlags flags,
2761 GDBusAuthObserver *observer,
2762 GCancellable *cancellable,
2763 GAsyncReadyCallback callback,
2766 g_return_if_fail (G_IS_IO_STREAM (stream));
2767 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2775 "authentication-observer", observer,
2780 * g_dbus_connection_new_finish:
2781 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback
2782 * passed to g_dbus_connection_new().
2783 * @error: return location for error or %NULL
2785 * Finishes an operation started with g_dbus_connection_new().
2787 * Returns: a #GDBusConnection or %NULL if @error is set. Free
2788 * with g_object_unref().
2793 g_dbus_connection_new_finish (GAsyncResult *res,
2797 GObject *source_object;
2799 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2800 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2802 source_object = g_async_result_get_source_object (res);
2803 g_assert (source_object != NULL);
2804 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2807 g_object_unref (source_object);
2809 return G_DBUS_CONNECTION (object);
2815 * g_dbus_connection_new_sync:
2816 * @stream: a #GIOStream
2817 * @guid: (allow-none): the GUID to use if a authenticating as a server or %NULL
2818 * @flags: flags describing how to make the connection
2819 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
2820 * @cancellable: (allow-none): a #GCancellable or %NULL
2821 * @error: return location for error or %NULL
2823 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2824 * with the end represented by @stream.
2826 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2827 * will be put into non-blocking mode.
2829 * The D-Bus connection will interact with @stream from a worker thread.
2830 * As a result, the caller should not interact with @stream after this
2831 * method has been called, except by calling g_object_unref() on it.
2833 * If @observer is not %NULL it may be used to control the
2834 * authentication process.
2836 * This is a synchronous failable constructor. See
2837 * g_dbus_connection_new() for the asynchronous version.
2839 * Returns: a #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2844 g_dbus_connection_new_sync (GIOStream *stream,
2846 GDBusConnectionFlags flags,
2847 GDBusAuthObserver *observer,
2848 GCancellable *cancellable,
2851 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2852 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2853 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2859 "authentication-observer", observer,
2863 /* ---------------------------------------------------------------------------------------------------- */
2866 * g_dbus_connection_new_for_address:
2867 * @address: a D-Bus address
2868 * @flags: flags describing how to make the connection
2869 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
2870 * @cancellable: (allow-none): a #GCancellable or %NULL
2871 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
2872 * @user_data: the data to pass to @callback
2874 * Asynchronously connects and sets up a D-Bus client connection for
2875 * exchanging D-Bus messages with an endpoint specified by @address
2876 * which must be in the D-Bus address format.
2878 * This constructor can only be used to initiate client-side
2879 * connections - use g_dbus_connection_new() if you need to act as the
2880 * server. In particular, @flags cannot contain the
2881 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2882 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2884 * When the operation is finished, @callback will be invoked. You can
2885 * then call g_dbus_connection_new_finish() to get the result of the
2888 * If @observer is not %NULL it may be used to control the
2889 * authentication process.
2891 * This is a asynchronous failable constructor. See
2892 * g_dbus_connection_new_for_address_sync() for the synchronous
2898 g_dbus_connection_new_for_address (const gchar *address,
2899 GDBusConnectionFlags flags,
2900 GDBusAuthObserver *observer,
2901 GCancellable *cancellable,
2902 GAsyncReadyCallback callback,
2905 g_return_if_fail (address != NULL);
2906 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2913 "authentication-observer", observer,
2918 * g_dbus_connection_new_for_address_finish:
2919 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
2920 * to g_dbus_connection_new()
2921 * @error: return location for error or %NULL
2923 * Finishes an operation started with g_dbus_connection_new_for_address().
2925 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
2931 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2935 GObject *source_object;
2937 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2938 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2940 source_object = g_async_result_get_source_object (res);
2941 g_assert (source_object != NULL);
2942 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2945 g_object_unref (source_object);
2947 return G_DBUS_CONNECTION (object);
2953 * g_dbus_connection_new_for_address_sync:
2954 * @address: a D-Bus address
2955 * @flags: flags describing how to make the connection
2956 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
2957 * @cancellable: (allow-none): a #GCancellable or %NULL
2958 * @error: return location for error or %NULL
2960 * Synchronously connects and sets up a D-Bus client connection for
2961 * exchanging D-Bus messages with an endpoint specified by @address
2962 * which must be in the D-Bus address format.
2964 * This constructor can only be used to initiate client-side
2965 * connections - use g_dbus_connection_new_sync() if you need to act
2966 * as the server. In particular, @flags cannot contain the
2967 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2968 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2970 * This is a synchronous failable constructor. See
2971 * g_dbus_connection_new_for_address() for the asynchronous version.
2973 * If @observer is not %NULL it may be used to control the
2974 * authentication process.
2976 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
2982 g_dbus_connection_new_for_address_sync (const gchar *address,
2983 GDBusConnectionFlags flags,
2984 GDBusAuthObserver *observer,
2985 GCancellable *cancellable,
2988 g_return_val_if_fail (address != NULL, NULL);
2989 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2990 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2995 "authentication-observer", observer,
2999 /* ---------------------------------------------------------------------------------------------------- */
3002 * g_dbus_connection_set_exit_on_close:
3003 * @connection: a #GDBusConnection
3004 * @exit_on_close: whether the process should be terminated
3005 * when @connection is closed by the remote peer
3007 * Sets whether the process should be terminated when @connection is
3008 * closed by the remote peer. See #GDBusConnection:exit-on-close for
3011 * Note that this function should be used with care. Most modern UNIX
3012 * desktops tie the notion of a user session the session bus, and expect
3013 * all of a users applications to quit when their bus connection goes away.
3014 * If you are setting @exit_on_close to %FALSE for the shared session
3015 * bus connection, you should make sure that your application exits
3016 * when the user session ends.
3021 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
3022 gboolean exit_on_close)
3024 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3027 g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
3029 g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
3034 * g_dbus_connection_get_exit_on_close:
3035 * @connection: a #GDBusConnection
3037 * Gets whether the process is terminated when @connection is
3038 * closed by the remote peer. See
3039 * #GDBusConnection:exit-on-close for more details.
3041 * Returns: whether the process is terminated when @connection is
3042 * closed by the remote peer
3047 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
3049 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3051 if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
3058 * g_dbus_connection_get_guid:
3059 * @connection: a #GDBusConnection
3061 * The GUID of the peer performing the role of server when
3062 * authenticating. See #GDBusConnection:guid for more details.
3064 * Returns: The GUID. Do not free this string, it is owned by
3070 g_dbus_connection_get_guid (GDBusConnection *connection)
3072 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3073 return connection->guid;
3077 * g_dbus_connection_get_unique_name:
3078 * @connection: a #GDBusConnection
3080 * Gets the unique name of @connection as assigned by the message
3081 * bus. This can also be used to figure out if @connection is a
3082 * message bus connection.
3084 * Returns: the unique name or %NULL if @connection is not a message
3085 * bus connection. Do not free this string, it is owned by
3091 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3093 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3095 /* do not use g_return_val_if_fail(), we want the memory barrier */
3096 if (!check_initialized (connection))
3099 return connection->bus_unique_name;
3103 * g_dbus_connection_get_peer_credentials:
3104 * @connection: a #GDBusConnection
3106 * Gets the credentials of the authenticated peer. This will always
3107 * return %NULL unless @connection acted as a server
3108 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3109 * when set up and the client passed credentials as part of the
3110 * authentication process.
3112 * In a message bus setup, the message bus is always the server and
3113 * each application is a client. So this method will always return
3114 * %NULL for message bus clients.
3116 * Returns: (transfer none): a #GCredentials or %NULL if not available.
3117 * Do not free this object, it is owned by @connection.
3122 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3124 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3126 /* do not use g_return_val_if_fail(), we want the memory barrier */
3127 if (!check_initialized (connection))
3130 return connection->credentials;
3133 /* ---------------------------------------------------------------------------------------------------- */
3135 static guint _global_filter_id = 1;
3138 * g_dbus_connection_add_filter:
3139 * @connection: a #GDBusConnection
3140 * @filter_function: a filter function
3141 * @user_data: user data to pass to @filter_function
3142 * @user_data_free_func: function to free @user_data with when filter
3143 * is removed or %NULL
3145 * Adds a message filter. Filters are handlers that are run on all
3146 * incoming and outgoing messages, prior to standard dispatch. Filters
3147 * are run in the order that they were added. The same handler can be
3148 * added as a filter more than once, in which case it will be run more
3149 * than once. Filters added during a filter callback won't be run on
3150 * the message being processed. Filter functions are allowed to modify
3151 * and even drop messages.
3153 * Note that filters are run in a dedicated message handling thread so
3154 * they can't block and, generally, can't do anything but signal a
3155 * worker thread. Also note that filters are rarely needed - use API
3156 * such as g_dbus_connection_send_message_with_reply(),
3157 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3159 * If a filter consumes an incoming message the message is not
3160 * dispatched anywhere else - not even the standard dispatch machinery
3161 * (that API such as g_dbus_connection_signal_subscribe() and
3162 * g_dbus_connection_send_message_with_reply() relies on) will see the
3163 * message. Similary, if a filter consumes an outgoing message, the
3164 * message will not be sent to the other peer.
3166 * Returns: a filter identifier that can be used with
3167 * g_dbus_connection_remove_filter()
3172 g_dbus_connection_add_filter (GDBusConnection *connection,
3173 GDBusMessageFilterFunction filter_function,
3175 GDestroyNotify user_data_free_func)
3179 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3180 g_return_val_if_fail (filter_function != NULL, 0);
3181 g_return_val_if_fail (check_initialized (connection), 0);
3183 CONNECTION_LOCK (connection);
3184 data = g_new0 (FilterData, 1);
3185 data->id = _global_filter_id++; /* TODO: overflow etc. */
3186 data->filter_function = filter_function;
3187 data->user_data = user_data;
3188 data->user_data_free_func = user_data_free_func;
3189 g_ptr_array_add (connection->filters, data);
3190 CONNECTION_UNLOCK (connection);
3195 /* only called from finalize(), removes all filters */
3197 purge_all_filters (GDBusConnection *connection)
3200 for (n = 0; n < connection->filters->len; n++)
3202 FilterData *data = connection->filters->pdata[n];
3203 if (data->user_data_free_func != NULL)
3204 data->user_data_free_func (data->user_data);
3210 * g_dbus_connection_remove_filter:
3211 * @connection: a #GDBusConnection
3212 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3219 g_dbus_connection_remove_filter (GDBusConnection *connection,
3223 FilterData *to_destroy;
3225 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3226 g_return_if_fail (check_initialized (connection));
3228 CONNECTION_LOCK (connection);
3230 for (n = 0; n < connection->filters->len; n++)
3232 FilterData *data = connection->filters->pdata[n];
3233 if (data->id == filter_id)
3235 g_ptr_array_remove_index (connection->filters, n);
3240 CONNECTION_UNLOCK (connection);
3242 /* do free without holding lock */
3243 if (to_destroy != NULL)
3245 if (to_destroy->user_data_free_func != NULL)
3246 to_destroy->user_data_free_func (to_destroy->user_data);
3247 g_free (to_destroy);
3251 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3255 /* ---------------------------------------------------------------------------------------------------- */
3261 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3262 gchar *interface_name;
3266 GDBusSignalFlags flags;
3267 GArray *subscribers;
3272 GDBusSignalCallback callback;
3274 GDestroyNotify user_data_free_func;
3276 GMainContext *context;
3280 signal_data_free (SignalData *signal_data)
3282 g_free (signal_data->rule);
3283 g_free (signal_data->sender);
3284 g_free (signal_data->sender_unique_name);
3285 g_free (signal_data->interface_name);
3286 g_free (signal_data->member);
3287 g_free (signal_data->object_path);
3288 g_free (signal_data->arg0);
3289 g_array_free (signal_data->subscribers, TRUE);
3290 g_free (signal_data);
3294 args_to_rule (const gchar *sender,
3295 const gchar *interface_name,
3296 const gchar *member,
3297 const gchar *object_path,
3299 GDBusSignalFlags flags)
3303 rule = g_string_new ("type='signal'");
3304 if (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE)
3305 g_string_prepend_c (rule, '-');
3307 g_string_append_printf (rule, ",sender='%s'", sender);
3308 if (interface_name != NULL)
3309 g_string_append_printf (rule, ",interface='%s'", interface_name);
3311 g_string_append_printf (rule, ",member='%s'", member);
3312 if (object_path != NULL)
3313 g_string_append_printf (rule, ",path='%s'", object_path);
3317 if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3318 g_string_append_printf (rule, ",arg0path='%s'", arg0);
3319 else if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3320 g_string_append_printf (rule, ",arg0namespace='%s'", arg0);
3322 g_string_append_printf (rule, ",arg0='%s'", arg0);
3325 return g_string_free (rule, FALSE);
3328 static guint _global_subscriber_id = 1;
3329 static guint _global_registration_id = 1;
3330 static guint _global_subtree_registration_id = 1;
3332 /* ---------------------------------------------------------------------------------------------------- */
3334 /* Called in a user thread, lock is held */
3336 add_match_rule (GDBusConnection *connection,
3337 const gchar *match_rule)
3340 GDBusMessage *message;
3342 if (match_rule[0] == '-')
3345 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3346 "/org/freedesktop/DBus", /* path */
3347 "org.freedesktop.DBus", /* interface */
3349 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3351 if (!g_dbus_connection_send_message_unlocked (connection,
3353 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3357 g_critical ("Error while sending AddMatch() message: %s", error->message);
3358 g_error_free (error);
3360 g_object_unref (message);
3363 /* ---------------------------------------------------------------------------------------------------- */
3365 /* Called in a user thread, lock is held */
3367 remove_match_rule (GDBusConnection *connection,
3368 const gchar *match_rule)
3371 GDBusMessage *message;
3373 if (match_rule[0] == '-')
3376 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3377 "/org/freedesktop/DBus", /* path */
3378 "org.freedesktop.DBus", /* interface */
3380 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3383 if (!g_dbus_connection_send_message_unlocked (connection,
3385 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3389 /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
3390 * critical; but we're holding the lock, and our caller checked whether
3391 * we were already closed, so we can't get that error.
3393 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3394 g_error_free (error);
3396 g_object_unref (message);
3399 /* ---------------------------------------------------------------------------------------------------- */
3402 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3404 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3405 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3406 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3407 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3408 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3411 /* ---------------------------------------------------------------------------------------------------- */
3414 * g_dbus_connection_signal_subscribe:
3415 * @connection: a #GDBusConnection
3416 * @sender: (allow-none): sender name to match on (unique or well-known name)
3417 * or %NULL to listen from all senders
3418 * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3419 * match on all interfaces
3420 * @member: (allow-none): D-Bus signal name to match on or %NULL to match on
3422 * @object_path: (allow-none): object path to match on or %NULL to match on
3424 * @arg0: (allow-none): contents of first string argument to match on or %NULL
3425 * to match on all kinds of arguments
3426 * @flags: flags describing how to subscribe to the signal (currently unused)
3427 * @callback: callback to invoke when there is a signal matching the requested data
3428 * @user_data: user data to pass to @callback
3429 * @user_data_free_func: (allow-none): function to free @user_data with when
3430 * subscription is removed or %NULL
3432 * Subscribes to signals on @connection and invokes @callback with a whenever
3433 * the signal is received. Note that @callback will be invoked in the
3434 * [thread-default main context][g-main-context-push-thread-default]
3435 * of the thread you are calling this method from.
3437 * If @connection is not a message bus connection, @sender must be
3440 * If @sender is a well-known name note that @callback is invoked with
3441 * the unique name for the owner of @sender, not the well-known name
3442 * as one would expect. This is because the message bus rewrites the
3443 * name. As such, to avoid certain race conditions, users should be
3444 * tracking the name owner of the well-known name and use that when
3445 * processing the received signal.
3447 * If one of %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE or
3448 * %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH are given, @arg0 is
3449 * interpreted as part of a namespace or path. The first argument
3450 * of a signal is matched against that part as specified by D-Bus.
3452 * Returns: a subscription identifier that can be used with g_dbus_connection_signal_unsubscribe()
3457 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3458 const gchar *sender,
3459 const gchar *interface_name,
3460 const gchar *member,
3461 const gchar *object_path,
3463 GDBusSignalFlags flags,
3464 GDBusSignalCallback callback,
3466 GDestroyNotify user_data_free_func)
3469 SignalData *signal_data;
3470 SignalSubscriber subscriber;
3471 GPtrArray *signal_data_array;
3472 const gchar *sender_unique_name;
3474 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3475 * an OOM condition. We might want to change that but that would involve making
3476 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3477 * handle that. And there's really no sensible way of handling this short of retrying
3478 * to add the match rule... and then there's the little thing that, hey, maybe there's
3479 * a reason the bus in an OOM condition.
3481 * Doable, but not really sure it's worth it...
3484 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3485 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3486 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3487 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3488 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3489 g_return_val_if_fail (callback != NULL, 0);
3490 g_return_val_if_fail (check_initialized (connection), 0);
3491 g_return_val_if_fail (!((flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH) && (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)), 0);
3492 g_return_val_if_fail (!(arg0 == NULL && (flags & (G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH | G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE))), 0);
3494 CONNECTION_LOCK (connection);
3496 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3497 * with a '-' character to prefix the rule (which will otherwise be
3500 * This allows us to hash the rule and do our lifecycle tracking in
3501 * the usual way, but the '-' prevents the match rule from ever
3502 * actually being send to the bus (either for add or remove).
3504 rule = args_to_rule (sender, interface_name, member, object_path, arg0, flags);
3506 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3507 sender_unique_name = sender;
3509 sender_unique_name = "";
3511 subscriber.callback = callback;
3512 subscriber.user_data = user_data;
3513 subscriber.user_data_free_func = user_data_free_func;
3514 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3515 subscriber.context = g_main_context_ref_thread_default ();
3517 /* see if we've already have this rule */
3518 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3519 if (signal_data != NULL)
3521 g_array_append_val (signal_data->subscribers, subscriber);
3526 signal_data = g_new0 (SignalData, 1);
3527 signal_data->rule = rule;
3528 signal_data->sender = g_strdup (sender);
3529 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3530 signal_data->interface_name = g_strdup (interface_name);
3531 signal_data->member = g_strdup (member);
3532 signal_data->object_path = g_strdup (object_path);
3533 signal_data->arg0 = g_strdup (arg0);
3534 signal_data->flags = flags;
3535 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3536 g_array_append_val (signal_data->subscribers, subscriber);
3538 g_hash_table_insert (connection->map_rule_to_signal_data,
3542 /* Add the match rule to the bus...
3544 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3545 * always send such messages to us.
3547 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3549 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3550 add_match_rule (connection, signal_data->rule);
3553 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3554 signal_data->sender_unique_name);
3555 if (signal_data_array == NULL)
3557 signal_data_array = g_ptr_array_new ();
3558 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3559 g_strdup (signal_data->sender_unique_name),
3562 g_ptr_array_add (signal_data_array, signal_data);
3565 g_hash_table_insert (connection->map_id_to_signal_data,
3566 GUINT_TO_POINTER (subscriber.id),
3569 CONNECTION_UNLOCK (connection);
3571 return subscriber.id;
3574 /* ---------------------------------------------------------------------------------------------------- */
3576 /* called in any thread */
3577 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3579 unsubscribe_id_internal (GDBusConnection *connection,
3580 guint subscription_id,
3581 GArray *out_removed_subscribers)
3583 SignalData *signal_data;
3584 GPtrArray *signal_data_array;
3587 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3588 GUINT_TO_POINTER (subscription_id));
3589 if (signal_data == NULL)
3591 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3595 for (n = 0; n < signal_data->subscribers->len; n++)
3597 SignalSubscriber *subscriber;
3599 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3600 if (subscriber->id != subscription_id)
3603 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3604 GUINT_TO_POINTER (subscription_id)));
3605 g_array_append_val (out_removed_subscribers, *subscriber);
3606 g_array_remove_index (signal_data->subscribers, n);
3608 if (signal_data->subscribers->len == 0)
3610 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3612 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3613 signal_data->sender_unique_name);
3614 g_warn_if_fail (signal_data_array != NULL);
3615 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3617 if (signal_data_array->len == 0)
3619 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3620 signal_data->sender_unique_name));
3623 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3624 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
3625 !is_signal_data_for_name_lost_or_acquired (signal_data) &&
3626 !g_dbus_connection_is_closed (connection) &&
3627 !connection->finalizing)
3629 /* The check for g_dbus_connection_is_closed() means that
3630 * sending the RemoveMatch message can't fail with
3631 * G_IO_ERROR_CLOSED, because we're holding the lock,
3632 * so on_worker_closed() can't happen between the check we just
3633 * did, and releasing the lock later.
3635 remove_match_rule (connection, signal_data->rule);
3638 signal_data_free (signal_data);
3644 g_assert_not_reached ();
3651 * g_dbus_connection_signal_unsubscribe:
3652 * @connection: a #GDBusConnection
3653 * @subscription_id: a subscription id obtained from
3654 * g_dbus_connection_signal_subscribe()
3656 * Unsubscribes from signals.
3661 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3662 guint subscription_id)
3664 GArray *subscribers;
3667 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3668 g_return_if_fail (check_initialized (connection));
3670 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3672 CONNECTION_LOCK (connection);
3673 unsubscribe_id_internal (connection,
3676 CONNECTION_UNLOCK (connection);
3679 g_assert (subscribers->len == 0 || subscribers->len == 1);
3681 /* call GDestroyNotify without lock held */
3682 for (n = 0; n < subscribers->len; n++)
3684 SignalSubscriber *subscriber;
3685 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3686 call_destroy_notify (subscriber->context,
3687 subscriber->user_data_free_func,
3688 subscriber->user_data);
3689 g_main_context_unref (subscriber->context);
3692 g_array_free (subscribers, TRUE);
3695 /* ---------------------------------------------------------------------------------------------------- */
3699 guint subscription_id;
3700 GDBusSignalCallback callback;
3702 GDBusMessage *message;
3703 GDBusConnection *connection;
3704 const gchar *sender;
3706 const gchar *interface;
3707 const gchar *member;
3710 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3714 emit_signal_instance_in_idle_cb (gpointer data)
3716 SignalInstance *signal_instance = data;
3717 GVariant *parameters;
3718 gboolean has_subscription;
3720 parameters = g_dbus_message_get_body (signal_instance->message);
3721 if (parameters == NULL)
3723 parameters = g_variant_new ("()");
3724 g_variant_ref_sink (parameters);
3728 g_variant_ref_sink (parameters);
3732 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3733 signal_instance->subscription_id,
3734 signal_instance->sender,
3735 signal_instance->path,
3736 signal_instance->interface,
3737 signal_instance->member,
3738 g_variant_print (parameters, TRUE));
3741 /* Careful here, don't do the callback if we no longer has the subscription */
3742 CONNECTION_LOCK (signal_instance->connection);
3743 has_subscription = FALSE;
3744 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3745 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3746 has_subscription = TRUE;
3747 CONNECTION_UNLOCK (signal_instance->connection);
3749 if (has_subscription)
3750 signal_instance->callback (signal_instance->connection,
3751 signal_instance->sender,
3752 signal_instance->path,
3753 signal_instance->interface,
3754 signal_instance->member,
3756 signal_instance->user_data);
3758 g_variant_unref (parameters);
3764 signal_instance_free (SignalInstance *signal_instance)
3766 g_object_unref (signal_instance->message);
3767 g_object_unref (signal_instance->connection);
3768 g_free (signal_instance);
3772 namespace_rule_matches (const gchar *namespace,
3778 len_namespace = strlen (namespace);
3779 len_name = strlen (name);
3781 if (len_name < len_namespace)
3784 if (memcmp (namespace, name, len_namespace) != 0)
3787 return len_namespace == len_name || name[len_namespace] == '.';
3791 path_rule_matches (const gchar *path_a,
3792 const gchar *path_b)
3796 len_a = strlen (path_a);
3797 len_b = strlen (path_b);
3799 if (len_a < len_b && path_a[len_a - 1] != '/')
3802 if (len_b < len_a && path_b[len_b - 1] != '/')
3805 return memcmp (path_a, path_b, MIN (len_a, len_b)) == 0;
3808 /* called in GDBusWorker thread WITH lock held */
3810 schedule_callbacks (GDBusConnection *connection,
3811 GPtrArray *signal_data_array,
3812 GDBusMessage *message,
3813 const gchar *sender)
3816 const gchar *interface;
3817 const gchar *member;
3826 interface = g_dbus_message_get_interface (message);
3827 member = g_dbus_message_get_member (message);
3828 path = g_dbus_message_get_path (message);
3829 arg0 = g_dbus_message_get_arg0 (message);
3832 g_print ("In schedule_callbacks:\n"
3834 " interface = '%s'\n"
3845 /* TODO: if this is slow, then we can change signal_data_array into
3846 * map_object_path_to_signal_data_array or something.
3848 for (n = 0; n < signal_data_array->len; n++)
3850 SignalData *signal_data = signal_data_array->pdata[n];
3852 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3855 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3858 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3861 if (signal_data->arg0 != NULL)
3866 if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3868 if (!namespace_rule_matches (signal_data->arg0, arg0))
3871 else if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3873 if (!path_rule_matches (signal_data->arg0, arg0))
3876 else if (!g_str_equal (signal_data->arg0, arg0))
3880 for (m = 0; m < signal_data->subscribers->len; m++)
3882 SignalSubscriber *subscriber;
3883 GSource *idle_source;
3884 SignalInstance *signal_instance;
3886 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3888 signal_instance = g_new0 (SignalInstance, 1);
3889 signal_instance->subscription_id = subscriber->id;
3890 signal_instance->callback = subscriber->callback;
3891 signal_instance->user_data = subscriber->user_data;
3892 signal_instance->message = g_object_ref (message);
3893 signal_instance->connection = g_object_ref (connection);
3894 signal_instance->sender = sender;
3895 signal_instance->path = path;
3896 signal_instance->interface = interface;
3897 signal_instance->member = member;
3899 idle_source = g_idle_source_new ();
3900 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3901 g_source_set_callback (idle_source,
3902 emit_signal_instance_in_idle_cb,
3904 (GDestroyNotify) signal_instance_free);
3905 g_source_attach (idle_source, subscriber->context);
3906 g_source_unref (idle_source);
3911 /* called in GDBusWorker thread with lock held */
3913 distribute_signals (GDBusConnection *connection,
3914 GDBusMessage *message)
3916 GPtrArray *signal_data_array;
3917 const gchar *sender;
3919 sender = g_dbus_message_get_sender (message);
3921 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3923 _g_dbus_debug_print_lock ();
3924 g_print ("========================================================================\n"
3925 "GDBus-debug:Signal:\n"
3926 " <<<< RECEIVED SIGNAL %s.%s\n"
3928 " sent by name %s\n",
3929 g_dbus_message_get_interface (message),
3930 g_dbus_message_get_member (message),
3931 g_dbus_message_get_path (message),
3932 sender != NULL ? sender : "(none)");
3933 _g_dbus_debug_print_unlock ();
3936 /* collect subscribers that match on sender */
3939 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3940 if (signal_data_array != NULL)
3941 schedule_callbacks (connection, signal_data_array, message, sender);
3944 /* collect subscribers not matching on sender */
3945 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3946 if (signal_data_array != NULL)
3947 schedule_callbacks (connection, signal_data_array, message, sender);
3950 /* ---------------------------------------------------------------------------------------------------- */
3952 /* only called from finalize(), removes all subscriptions */
3954 purge_all_signal_subscriptions (GDBusConnection *connection)
3956 GHashTableIter iter;
3959 GArray *subscribers;
3962 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3963 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3964 while (g_hash_table_iter_next (&iter, &key, NULL))
3966 guint subscription_id = GPOINTER_TO_UINT (key);
3967 g_array_append_val (ids, subscription_id);
3970 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3971 for (n = 0; n < ids->len; n++)
3973 guint subscription_id = g_array_index (ids, guint, n);
3974 unsubscribe_id_internal (connection,
3978 g_array_free (ids, TRUE);
3980 /* call GDestroyNotify without lock held */
3981 for (n = 0; n < subscribers->len; n++)
3983 SignalSubscriber *subscriber;
3984 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3985 call_destroy_notify (subscriber->context,
3986 subscriber->user_data_free_func,
3987 subscriber->user_data);
3988 g_main_context_unref (subscriber->context);
3991 g_array_free (subscribers, TRUE);
3994 /* ---------------------------------------------------------------------------------------------------- */
3996 static GDBusInterfaceVTable *
3997 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3999 /* Don't waste memory by copying padding - remember to update this
4000 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
4002 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4006 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
4011 /* ---------------------------------------------------------------------------------------------------- */
4013 static GDBusSubtreeVTable *
4014 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
4016 /* Don't waste memory by copying padding - remember to update this
4017 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
4019 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4023 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
4028 /* ---------------------------------------------------------------------------------------------------- */
4030 struct ExportedObject
4033 GDBusConnection *connection;
4035 /* maps gchar* -> ExportedInterface* */
4036 GHashTable *map_if_name_to_ei;
4039 /* only called with lock held */
4041 exported_object_free (ExportedObject *eo)
4043 g_free (eo->object_path);
4044 g_hash_table_unref (eo->map_if_name_to_ei);
4053 gchar *interface_name;
4054 GDBusInterfaceVTable *vtable;
4055 GDBusInterfaceInfo *interface_info;
4057 GMainContext *context;
4059 GDestroyNotify user_data_free_func;
4060 } ExportedInterface;
4062 /* called with lock held */
4064 exported_interface_free (ExportedInterface *ei)
4066 g_dbus_interface_info_cache_release (ei->interface_info);
4067 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
4069 call_destroy_notify (ei->context,
4070 ei->user_data_free_func,
4073 g_main_context_unref (ei->context);
4075 g_free (ei->interface_name);
4076 _g_dbus_interface_vtable_free (ei->vtable);
4080 /* ---------------------------------------------------------------------------------------------------- */
4082 /* Convenience function to check if @registration_id (if not zero) or
4083 * @subtree_registration_id (if not zero) has been unregistered. If
4084 * so, returns %TRUE.
4086 * May be called by any thread. Caller must *not* hold lock.
4089 has_object_been_unregistered (GDBusConnection *connection,
4090 guint registration_id,
4091 guint subtree_registration_id)
4095 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4099 CONNECTION_LOCK (connection);
4100 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
4101 GUINT_TO_POINTER (registration_id)) == NULL)
4105 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
4106 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
4110 CONNECTION_UNLOCK (connection);
4115 /* ---------------------------------------------------------------------------------------------------- */
4119 GDBusConnection *connection;
4120 GDBusMessage *message;
4122 const gchar *property_name;
4123 const GDBusInterfaceVTable *vtable;
4124 GDBusInterfaceInfo *interface_info;
4125 const GDBusPropertyInfo *property_info;
4126 guint registration_id;
4127 guint subtree_registration_id;
4131 property_data_free (PropertyData *data)
4133 g_object_unref (data->connection);
4134 g_object_unref (data->message);
4138 /* called in thread where object was registered - no locks held */
4140 invoke_get_property_in_idle_cb (gpointer _data)
4142 PropertyData *data = _data;
4145 GDBusMessage *reply;
4147 if (has_object_been_unregistered (data->connection,
4148 data->registration_id,
4149 data->subtree_registration_id))
4151 reply = g_dbus_message_new_method_error (data->message,
4152 "org.freedesktop.DBus.Error.UnknownMethod",
4153 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4154 g_dbus_message_get_path (data->message));
4155 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4156 g_object_unref (reply);
4161 value = data->vtable->get_property (data->connection,
4162 g_dbus_message_get_sender (data->message),
4163 g_dbus_message_get_path (data->message),
4164 data->interface_info->name,
4165 data->property_name,
4172 g_assert_no_error (error);
4174 g_variant_take_ref (value);
4175 reply = g_dbus_message_new_method_reply (data->message);
4176 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4177 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4178 g_variant_unref (value);
4179 g_object_unref (reply);
4183 gchar *dbus_error_name;
4184 g_assert (error != NULL);
4185 dbus_error_name = g_dbus_error_encode_gerror (error);
4186 reply = g_dbus_message_new_method_error_literal (data->message,
4189 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4190 g_free (dbus_error_name);
4191 g_error_free (error);
4192 g_object_unref (reply);
4199 /* called in thread where object was registered - no locks held */
4201 invoke_set_property_in_idle_cb (gpointer _data)
4203 PropertyData *data = _data;
4205 GDBusMessage *reply;
4211 g_variant_get (g_dbus_message_get_body (data->message),
4217 if (!data->vtable->set_property (data->connection,
4218 g_dbus_message_get_sender (data->message),
4219 g_dbus_message_get_path (data->message),
4220 data->interface_info->name,
4221 data->property_name,
4226 gchar *dbus_error_name;
4227 g_assert (error != NULL);
4228 dbus_error_name = g_dbus_error_encode_gerror (error);
4229 reply = g_dbus_message_new_method_error_literal (data->message,
4232 g_free (dbus_error_name);
4233 g_error_free (error);
4237 reply = g_dbus_message_new_method_reply (data->message);
4240 g_assert (reply != NULL);
4241 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4242 g_object_unref (reply);
4243 g_variant_unref (value);
4248 /* called in any thread with connection's lock held */
4250 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4251 GDBusMessage *message,
4252 guint registration_id,
4253 guint subtree_registration_id,
4255 GDBusInterfaceInfo *interface_info,
4256 const GDBusInterfaceVTable *vtable,
4257 GMainContext *main_context,
4261 const char *interface_name;
4262 const char *property_name;
4263 const GDBusPropertyInfo *property_info;
4264 GSource *idle_source;
4265 PropertyData *property_data;
4266 GDBusMessage *reply;
4271 g_variant_get (g_dbus_message_get_body (message),
4276 g_variant_get (g_dbus_message_get_body (message),
4285 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4287 property_info = NULL;
4289 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4290 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4291 if (property_info == NULL)
4293 reply = g_dbus_message_new_method_error (message,
4294 "org.freedesktop.DBus.Error.InvalidArgs",
4295 _("No such property '%s'"),
4297 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4298 g_object_unref (reply);
4303 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4305 reply = g_dbus_message_new_method_error (message,
4306 "org.freedesktop.DBus.Error.InvalidArgs",
4307 _("Property '%s' is not readable"),
4309 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4310 g_object_unref (reply);
4314 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4316 reply = g_dbus_message_new_method_error (message,
4317 "org.freedesktop.DBus.Error.InvalidArgs",
4318 _("Property '%s' is not writable"),
4320 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4321 g_object_unref (reply);
4330 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4331 * of the given value is wrong
4333 g_variant_get_child (g_dbus_message_get_body (message), 2, "v", &value);
4334 if (g_strcmp0 (g_variant_get_type_string (value), property_info->signature) != 0)
4336 reply = g_dbus_message_new_method_error (message,
4337 "org.freedesktop.DBus.Error.InvalidArgs",
4338 _("Error setting property '%s': Expected type '%s' but got '%s'"),
4339 property_name, property_info->signature,
4340 g_variant_get_type_string (value));
4341 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4342 g_variant_unref (value);
4343 g_object_unref (reply);
4348 g_variant_unref (value);
4351 /* If the vtable pointer for get_property() resp. set_property() is
4352 * NULL then dispatch the call via the method_call() handler.
4356 if (vtable->get_property == NULL)
4358 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4359 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4360 vtable, main_context, user_data);
4367 if (vtable->set_property == NULL)
4369 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4370 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4371 vtable, main_context, user_data);
4377 /* ok, got the property info - call user code in an idle handler */
4378 property_data = g_new0 (PropertyData, 1);
4379 property_data->connection = g_object_ref (connection);
4380 property_data->message = g_object_ref (message);
4381 property_data->user_data = user_data;
4382 property_data->property_name = property_name;
4383 property_data->vtable = vtable;
4384 property_data->interface_info = interface_info;
4385 property_data->property_info = property_info;
4386 property_data->registration_id = registration_id;
4387 property_data->subtree_registration_id = subtree_registration_id;
4389 idle_source = g_idle_source_new ();
4390 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4391 g_source_set_callback (idle_source,
4392 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4394 (GDestroyNotify) property_data_free);
4395 g_source_attach (idle_source, main_context);
4396 g_source_unref (idle_source);
4404 /* called in GDBusWorker thread with connection's lock held */
4406 handle_getset_property (GDBusConnection *connection,
4408 GDBusMessage *message,
4411 ExportedInterface *ei;
4413 const char *interface_name;
4414 const char *property_name;
4419 g_variant_get (g_dbus_message_get_body (message),
4424 g_variant_get (g_dbus_message_get_body (message),
4430 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4431 * no such interface registered
4433 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4436 GDBusMessage *reply;
4437 reply = g_dbus_message_new_method_error (message,
4438 "org.freedesktop.DBus.Error.InvalidArgs",
4439 _("No such interface '%s'"),
4441 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4442 g_object_unref (reply);
4447 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4460 /* ---------------------------------------------------------------------------------------------------- */
4464 GDBusConnection *connection;
4465 GDBusMessage *message;
4467 const GDBusInterfaceVTable *vtable;
4468 GDBusInterfaceInfo *interface_info;
4469 guint registration_id;
4470 guint subtree_registration_id;
4471 } PropertyGetAllData;
4474 property_get_all_data_free (PropertyData *data)
4476 g_object_unref (data->connection);
4477 g_object_unref (data->message);
4481 /* called in thread where object was registered - no locks held */
4483 invoke_get_all_properties_in_idle_cb (gpointer _data)
4485 PropertyGetAllData *data = _data;
4486 GVariantBuilder builder;
4487 GDBusMessage *reply;
4490 if (has_object_been_unregistered (data->connection,
4491 data->registration_id,
4492 data->subtree_registration_id))
4494 reply = g_dbus_message_new_method_error (data->message,
4495 "org.freedesktop.DBus.Error.UnknownMethod",
4496 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4497 g_dbus_message_get_path (data->message));
4498 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4499 g_object_unref (reply);
4503 /* TODO: Right now we never fail this call - we just omit values if
4504 * a get_property() call is failing.
4506 * We could fail the whole call if just a single get_property() call
4507 * returns an error. We need clarification in the D-Bus spec about this.
4509 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4510 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4511 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4513 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4516 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4519 value = data->vtable->get_property (data->connection,
4520 g_dbus_message_get_sender (data->message),
4521 g_dbus_message_get_path (data->message),
4522 data->interface_info->name,
4523 property_info->name,
4530 g_variant_take_ref (value);
4531 g_variant_builder_add (&builder,
4533 property_info->name,
4535 g_variant_unref (value);
4537 g_variant_builder_close (&builder);
4539 reply = g_dbus_message_new_method_reply (data->message);
4540 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4541 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4542 g_object_unref (reply);
4549 interface_has_readable_properties (GDBusInterfaceInfo *interface_info)
4553 if (!interface_info->properties)
4556 for (i = 0; interface_info->properties[i]; i++)
4557 if (interface_info->properties[i]->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE)
4563 /* called in any thread with connection's lock held */
4565 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4566 GDBusMessage *message,
4567 guint registration_id,
4568 guint subtree_registration_id,
4569 GDBusInterfaceInfo *interface_info,
4570 const GDBusInterfaceVTable *vtable,
4571 GMainContext *main_context,
4575 GSource *idle_source;
4576 PropertyGetAllData *property_get_all_data;
4583 /* If the vtable pointer for get_property() is NULL but we have a
4584 * non-zero number of readable properties, then dispatch the call via
4585 * the method_call() handler.
4587 if (vtable->get_property == NULL && interface_has_readable_properties (interface_info))
4589 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4590 interface_info, NULL, NULL, g_dbus_message_get_body (message),
4591 vtable, main_context, user_data);
4596 /* ok, got the property info - call user in an idle handler */
4597 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4598 property_get_all_data->connection = g_object_ref (connection);
4599 property_get_all_data->message = g_object_ref (message);
4600 property_get_all_data->user_data = user_data;
4601 property_get_all_data->vtable = vtable;
4602 property_get_all_data->interface_info = interface_info;
4603 property_get_all_data->registration_id = registration_id;
4604 property_get_all_data->subtree_registration_id = subtree_registration_id;
4606 idle_source = g_idle_source_new ();
4607 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4608 g_source_set_callback (idle_source,
4609 invoke_get_all_properties_in_idle_cb,
4610 property_get_all_data,
4611 (GDestroyNotify) property_get_all_data_free);
4612 g_source_attach (idle_source, main_context);
4613 g_source_unref (idle_source);
4621 /* called in GDBusWorker thread with connection's lock held */
4623 handle_get_all_properties (GDBusConnection *connection,
4625 GDBusMessage *message)
4627 ExportedInterface *ei;
4629 const char *interface_name;
4633 g_variant_get (g_dbus_message_get_body (message),
4637 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4638 * no such interface registered
4640 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4643 GDBusMessage *reply;
4644 reply = g_dbus_message_new_method_error (message,
4645 "org.freedesktop.DBus.Error.InvalidArgs",
4646 _("No such interface"),
4648 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4649 g_object_unref (reply);
4654 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4666 /* ---------------------------------------------------------------------------------------------------- */
4668 static const gchar introspect_header[] =
4669 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4670 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4671 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4674 static const gchar introspect_tail[] =
4677 static const gchar introspect_properties_interface[] =
4678 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4679 " <method name=\"Get\">\n"
4680 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4681 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4682 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4684 " <method name=\"GetAll\">\n"
4685 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4686 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4688 " <method name=\"Set\">\n"
4689 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4690 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4691 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4693 " <signal name=\"PropertiesChanged\">\n"
4694 " <arg type=\"s\" name=\"interface_name\"/>\n"
4695 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4696 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4700 static const gchar introspect_introspectable_interface[] =
4701 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4702 " <method name=\"Introspect\">\n"
4703 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4706 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4707 " <method name=\"Ping\"/>\n"
4708 " <method name=\"GetMachineId\">\n"
4709 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4714 introspect_append_header (GString *s)
4716 g_string_append (s, introspect_header);
4720 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4722 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4728 begin = object_path + path_len;
4729 end = strchr (begin, '/');
4731 s = g_strndup (begin, end - begin);
4733 s = g_strdup (begin);
4735 if (g_hash_table_lookup (set, s) == NULL)
4736 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
4742 /* TODO: we want a nicer public interface for this */
4743 /* called in any thread with connection's lock held */
4745 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4750 GHashTableIter hash_iter;
4751 const gchar *object_path;
4757 CONNECTION_ENSURE_LOCK (connection);
4759 path_len = strlen (path);
4763 set = g_hash_table_new (g_str_hash, g_str_equal);
4765 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4766 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4767 maybe_add_path (path, path_len, object_path, set);
4769 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4770 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4771 maybe_add_path (path, path_len, object_path, set);
4773 p = g_ptr_array_new ();
4774 keys = g_hash_table_get_keys (set);
4775 for (l = keys; l != NULL; l = l->next)
4776 g_ptr_array_add (p, l->data);
4777 g_hash_table_unref (set);
4780 g_ptr_array_add (p, NULL);
4781 ret = (gchar **) g_ptr_array_free (p, FALSE);
4785 /* called in any thread with connection's lock not held */
4787 g_dbus_connection_list_registered (GDBusConnection *connection,
4791 CONNECTION_LOCK (connection);
4792 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4793 CONNECTION_UNLOCK (connection);
4797 /* called in GDBusWorker thread with connection's lock held */
4799 handle_introspect (GDBusConnection *connection,
4801 GDBusMessage *message)
4805 GDBusMessage *reply;
4806 GHashTableIter hash_iter;
4807 ExportedInterface *ei;
4810 /* first the header with the standard interfaces */
4811 s = g_string_sized_new (sizeof (introspect_header) +
4812 sizeof (introspect_properties_interface) +
4813 sizeof (introspect_introspectable_interface) +
4814 sizeof (introspect_tail));
4815 introspect_append_header (s);
4816 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4817 "org.freedesktop.DBus.Properties"))
4818 g_string_append (s, introspect_properties_interface);
4820 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4821 "org.freedesktop.DBus.Introspectable"))
4822 g_string_append (s, introspect_introspectable_interface);
4824 /* then include the registered interfaces */
4825 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4826 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4827 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4829 /* finally include nodes registered below us */
4830 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4831 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4832 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4833 g_strfreev (registered);
4834 g_string_append (s, introspect_tail);
4836 reply = g_dbus_message_new_method_reply (message);
4837 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4838 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4839 g_object_unref (reply);
4840 g_string_free (s, TRUE);
4845 /* called in thread where object was registered - no locks held */
4847 call_in_idle_cb (gpointer user_data)
4849 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4850 GDBusInterfaceVTable *vtable;
4851 guint registration_id;
4852 guint subtree_registration_id;
4854 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4855 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4857 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4859 subtree_registration_id))
4861 GDBusMessage *reply;
4862 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4863 "org.freedesktop.DBus.Error.UnknownMethod",
4864 _("No such interface '%s' on object at path %s"),
4865 g_dbus_method_invocation_get_interface_name (invocation),
4866 g_dbus_method_invocation_get_object_path (invocation));
4867 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4868 g_object_unref (reply);
4872 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4873 g_assert (vtable != NULL && vtable->method_call != NULL);
4875 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4876 g_dbus_method_invocation_get_sender (invocation),
4877 g_dbus_method_invocation_get_object_path (invocation),
4878 g_dbus_method_invocation_get_interface_name (invocation),
4879 g_dbus_method_invocation_get_method_name (invocation),
4880 g_dbus_method_invocation_get_parameters (invocation),
4881 g_object_ref (invocation),
4882 g_dbus_method_invocation_get_user_data (invocation));
4888 /* called in GDBusWorker thread with connection's lock held */
4890 schedule_method_call (GDBusConnection *connection,
4891 GDBusMessage *message,
4892 guint registration_id,
4893 guint subtree_registration_id,
4894 const GDBusInterfaceInfo *interface_info,
4895 const GDBusMethodInfo *method_info,
4896 const GDBusPropertyInfo *property_info,
4897 GVariant *parameters,
4898 const GDBusInterfaceVTable *vtable,
4899 GMainContext *main_context,
4902 GDBusMethodInvocation *invocation;
4903 GSource *idle_source;
4905 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4906 g_dbus_message_get_path (message),
4907 g_dbus_message_get_interface (message),
4908 g_dbus_message_get_member (message),
4916 /* TODO: would be nicer with a real MethodData like we already
4917 * have PropertyData and PropertyGetAllData... */
4918 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4919 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4920 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4922 idle_source = g_idle_source_new ();
4923 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4924 g_source_set_callback (idle_source,
4928 g_source_attach (idle_source, main_context);
4929 g_source_unref (idle_source);
4932 /* called in GDBusWorker thread with connection's lock held */
4934 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4935 GDBusMessage *message,
4936 guint registration_id,
4937 guint subtree_registration_id,
4938 GDBusInterfaceInfo *interface_info,
4939 const GDBusInterfaceVTable *vtable,
4940 GMainContext *main_context,
4943 GDBusMethodInfo *method_info;
4944 GDBusMessage *reply;
4945 GVariant *parameters;
4947 GVariantType *in_type;
4951 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4952 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4954 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4955 * error to the caller
4957 if (method_info == NULL)
4959 reply = g_dbus_message_new_method_error (message,
4960 "org.freedesktop.DBus.Error.UnknownMethod",
4961 _("No such method '%s'"),
4962 g_dbus_message_get_member (message));
4963 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4964 g_object_unref (reply);
4969 parameters = g_dbus_message_get_body (message);
4970 if (parameters == NULL)
4972 parameters = g_variant_new ("()");
4973 g_variant_ref_sink (parameters);
4977 g_variant_ref (parameters);
4980 /* Check that the incoming args are of the right type - if they are not, return
4981 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4983 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4984 if (!g_variant_is_of_type (parameters, in_type))
4988 type_string = g_variant_type_dup_string (in_type);
4990 reply = g_dbus_message_new_method_error (message,
4991 "org.freedesktop.DBus.Error.InvalidArgs",
4992 _("Type of message, '%s', does not match expected type '%s'"),
4993 g_variant_get_type_string (parameters),
4995 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4996 g_variant_type_free (in_type);
4997 g_variant_unref (parameters);
4998 g_object_unref (reply);
4999 g_free (type_string);
5003 g_variant_type_free (in_type);
5005 /* schedule the call in idle */
5006 schedule_method_call (connection, message, registration_id, subtree_registration_id,
5007 interface_info, method_info, NULL, parameters,
5008 vtable, main_context, user_data);
5009 g_variant_unref (parameters);
5016 /* ---------------------------------------------------------------------------------------------------- */
5018 /* called in GDBusWorker thread with connection's lock held */
5020 obj_message_func (GDBusConnection *connection,
5022 GDBusMessage *message)
5024 const gchar *interface_name;
5025 const gchar *member;
5026 const gchar *signature;
5031 interface_name = g_dbus_message_get_interface (message);
5032 member = g_dbus_message_get_member (message);
5033 signature = g_dbus_message_get_signature (message);
5035 /* see if we have an interface for handling this call */
5036 if (interface_name != NULL)
5038 ExportedInterface *ei;
5039 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5042 /* we do - invoke the handler in idle in the right thread */
5044 /* handle no vtable or handler being present */
5045 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
5048 handled = validate_and_maybe_schedule_method_call (connection,
5060 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5061 g_strcmp0 (member, "Introspect") == 0 &&
5062 g_strcmp0 (signature, "") == 0)
5064 handled = handle_introspect (connection, eo, message);
5067 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5068 g_strcmp0 (member, "Get") == 0 &&
5069 g_strcmp0 (signature, "ss") == 0)
5071 handled = handle_getset_property (connection, eo, message, TRUE);
5074 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5075 g_strcmp0 (member, "Set") == 0 &&
5076 g_strcmp0 (signature, "ssv") == 0)
5078 handled = handle_getset_property (connection, eo, message, FALSE);
5081 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5082 g_strcmp0 (member, "GetAll") == 0 &&
5083 g_strcmp0 (signature, "s") == 0)
5085 handled = handle_get_all_properties (connection, eo, message);
5094 * g_dbus_connection_register_object:
5095 * @connection: a #GDBusConnection
5096 * @object_path: the object path to register at
5097 * @interface_info: introspection data for the interface
5098 * @vtable: (allow-none): a #GDBusInterfaceVTable to call into or %NULL
5099 * @user_data: (allow-none): data to pass to functions in @vtable
5100 * @user_data_free_func: function to call when the object path is unregistered
5101 * @error: return location for error or %NULL
5103 * Registers callbacks for exported objects at @object_path with the
5104 * D-Bus interface that is described in @interface_info.
5106 * Calls to functions in @vtable (and @user_data_free_func) will happen
5108 * [thread-default main context][g-main-context-push-thread-default]
5109 * of the thread you are calling this method from.
5111 * Note that all #GVariant values passed to functions in @vtable will match
5112 * the signature given in @interface_info - if a remote caller passes
5113 * incorrect values, the `org.freedesktop.DBus.Error.InvalidArgs`
5114 * is returned to the remote caller.
5116 * Additionally, if the remote caller attempts to invoke methods or
5117 * access properties not mentioned in @interface_info the
5118 * `org.freedesktop.DBus.Error.UnknownMethod` resp.
5119 * `org.freedesktop.DBus.Error.InvalidArgs` errors
5120 * are returned to the caller.
5122 * It is considered a programming error if the
5123 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
5124 * #GVariant of incorrect type.
5126 * If an existing callback is already registered at @object_path and
5127 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
5129 * GDBus automatically implements the standard D-Bus interfaces
5130 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
5131 * and org.freedesktop.Peer, so you don't have to implement those for the
5132 * objects you export. You can implement org.freedesktop.DBus.Properties
5133 * yourself, e.g. to handle getting and setting of properties asynchronously.
5135 * Note that the reference count on @interface_info will be
5136 * incremented by 1 (unless allocated statically, e.g. if the
5137 * reference count is -1, see g_dbus_interface_info_ref()) for as long
5138 * as the object is exported. Also note that @vtable will be copied.
5140 * See this [server][gdbus-server] for an example of how to use this method.
5142 * Returns: 0 if @error is set, otherwise a registration id (never 0)
5143 * that can be used with g_dbus_connection_unregister_object()
5148 g_dbus_connection_register_object (GDBusConnection *connection,
5149 const gchar *object_path,
5150 GDBusInterfaceInfo *interface_info,
5151 const GDBusInterfaceVTable *vtable,
5153 GDestroyNotify user_data_free_func,
5157 ExportedInterface *ei;
5160 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5161 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5162 g_return_val_if_fail (interface_info != NULL, 0);
5163 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
5164 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5165 g_return_val_if_fail (check_initialized (connection), 0);
5169 CONNECTION_LOCK (connection);
5171 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5174 eo = g_new0 (ExportedObject, 1);
5175 eo->object_path = g_strdup (object_path);
5176 eo->connection = connection;
5177 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
5180 (GDestroyNotify) exported_interface_free);
5181 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
5184 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
5190 _("An object is already exported for the interface %s at %s"),
5191 interface_info->name,
5196 ei = g_new0 (ExportedInterface, 1);
5197 ei->id = _global_registration_id++; /* TODO: overflow etc. */
5199 ei->user_data = user_data;
5200 ei->user_data_free_func = user_data_free_func;
5201 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
5202 ei->interface_info = g_dbus_interface_info_ref (interface_info);
5203 g_dbus_interface_info_cache_build (ei->interface_info);
5204 ei->interface_name = g_strdup (interface_info->name);
5205 ei->context = g_main_context_ref_thread_default ();
5207 g_hash_table_insert (eo->map_if_name_to_ei,
5208 (gpointer) ei->interface_name,
5210 g_hash_table_insert (connection->map_id_to_ei,
5211 GUINT_TO_POINTER (ei->id),
5217 CONNECTION_UNLOCK (connection);
5223 * g_dbus_connection_unregister_object:
5224 * @connection: a #GDBusConnection
5225 * @registration_id: a registration id obtained from
5226 * g_dbus_connection_register_object()
5228 * Unregisters an object.
5230 * Returns: %TRUE if the object was unregistered, %FALSE otherwise
5235 g_dbus_connection_unregister_object (GDBusConnection *connection,
5236 guint registration_id)
5238 ExportedInterface *ei;
5242 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5243 g_return_val_if_fail (check_initialized (connection), FALSE);
5247 CONNECTION_LOCK (connection);
5249 ei = g_hash_table_lookup (connection->map_id_to_ei,
5250 GUINT_TO_POINTER (registration_id));
5256 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5257 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5258 /* unregister object path if we have no more exported interfaces */
5259 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5260 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5266 CONNECTION_UNLOCK (connection);
5271 /* ---------------------------------------------------------------------------------------------------- */
5274 * g_dbus_connection_emit_signal:
5275 * @connection: a #GDBusConnection
5276 * @destination_bus_name: (allow-none): the unique bus name for the destination
5277 * for the signal or %NULL to emit to all listeners
5278 * @object_path: path of remote object
5279 * @interface_name: D-Bus interface to emit a signal on
5280 * @signal_name: the name of the signal to emit
5281 * @parameters: (allow-none): a #GVariant tuple with parameters for the signal
5282 * or %NULL if not passing parameters
5283 * @error: Return location for error or %NULL
5287 * If the parameters GVariant is floating, it is consumed.
5289 * This can only fail if @parameters is not compatible with the D-Bus protocol.
5291 * Returns: %TRUE unless @error is set
5296 g_dbus_connection_emit_signal (GDBusConnection *connection,
5297 const gchar *destination_bus_name,
5298 const gchar *object_path,
5299 const gchar *interface_name,
5300 const gchar *signal_name,
5301 GVariant *parameters,
5304 GDBusMessage *message;
5310 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5311 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5312 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5313 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5314 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5315 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5316 g_return_val_if_fail (check_initialized (connection), FALSE);
5318 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5320 _g_dbus_debug_print_lock ();
5321 g_print ("========================================================================\n"
5322 "GDBus-debug:Emission:\n"
5323 " >>>> SIGNAL EMISSION %s.%s()\n"
5325 " destination %s\n",
5326 interface_name, signal_name,
5328 destination_bus_name != NULL ? destination_bus_name : "(none)");
5329 _g_dbus_debug_print_unlock ();
5332 message = g_dbus_message_new_signal (object_path,
5336 if (destination_bus_name != NULL)
5337 g_dbus_message_set_header (message,
5338 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5339 g_variant_new_string (destination_bus_name));
5341 if (parameters != NULL)
5342 g_dbus_message_set_body (message, parameters);
5344 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5345 g_object_unref (message);
5351 add_call_flags (GDBusMessage *message,
5352 GDBusCallFlags flags)
5354 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5355 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
5359 decode_method_reply (GDBusMessage *reply,
5360 const gchar *method_name,
5361 const GVariantType *reply_type,
5362 GUnixFDList **out_fd_list,
5368 switch (g_dbus_message_get_message_type (reply))
5370 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5371 result = g_dbus_message_get_body (reply);
5374 result = g_variant_new ("()");
5375 g_variant_ref_sink (result);
5379 g_variant_ref (result);
5382 if (!g_variant_is_of_type (result, reply_type))
5384 gchar *type_string = g_variant_type_dup_string (reply_type);
5388 G_IO_ERROR_INVALID_ARGUMENT,
5389 _("Method '%s' returned type '%s', but expected '%s'"),
5390 method_name, g_variant_get_type_string (result), type_string);
5392 g_variant_unref (result);
5393 g_free (type_string);
5400 if (out_fd_list != NULL)
5402 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5403 if (*out_fd_list != NULL)
5404 g_object_ref (*out_fd_list);
5410 case G_DBUS_MESSAGE_TYPE_ERROR:
5411 g_dbus_message_to_gerror (reply, error);
5415 g_assert_not_reached ();
5425 GSimpleAsyncResult *simple;
5426 GVariantType *reply_type;
5427 gchar *method_name; /* for error message */
5431 GUnixFDList *fd_list;
5435 call_state_free (CallState *state)
5437 g_variant_type_free (state->reply_type);
5438 g_free (state->method_name);
5440 if (state->value != NULL)
5441 g_variant_unref (state->value);
5442 if (state->fd_list != NULL)
5443 g_object_unref (state->fd_list);
5444 g_slice_free (CallState, state);
5447 /* called in any thread, with the connection's lock not held */
5449 g_dbus_connection_call_done (GObject *source,
5450 GAsyncResult *result,
5453 GSimpleAsyncResult *simple;
5454 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5455 CallState *state = user_data;
5457 GDBusMessage *reply;
5460 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5464 if (G_UNLIKELY (_g_dbus_debug_call ()))
5466 _g_dbus_debug_print_lock ();
5467 g_print ("========================================================================\n"
5468 "GDBus-debug:Call:\n"
5469 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5475 g_print ("SUCCESS\n");
5479 g_print ("FAILED: %s\n",
5482 _g_dbus_debug_print_unlock ();
5486 state->value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5488 simple = state->simple; /* why? because state is freed before we unref simple.. */
5491 g_simple_async_result_take_error (state->simple, error);
5492 g_simple_async_result_complete (state->simple);
5493 call_state_free (state);
5497 g_simple_async_result_set_op_res_gpointer (state->simple, state, (GDestroyNotify) call_state_free);
5498 g_simple_async_result_complete (state->simple);
5500 g_clear_object (&reply);
5501 g_object_unref (simple);
5504 /* called in any thread, with the connection's lock not held */
5506 g_dbus_connection_call_internal (GDBusConnection *connection,
5507 const gchar *bus_name,
5508 const gchar *object_path,
5509 const gchar *interface_name,
5510 const gchar *method_name,
5511 GVariant *parameters,
5512 const GVariantType *reply_type,
5513 GDBusCallFlags flags,
5515 GUnixFDList *fd_list,
5516 GCancellable *cancellable,
5517 GAsyncReadyCallback callback,
5520 GDBusMessage *message;
5523 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5524 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5525 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5526 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5527 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5528 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5529 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5530 g_return_if_fail (check_initialized (connection));
5532 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5534 g_return_if_fail (fd_list == NULL);
5537 message = g_dbus_message_new_method_call (bus_name,
5541 add_call_flags (message, flags);
5542 if (parameters != NULL)
5543 g_dbus_message_set_body (message, parameters);
5546 if (fd_list != NULL)
5547 g_dbus_message_set_unix_fd_list (message, fd_list);
5550 /* If the user has no callback then we can just send the message with
5551 * the G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set and skip all
5552 * the logic for processing the reply. If the service sends the reply
5553 * anyway then it will just be ignored.
5555 if (callback != NULL)
5559 state = g_slice_new0 (CallState);
5560 state->simple = g_simple_async_result_new (G_OBJECT (connection),
5561 callback, user_data,
5562 g_dbus_connection_call_internal);
5563 g_simple_async_result_set_check_cancellable (state->simple, cancellable);
5564 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5566 if (reply_type == NULL)
5567 reply_type = G_VARIANT_TYPE_ANY;
5569 state->reply_type = g_variant_type_copy (reply_type);
5571 g_dbus_connection_send_message_with_reply (connection,
5573 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5577 g_dbus_connection_call_done,
5579 serial = state->serial;
5583 GDBusMessageFlags flags;
5585 flags = g_dbus_message_get_flags (message);
5586 flags |= G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
5587 g_dbus_message_set_flags (message, flags);
5589 g_dbus_connection_send_message (connection,
5591 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5595 if (G_UNLIKELY (_g_dbus_debug_call ()))
5597 _g_dbus_debug_print_lock ();
5598 g_print ("========================================================================\n"
5599 "GDBus-debug:Call:\n"
5600 " >>>> ASYNC %s.%s()\n"
5602 " owned by name %s (serial %d)\n",
5606 bus_name != NULL ? bus_name : "(none)",
5608 _g_dbus_debug_print_unlock ();
5611 if (message != NULL)
5612 g_object_unref (message);
5615 /* called in any thread, with the connection's lock not held */
5617 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
5618 GUnixFDList **out_fd_list,
5622 GSimpleAsyncResult *simple;
5625 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5626 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
5627 g_dbus_connection_call_internal), NULL);
5628 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5630 simple = G_SIMPLE_ASYNC_RESULT (res);
5632 if (g_simple_async_result_propagate_error (simple, error))
5635 state = g_simple_async_result_get_op_res_gpointer (simple);
5636 if (out_fd_list != NULL)
5637 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
5638 return g_variant_ref (state->value);
5641 /* called in any user thread, with the connection's lock not held */
5643 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
5644 const gchar *bus_name,
5645 const gchar *object_path,
5646 const gchar *interface_name,
5647 const gchar *method_name,
5648 GVariant *parameters,
5649 const GVariantType *reply_type,
5650 GDBusCallFlags flags,
5652 GUnixFDList *fd_list,
5653 GUnixFDList **out_fd_list,
5654 GCancellable *cancellable,
5657 GDBusMessage *message;
5658 GDBusMessage *reply;
5660 GError *local_error;
5661 GDBusSendMessageFlags send_flags;
5667 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5668 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5669 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5670 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5671 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5672 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5673 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5675 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
5677 g_return_val_if_fail (fd_list == NULL, NULL);
5679 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5681 if (!(flags & CALL_FLAGS_INITIALIZING))
5682 g_return_val_if_fail (check_initialized (connection), FALSE);
5684 if (reply_type == NULL)
5685 reply_type = G_VARIANT_TYPE_ANY;
5687 message = g_dbus_message_new_method_call (bus_name,
5691 add_call_flags (message, flags);
5692 if (parameters != NULL)
5693 g_dbus_message_set_body (message, parameters);
5696 if (fd_list != NULL)
5697 g_dbus_message_set_unix_fd_list (message, fd_list);
5700 if (G_UNLIKELY (_g_dbus_debug_call ()))
5702 _g_dbus_debug_print_lock ();
5703 g_print ("========================================================================\n"
5704 "GDBus-debug:Call:\n"
5705 " >>>> SYNC %s.%s()\n"
5707 " owned by name %s\n",
5711 bus_name != NULL ? bus_name : "(none)");
5712 _g_dbus_debug_print_unlock ();
5717 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
5719 /* translate from one flavour of flags to another... */
5720 if (flags & CALL_FLAGS_INITIALIZING)
5721 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
5723 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5727 NULL, /* volatile guint32 *out_serial */
5731 if (G_UNLIKELY (_g_dbus_debug_call ()))
5733 _g_dbus_debug_print_lock ();
5734 g_print ("========================================================================\n"
5735 "GDBus-debug:Call:\n"
5736 " <<<< SYNC COMPLETE %s.%s()\n"
5742 g_print ("SUCCESS\n");
5746 g_print ("FAILED: %s\n",
5747 local_error->message);
5749 _g_dbus_debug_print_unlock ();
5755 *error = local_error;
5757 g_error_free (local_error);
5761 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
5764 if (message != NULL)
5765 g_object_unref (message);
5767 g_object_unref (reply);
5772 /* ---------------------------------------------------------------------------------------------------- */
5775 * g_dbus_connection_call:
5776 * @connection: a #GDBusConnection
5777 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
5778 * @connection is not a message bus connection
5779 * @object_path: path of remote object
5780 * @interface_name: D-Bus interface to invoke method on
5781 * @method_name: the name of the method to invoke
5782 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
5783 * or %NULL if not passing parameters
5784 * @reply_type: (allow-none): the expected type of the reply, or %NULL
5785 * @flags: flags from the #GDBusCallFlags enumeration
5786 * @timeout_msec: the timeout in milliseconds, -1 to use the default
5787 * timeout or %G_MAXINT for no timeout
5788 * @cancellable: (allow-none): a #GCancellable or %NULL
5789 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request
5790 * is satisfied or %NULL if you don't care about the result of the
5792 * @user_data: the data to pass to @callback
5794 * Asynchronously invokes the @method_name method on the
5795 * @interface_name D-Bus interface on the remote object at
5796 * @object_path owned by @bus_name.
5798 * If @connection is closed then the operation will fail with
5799 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
5800 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
5801 * not compatible with the D-Bus protocol, the operation fails with
5802 * %G_IO_ERROR_INVALID_ARGUMENT.
5804 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
5805 * error will be raised if it does not match. Said another way, if you give a @reply_type
5806 * then any non-%NULL return value will be of this type.
5808 * If the @parameters #GVariant is floating, it is consumed. This allows
5809 * convenient 'inline' use of g_variant_new(), e.g.:
5810 * |[<!-- language="C" -->
5811 * g_dbus_connection_call (connection,
5812 * "org.freedesktop.StringThings",
5813 * "/org/freedesktop/StringThings",
5814 * "org.freedesktop.StringThings",
5816 * g_variant_new ("(ss)",
5820 * G_DBUS_CALL_FLAGS_NONE,
5823 * (GAsyncReadyCallback) two_strings_done,
5827 * This is an asynchronous method. When the operation is finished,
5828 * @callback will be invoked in the
5829 * [thread-default main context][g-main-context-push-thread-default]
5830 * of the thread you are calling this method from. You can then call
5831 * g_dbus_connection_call_finish() to get the result of the operation.
5832 * See g_dbus_connection_call_sync() for the synchronous version of this
5835 * If @callback is %NULL then the D-Bus method call message will be sent with
5836 * the %G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set.
5841 g_dbus_connection_call (GDBusConnection *connection,
5842 const gchar *bus_name,
5843 const gchar *object_path,
5844 const gchar *interface_name,
5845 const gchar *method_name,
5846 GVariant *parameters,
5847 const GVariantType *reply_type,
5848 GDBusCallFlags flags,
5850 GCancellable *cancellable,
5851 GAsyncReadyCallback callback,
5854 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);
5858 * g_dbus_connection_call_finish:
5859 * @connection: a #GDBusConnection
5860 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call()
5861 * @error: return location for error or %NULL
5863 * Finishes an operation started with g_dbus_connection_call().
5865 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5866 * return values. Free with g_variant_unref().
5871 g_dbus_connection_call_finish (GDBusConnection *connection,
5875 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
5879 * g_dbus_connection_call_sync:
5880 * @connection: a #GDBusConnection
5881 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
5882 * @connection is not a message bus connection
5883 * @object_path: path of remote object
5884 * @interface_name: D-Bus interface to invoke method on
5885 * @method_name: the name of the method to invoke
5886 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
5887 * or %NULL if not passing parameters
5888 * @reply_type: (allow-none): the expected type of the reply, or %NULL
5889 * @flags: flags from the #GDBusCallFlags enumeration
5890 * @timeout_msec: the timeout in milliseconds, -1 to use the default
5891 * timeout or %G_MAXINT for no timeout
5892 * @cancellable: (allow-none): a #GCancellable or %NULL
5893 * @error: return location for error or %NULL
5895 * Synchronously invokes the @method_name method on the
5896 * @interface_name D-Bus interface on the remote object at
5897 * @object_path owned by @bus_name.
5899 * If @connection is closed then the operation will fail with
5900 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
5901 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
5902 * contains a value not compatible with the D-Bus protocol, the operation
5903 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
5905 * If @reply_type is non-%NULL then the reply will be checked for having
5906 * this type and an error will be raised if it does not match. Said
5907 * another way, if you give a @reply_type then any non-%NULL return
5908 * value will be of this type.
5910 * If the @parameters #GVariant is floating, it is consumed.
5911 * This allows convenient 'inline' use of g_variant_new(), e.g.:
5912 * |[<!-- language="C" -->
5913 * g_dbus_connection_call_sync (connection,
5914 * "org.freedesktop.StringThings",
5915 * "/org/freedesktop/StringThings",
5916 * "org.freedesktop.StringThings",
5918 * g_variant_new ("(ss)",
5922 * G_DBUS_CALL_FLAGS_NONE,
5928 * The calling thread is blocked until a reply is received. See
5929 * g_dbus_connection_call() for the asynchronous version of
5932 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5933 * return values. Free with g_variant_unref().
5938 g_dbus_connection_call_sync (GDBusConnection *connection,
5939 const gchar *bus_name,
5940 const gchar *object_path,
5941 const gchar *interface_name,
5942 const gchar *method_name,
5943 GVariant *parameters,
5944 const GVariantType *reply_type,
5945 GDBusCallFlags flags,
5947 GCancellable *cancellable,
5950 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);
5953 /* ---------------------------------------------------------------------------------------------------- */
5958 * g_dbus_connection_call_with_unix_fd_list:
5959 * @connection: a #GDBusConnection
5960 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
5961 * @connection is not a message bus connection
5962 * @object_path: path of remote object
5963 * @interface_name: D-Bus interface to invoke method on
5964 * @method_name: the name of the method to invoke
5965 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
5966 * or %NULL if not passing parameters
5967 * @reply_type: (allow-none): the expected type of the reply, or %NULL
5968 * @flags: flags from the #GDBusCallFlags enumeration
5969 * @timeout_msec: the timeout in milliseconds, -1 to use the default
5970 * timeout or %G_MAXINT for no timeout
5971 * @fd_list: (allow-none): a #GUnixFDList or %NULL
5972 * @cancellable: (allow-none): a #GCancellable or %NULL
5973 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request is
5974 * satisfied or %NULL if you don't * care about the result of the
5976 * @user_data: The data to pass to @callback.
5978 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
5980 * This method is only available on UNIX.
5985 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
5986 const gchar *bus_name,
5987 const gchar *object_path,
5988 const gchar *interface_name,
5989 const gchar *method_name,
5990 GVariant *parameters,
5991 const GVariantType *reply_type,
5992 GDBusCallFlags flags,
5994 GUnixFDList *fd_list,
5995 GCancellable *cancellable,
5996 GAsyncReadyCallback callback,
5999 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);
6003 * g_dbus_connection_call_with_unix_fd_list_finish:
6004 * @connection: a #GDBusConnection
6005 * @out_fd_list: (out) (allow-none): return location for a #GUnixFDList or %NULL
6006 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
6007 * g_dbus_connection_call_with_unix_fd_list()
6008 * @error: return location for error or %NULL
6010 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
6012 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6013 * return values. Free with g_variant_unref().
6018 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
6019 GUnixFDList **out_fd_list,
6023 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
6027 * g_dbus_connection_call_with_unix_fd_list_sync:
6028 * @connection: a #GDBusConnection
6029 * @bus_name: (allow-none): a unique or well-known bus name or %NULL
6030 * if @connection is not a message bus connection
6031 * @object_path: path of remote object
6032 * @interface_name: D-Bus interface to invoke method on
6033 * @method_name: the name of the method to invoke
6034 * @parameters: (allow-none): a #GVariant tuple with parameters for
6035 * the method or %NULL if not passing parameters
6036 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6037 * @flags: flags from the #GDBusCallFlags enumeration
6038 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6039 * timeout or %G_MAXINT for no timeout
6040 * @fd_list: (allow-none): a #GUnixFDList or %NULL
6041 * @out_fd_list: (out) (allow-none): return location for a #GUnixFDList or %NULL
6042 * @cancellable: (allow-none): a #GCancellable or %NULL
6043 * @error: return location for error or %NULL
6045 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
6047 * This method is only available on UNIX.
6049 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6050 * return values. Free with g_variant_unref().
6055 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
6056 const gchar *bus_name,
6057 const gchar *object_path,
6058 const gchar *interface_name,
6059 const gchar *method_name,
6060 GVariant *parameters,
6061 const GVariantType *reply_type,
6062 GDBusCallFlags flags,
6064 GUnixFDList *fd_list,
6065 GUnixFDList **out_fd_list,
6066 GCancellable *cancellable,
6069 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);
6072 #endif /* G_OS_UNIX */
6074 /* ---------------------------------------------------------------------------------------------------- */
6076 struct ExportedSubtree
6080 GDBusConnection *connection;
6081 GDBusSubtreeVTable *vtable;
6082 GDBusSubtreeFlags flags;
6084 GMainContext *context;
6086 GDestroyNotify user_data_free_func;
6090 exported_subtree_free (ExportedSubtree *es)
6092 call_destroy_notify (es->context,
6093 es->user_data_free_func,
6096 g_main_context_unref (es->context);
6098 _g_dbus_subtree_vtable_free (es->vtable);
6099 g_free (es->object_path);
6103 /* called without lock held in the thread where the caller registered
6107 handle_subtree_introspect (GDBusConnection *connection,
6108 ExportedSubtree *es,
6109 GDBusMessage *message)
6113 GDBusMessage *reply;
6116 const gchar *sender;
6117 const gchar *requested_object_path;
6118 const gchar *requested_node;
6119 GDBusInterfaceInfo **interfaces;
6121 gchar **subnode_paths;
6122 gboolean has_properties_interface;
6123 gboolean has_introspectable_interface;
6127 requested_object_path = g_dbus_message_get_path (message);
6128 sender = g_dbus_message_get_sender (message);
6129 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6131 s = g_string_new (NULL);
6132 introspect_append_header (s);
6134 /* Strictly we don't need the children in dynamic mode, but we avoid the
6135 * conditionals to preserve code clarity
6137 children = es->vtable->enumerate (es->connection,
6144 requested_node = strrchr (requested_object_path, '/') + 1;
6146 /* Assert existence of object if we are not dynamic */
6147 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
6148 !_g_strv_has_string ((const gchar * const *) children, requested_node))
6153 requested_node = NULL;
6156 interfaces = es->vtable->introspect (es->connection,
6161 if (interfaces != NULL)
6163 has_properties_interface = FALSE;
6164 has_introspectable_interface = FALSE;
6166 for (n = 0; interfaces[n] != NULL; n++)
6168 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
6169 has_properties_interface = TRUE;
6170 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
6171 has_introspectable_interface = TRUE;
6173 if (!has_properties_interface)
6174 g_string_append (s, introspect_properties_interface);
6175 if (!has_introspectable_interface)
6176 g_string_append (s, introspect_introspectable_interface);
6178 for (n = 0; interfaces[n] != NULL; n++)
6180 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
6181 g_dbus_interface_info_unref (interfaces[n]);
6183 g_free (interfaces);
6186 /* then include <node> entries from the Subtree for the root */
6189 for (n = 0; children != NULL && children[n] != NULL; n++)
6190 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
6193 /* finally include nodes registered below us */
6194 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
6195 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
6196 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
6197 g_strfreev (subnode_paths);
6199 g_string_append (s, "</node>\n");
6201 reply = g_dbus_message_new_method_reply (message);
6202 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6203 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6204 g_object_unref (reply);
6209 g_string_free (s, TRUE);
6210 g_strfreev (children);
6214 /* called without lock held in the thread where the caller registered
6218 handle_subtree_method_invocation (GDBusConnection *connection,
6219 ExportedSubtree *es,
6220 GDBusMessage *message)
6223 const gchar *sender;
6224 const gchar *interface_name;
6225 const gchar *member;
6226 const gchar *signature;
6227 const gchar *requested_object_path;
6228 const gchar *requested_node;
6230 GDBusInterfaceInfo *interface_info;
6231 const GDBusInterfaceVTable *interface_vtable;
6232 gpointer interface_user_data;
6234 GDBusInterfaceInfo **interfaces;
6235 gboolean is_property_get;
6236 gboolean is_property_set;
6237 gboolean is_property_get_all;
6242 requested_object_path = g_dbus_message_get_path (message);
6243 sender = g_dbus_message_get_sender (message);
6244 interface_name = g_dbus_message_get_interface (message);
6245 member = g_dbus_message_get_member (message);
6246 signature = g_dbus_message_get_signature (message);
6247 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6249 is_property_get = FALSE;
6250 is_property_set = FALSE;
6251 is_property_get_all = FALSE;
6252 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6254 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6255 is_property_get = TRUE;
6256 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6257 is_property_set = TRUE;
6258 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6259 is_property_get_all = TRUE;
6264 requested_node = strrchr (requested_object_path, '/') + 1;
6266 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6268 /* We don't want to dispatch to unenumerated
6269 * nodes, so ensure that the child exists.
6274 children = es->vtable->enumerate (es->connection,
6279 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6280 g_strfreev (children);
6288 requested_node = NULL;
6291 /* get introspection data for the node */
6292 interfaces = es->vtable->introspect (es->connection,
6294 requested_object_path,
6298 if (interfaces == NULL)
6301 interface_info = NULL;
6302 for (n = 0; interfaces[n] != NULL; n++)
6304 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6305 interface_info = interfaces[n];
6308 /* dispatch the call if the user wants to handle it */
6309 if (interface_info != NULL)
6311 /* figure out where to dispatch the method call */
6312 interface_user_data = NULL;
6313 interface_vtable = es->vtable->dispatch (es->connection,
6318 &interface_user_data,
6320 if (interface_vtable == NULL)
6323 CONNECTION_LOCK (connection);
6324 handled = validate_and_maybe_schedule_method_call (es->connection,
6331 interface_user_data);
6332 CONNECTION_UNLOCK (connection);
6334 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6335 else if (is_property_get || is_property_set || is_property_get_all)
6337 if (is_property_get)
6338 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6339 else if (is_property_set)
6340 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6341 else if (is_property_get_all)
6342 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6344 g_assert_not_reached ();
6346 /* see if the object supports this interface at all */
6347 for (n = 0; interfaces[n] != NULL; n++)
6349 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6350 interface_info = interfaces[n];
6353 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6354 * claims it won't support the interface
6356 if (interface_info == NULL)
6358 GDBusMessage *reply;
6359 reply = g_dbus_message_new_method_error (message,
6360 "org.freedesktop.DBus.Error.InvalidArgs",
6361 _("No such interface '%s'"),
6363 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6364 g_object_unref (reply);
6369 /* figure out where to dispatch the property get/set/getall calls */
6370 interface_user_data = NULL;
6371 interface_vtable = es->vtable->dispatch (es->connection,
6376 &interface_user_data,
6378 if (interface_vtable == NULL)
6380 g_warning ("The subtree introspection function indicates that '%s' "
6381 "is a valid interface name, but calling the dispatch "
6382 "function on that interface gave us NULL", interface_name);
6386 if (is_property_get || is_property_set)
6388 CONNECTION_LOCK (connection);
6389 handled = validate_and_maybe_schedule_property_getset (es->connection,
6397 interface_user_data);
6398 CONNECTION_UNLOCK (connection);
6400 else if (is_property_get_all)
6402 CONNECTION_LOCK (connection);
6403 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6410 interface_user_data);
6411 CONNECTION_UNLOCK (connection);
6416 if (interfaces != NULL)
6418 for (n = 0; interfaces[n] != NULL; n++)
6419 g_dbus_interface_info_unref (interfaces[n]);
6420 g_free (interfaces);
6428 GDBusMessage *message;
6429 ExportedSubtree *es;
6430 } SubtreeDeferredData;
6433 subtree_deferred_data_free (SubtreeDeferredData *data)
6435 g_object_unref (data->message);
6439 /* called without lock held in the thread where the caller registered the subtree */
6441 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6443 SubtreeDeferredData *data = _data;
6448 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6449 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6450 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6451 handled = handle_subtree_introspect (data->es->connection,
6455 handled = handle_subtree_method_invocation (data->es->connection,
6461 CONNECTION_LOCK (data->es->connection);
6462 handled = handle_generic_unlocked (data->es->connection, data->message);
6463 CONNECTION_UNLOCK (data->es->connection);
6466 /* if we couldn't handle the request, just bail with the UnknownMethod error */
6469 GDBusMessage *reply;
6470 reply = g_dbus_message_new_method_error (data->message,
6471 "org.freedesktop.DBus.Error.UnknownMethod",
6472 _("Method '%s' on interface '%s' with signature '%s' does not exist"),
6473 g_dbus_message_get_member (data->message),
6474 g_dbus_message_get_interface (data->message),
6475 g_dbus_message_get_signature (data->message));
6476 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6477 g_object_unref (reply);
6483 /* called in GDBusWorker thread with connection's lock held */
6485 subtree_message_func (GDBusConnection *connection,
6486 ExportedSubtree *es,
6487 GDBusMessage *message)
6489 GSource *idle_source;
6490 SubtreeDeferredData *data;
6492 data = g_new0 (SubtreeDeferredData, 1);
6493 data->message = g_object_ref (message);
6496 /* defer this call to an idle handler in the right thread */
6497 idle_source = g_idle_source_new ();
6498 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
6499 g_source_set_callback (idle_source,
6500 process_subtree_vtable_message_in_idle_cb,
6502 (GDestroyNotify) subtree_deferred_data_free);
6503 g_source_attach (idle_source, es->context);
6504 g_source_unref (idle_source);
6506 /* since we own the entire subtree, handlers for objects not in the subtree have been
6507 * tried already by libdbus-1 - so we just need to ensure that we're always going
6508 * to reply to the message
6514 * g_dbus_connection_register_subtree:
6515 * @connection: a #GDBusConnection
6516 * @object_path: the object path to register the subtree at
6517 * @vtable: a #GDBusSubtreeVTable to enumerate, introspect and
6518 * dispatch nodes in the subtree
6519 * @flags: flags used to fine tune the behavior of the subtree
6520 * @user_data: data to pass to functions in @vtable
6521 * @user_data_free_func: function to call when the subtree is unregistered
6522 * @error: return location for error or %NULL
6524 * Registers a whole subtree of dynamic objects.
6526 * The @enumerate and @introspection functions in @vtable are used to
6527 * convey, to remote callers, what nodes exist in the subtree rooted
6530 * When handling remote calls into any node in the subtree, first the
6531 * @enumerate function is used to check if the node exists. If the node exists
6532 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6533 * the @introspection function is used to check if the node supports the
6534 * requested method. If so, the @dispatch function is used to determine
6535 * where to dispatch the call. The collected #GDBusInterfaceVTable and
6536 * #gpointer will be used to call into the interface vtable for processing
6539 * All calls into user-provided code will be invoked in the
6540 * [thread-default main context][g-main-context-push-thread-default]
6541 * of the thread you are calling this method from.
6543 * If an existing subtree is already registered at @object_path or
6544 * then @error is set to #G_IO_ERROR_EXISTS.
6546 * Note that it is valid to register regular objects (using
6547 * g_dbus_connection_register_object()) in a subtree registered with
6548 * g_dbus_connection_register_subtree() - if so, the subtree handler
6549 * is tried as the last resort. One way to think about a subtree
6550 * handler is to consider it a fallback handler for object paths not
6551 * registered via g_dbus_connection_register_object() or other bindings.
6553 * Note that @vtable will be copied so you cannot change it after
6556 * See this [server][gdbus-subtree-server] for an example of how to use
6559 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
6560 * that can be used with g_dbus_connection_unregister_subtree() .
6565 g_dbus_connection_register_subtree (GDBusConnection *connection,
6566 const gchar *object_path,
6567 const GDBusSubtreeVTable *vtable,
6568 GDBusSubtreeFlags flags,
6570 GDestroyNotify user_data_free_func,
6574 ExportedSubtree *es;
6576 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
6577 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
6578 g_return_val_if_fail (vtable != NULL, 0);
6579 g_return_val_if_fail (error == NULL || *error == NULL, 0);
6580 g_return_val_if_fail (check_initialized (connection), 0);
6584 CONNECTION_LOCK (connection);
6586 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6592 _("A subtree is already exported for %s"),
6597 es = g_new0 (ExportedSubtree, 1);
6598 es->object_path = g_strdup (object_path);
6599 es->connection = connection;
6601 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
6603 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
6604 es->user_data = user_data;
6605 es->user_data_free_func = user_data_free_func;
6606 es->context = g_main_context_ref_thread_default ();
6608 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
6609 g_hash_table_insert (connection->map_id_to_es,
6610 GUINT_TO_POINTER (es->id),
6616 CONNECTION_UNLOCK (connection);
6621 /* ---------------------------------------------------------------------------------------------------- */
6624 * g_dbus_connection_unregister_subtree:
6625 * @connection: a #GDBusConnection
6626 * @registration_id: a subtree registration id obtained from
6627 * g_dbus_connection_register_subtree()
6629 * Unregisters a subtree.
6631 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise
6636 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
6637 guint registration_id)
6639 ExportedSubtree *es;
6642 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
6643 g_return_val_if_fail (check_initialized (connection), FALSE);
6647 CONNECTION_LOCK (connection);
6649 es = g_hash_table_lookup (connection->map_id_to_es,
6650 GUINT_TO_POINTER (registration_id));
6654 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
6655 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
6660 CONNECTION_UNLOCK (connection);
6665 /* ---------------------------------------------------------------------------------------------------- */
6667 /* may be called in any thread, with connection's lock held */
6669 handle_generic_ping_unlocked (GDBusConnection *connection,
6670 const gchar *object_path,
6671 GDBusMessage *message)
6673 GDBusMessage *reply;
6674 reply = g_dbus_message_new_method_reply (message);
6675 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6676 g_object_unref (reply);
6679 /* may be called in any thread, with connection's lock held */
6681 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
6682 const gchar *object_path,
6683 GDBusMessage *message)
6685 GDBusMessage *reply;
6688 if (connection->machine_id == NULL)
6693 connection->machine_id = _g_dbus_get_machine_id (&error);
6694 if (connection->machine_id == NULL)
6696 reply = g_dbus_message_new_method_error_literal (message,
6697 "org.freedesktop.DBus.Error.Failed",
6699 g_error_free (error);
6705 reply = g_dbus_message_new_method_reply (message);
6706 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
6708 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6709 g_object_unref (reply);
6712 /* may be called in any thread, with connection's lock held */
6714 handle_generic_introspect_unlocked (GDBusConnection *connection,
6715 const gchar *object_path,
6716 GDBusMessage *message)
6721 GDBusMessage *reply;
6723 /* first the header */
6724 s = g_string_new (NULL);
6725 introspect_append_header (s);
6727 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
6728 for (n = 0; registered != NULL && registered[n] != NULL; n++)
6729 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
6730 g_strfreev (registered);
6731 g_string_append (s, "</node>\n");
6733 reply = g_dbus_message_new_method_reply (message);
6734 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6735 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6736 g_object_unref (reply);
6737 g_string_free (s, TRUE);
6740 /* may be called in any thread, with connection's lock held */
6742 handle_generic_unlocked (GDBusConnection *connection,
6743 GDBusMessage *message)
6746 const gchar *interface_name;
6747 const gchar *member;
6748 const gchar *signature;
6751 CONNECTION_ENSURE_LOCK (connection);
6755 interface_name = g_dbus_message_get_interface (message);
6756 member = g_dbus_message_get_member (message);
6757 signature = g_dbus_message_get_signature (message);
6758 path = g_dbus_message_get_path (message);
6760 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
6761 g_strcmp0 (member, "Introspect") == 0 &&
6762 g_strcmp0 (signature, "") == 0)
6764 handle_generic_introspect_unlocked (connection, path, message);
6767 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6768 g_strcmp0 (member, "Ping") == 0 &&
6769 g_strcmp0 (signature, "") == 0)
6771 handle_generic_ping_unlocked (connection, path, message);
6774 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6775 g_strcmp0 (member, "GetMachineId") == 0 &&
6776 g_strcmp0 (signature, "") == 0)
6778 handle_generic_get_machine_id_unlocked (connection, path, message);
6785 /* ---------------------------------------------------------------------------------------------------- */
6787 /* called in GDBusWorker thread with connection's lock held */
6789 distribute_method_call (GDBusConnection *connection,
6790 GDBusMessage *message)
6792 GDBusMessage *reply;
6794 ExportedSubtree *es;
6795 const gchar *object_path;
6796 const gchar *interface_name;
6797 const gchar *member;
6799 gchar *subtree_path;
6802 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
6804 interface_name = g_dbus_message_get_interface (message);
6805 member = g_dbus_message_get_member (message);
6806 path = g_dbus_message_get_path (message);
6807 subtree_path = g_strdup (path);
6808 needle = strrchr (subtree_path, '/');
6809 if (needle != NULL && needle != subtree_path)
6815 g_free (subtree_path);
6816 subtree_path = NULL;
6820 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
6822 _g_dbus_debug_print_lock ();
6823 g_print ("========================================================================\n"
6824 "GDBus-debug:Incoming:\n"
6825 " <<<< METHOD INVOCATION %s.%s()\n"
6827 " invoked by name %s\n"
6829 interface_name, member,
6831 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
6832 g_dbus_message_get_serial (message));
6833 _g_dbus_debug_print_unlock ();
6836 object_path = g_dbus_message_get_path (message);
6837 g_assert (object_path != NULL);
6839 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
6842 if (obj_message_func (connection, eo, message))
6846 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6849 if (subtree_message_func (connection, es, message))
6853 if (subtree_path != NULL)
6855 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
6858 if (subtree_message_func (connection, es, message))
6863 if (handle_generic_unlocked (connection, message))
6866 /* if we end up here, the message has not been not handled - so return an error saying this */
6867 reply = g_dbus_message_new_method_error (message,
6868 "org.freedesktop.DBus.Error.UnknownMethod",
6869 _("No such interface '%s' on object at path %s"),
6872 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6873 g_object_unref (reply);
6876 g_free (subtree_path);
6879 /* ---------------------------------------------------------------------------------------------------- */
6881 /* Called in any user thread, with the message_bus_lock held. */
6883 message_bus_get_singleton (GBusType bus_type,
6887 const gchar *starter_bus;
6893 case G_BUS_TYPE_SESSION:
6894 ret = &the_session_bus;
6897 case G_BUS_TYPE_SYSTEM:
6898 ret = &the_system_bus;
6901 case G_BUS_TYPE_STARTER:
6902 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
6903 if (g_strcmp0 (starter_bus, "session") == 0)
6905 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
6908 else if (g_strcmp0 (starter_bus, "system") == 0)
6910 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
6915 if (starter_bus != NULL)
6919 G_IO_ERROR_INVALID_ARGUMENT,
6920 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
6921 " - unknown value '%s'"),
6926 g_set_error_literal (error,
6928 G_IO_ERROR_INVALID_ARGUMENT,
6929 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
6930 "variable is not set"));
6936 g_assert_not_reached ();
6944 /* Called in any user thread, without holding locks. */
6945 static GDBusConnection *
6946 get_uninitialized_connection (GBusType bus_type,
6947 GCancellable *cancellable,
6950 GWeakRef *singleton;
6951 GDBusConnection *ret;
6955 G_LOCK (message_bus_lock);
6956 singleton = message_bus_get_singleton (bus_type, error);
6957 if (singleton == NULL)
6960 ret = g_weak_ref_get (singleton);
6965 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
6966 if (address == NULL)
6968 ret = g_object_new (G_TYPE_DBUS_CONNECTION,
6970 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
6971 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
6972 "exit-on-close", TRUE,
6975 g_weak_ref_set (singleton, ret);
6979 g_assert (ret != NULL);
6982 G_UNLOCK (message_bus_lock);
6986 /* May be called from any thread. Must not hold message_bus_lock. */
6988 _g_bus_get_singleton_if_exists (GBusType bus_type)
6990 GWeakRef *singleton;
6991 GDBusConnection *ret = NULL;
6993 G_LOCK (message_bus_lock);
6994 singleton = message_bus_get_singleton (bus_type, NULL);
6995 if (singleton == NULL)
6998 ret = g_weak_ref_get (singleton);
7001 G_UNLOCK (message_bus_lock);
7007 * @bus_type: a #GBusType
7008 * @cancellable: (allow-none): a #GCancellable or %NULL
7009 * @error: return location for error or %NULL
7011 * Synchronously connects to the message bus specified by @bus_type.
7012 * Note that the returned object may shared with other callers,
7013 * e.g. if two separate parts of a process calls this function with
7014 * the same @bus_type, they will share the same object.
7016 * This is a synchronous failable function. See g_bus_get() and
7017 * g_bus_get_finish() for the asynchronous version.
7019 * The returned object is a singleton, that is, shared with other
7020 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7021 * event that you need a private message bus connection, use
7022 * g_dbus_address_get_for_bus_sync() and
7023 * g_dbus_connection_new_for_address().
7025 * Note that the returned #GDBusConnection object will (usually) have
7026 * the #GDBusConnection:exit-on-close property set to %TRUE.
7028 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7029 * Free with g_object_unref().
7034 g_bus_get_sync (GBusType bus_type,
7035 GCancellable *cancellable,
7038 GDBusConnection *connection;
7040 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7042 connection = get_uninitialized_connection (bus_type, cancellable, error);
7043 if (connection == NULL)
7046 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
7048 g_object_unref (connection);
7057 bus_get_async_initable_cb (GObject *source_object,
7061 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
7065 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
7069 g_assert (error != NULL);
7070 g_simple_async_result_take_error (simple, error);
7071 g_object_unref (source_object);
7075 g_simple_async_result_set_op_res_gpointer (simple,
7079 g_simple_async_result_complete_in_idle (simple);
7080 g_object_unref (simple);
7085 * @bus_type: a #GBusType
7086 * @cancellable: (allow-none): a #GCancellable or %NULL
7087 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
7088 * @user_data: the data to pass to @callback
7090 * Asynchronously connects to the message bus specified by @bus_type.
7092 * When the operation is finished, @callback will be invoked. You can
7093 * then call g_bus_get_finish() to get the result of the operation.
7095 * This is a asynchronous failable function. See g_bus_get_sync() for
7096 * the synchronous version.
7101 g_bus_get (GBusType bus_type,
7102 GCancellable *cancellable,
7103 GAsyncReadyCallback callback,
7106 GDBusConnection *connection;
7107 GSimpleAsyncResult *simple;
7110 simple = g_simple_async_result_new (NULL,
7114 g_simple_async_result_set_check_cancellable (simple, cancellable);
7117 connection = get_uninitialized_connection (bus_type, cancellable, &error);
7118 if (connection == NULL)
7120 g_assert (error != NULL);
7121 g_simple_async_result_take_error (simple, error);
7122 g_simple_async_result_complete_in_idle (simple);
7123 g_object_unref (simple);
7127 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
7130 bus_get_async_initable_cb,
7137 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
7139 * @error: return location for error or %NULL
7141 * Finishes an operation started with g_bus_get().
7143 * The returned object is a singleton, that is, shared with other
7144 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7145 * event that you need a private message bus connection, use
7146 * g_dbus_address_get_for_bus_sync() and
7147 * g_dbus_connection_new_for_address().
7149 * Note that the returned #GDBusConnection object will (usually) have
7150 * the #GDBusConnection:exit-on-close property set to %TRUE.
7152 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7153 * Free with g_object_unref().
7158 g_bus_get_finish (GAsyncResult *res,
7161 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
7163 GDBusConnection *ret;
7165 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7167 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
7171 if (g_simple_async_result_propagate_error (simple, error))
7174 object = g_simple_async_result_get_op_res_gpointer (simple);
7175 g_assert (object != NULL);
7176 ret = g_object_ref (G_DBUS_CONNECTION (object));
7182 /* ---------------------------------------------------------------------------------------------------- */