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, write to the
17 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18 * Boston, MA 02111-1307, USA.
20 * Author: David Zeuthen <davidz@redhat.com>
26 * - would be nice to expose GDBusAuthMechanism and an extension point
28 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
29 * the mechanism VFuncs need to be able to set an error.
31 * - Need to document other mechanisms/sources for determining the D-Bus
32 * address of a well-known bus.
34 * - e.g. on Win32 we need code like from here
36 * http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
38 * that was never copied over here because it originally was copy-paste
39 * from the GPLv2 / AFL 2.1 libdbus sources.
41 * - on OS X we need to look in launchd for the address
43 * https://bugs.freedesktop.org/show_bug.cgi?id=14259
45 * - on X11 we need to look in a X11 property on the X server
46 * - (we can also just use dbus-launch(1) from the D-Bus
49 * - (ideally) this requires D-Bus spec work because none of
50 * this has never really been specced out properly (except
53 * - Related to the above, we also need to be able to launch a message bus
54 * instance.... Since we don't want to write our own bus daemon we should
55 * launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
57 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
58 * to specify where the nonce is stored. This will allow people to use
59 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
60 * to easily achieve secure RPC via nonce-tcp.
62 * - need to expose an extension point for resolving D-Bus address and
63 * turning them into GIOStream objects. This will allow us to implement
64 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
66 * - see g_dbus_address_connect() in gdbusaddress.c
68 * - would be cute to use kernel-specific APIs to resolve fds for
69 * debug output when using G_DBUS_DEBUG=message, e.g. in addition to
71 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
73 * maybe we can show more information about what fd 21 really is.
74 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
75 * Initial experiments on Linux 2.6 suggests that the symlink looks
80 * e.g. not of much use.
82 * - GDBus High-Level docs
83 * - Proxy: properties, signals...
84 * - Connection: IOStream based, ::close, connection setup steps
85 * mainloop integration, threading
86 * - Differences from libdbus (extend "Migrating from")
87 * - the message handling thread
88 * - Using GVariant instead of GValue
89 * - Explain why the high-level API is a good thing and what
90 * kind of pitfalls it avoids
91 * - Export objects before claiming names
92 * - Talk about auto-starting services (cf. GBusNameWatcherFlags)
94 * - use abstract sockets in test code
95 * - right now it doesn't work, dbus-daemon(1) fails with
97 * /gdbus/connection/filter: Failed to start message bus: Failed to bind
98 * socket "/tmp/g-dbus-tests-pid-28531": Address already in use
99 * ** WARNING **: Error reading address from dbus daemon, 0 bytes read
109 #include "gdbusauth.h"
110 #include "gdbusutils.h"
111 #include "gdbusaddress.h"
112 #include "gdbusmessage.h"
113 #include "gdbusconnection.h"
114 #include "gdbuserror.h"
115 #include "gioenumtypes.h"
116 #include "gdbusintrospection.h"
117 #include "gdbusmethodinvocation.h"
118 #include "gdbusprivate.h"
119 #include "gdbusauthobserver.h"
120 #include "ginitable.h"
121 #include "gasyncinitable.h"
122 #include "giostream.h"
123 #include "gasyncresult.h"
124 #include "gsimpleasyncresult.h"
127 #include "gunixconnection.h"
128 #include "gunixfdmessage.h"
131 #include "glibintl.h"
134 * SECTION:gdbusconnection
135 * @short_description: D-Bus Connections
136 * @include: gio/gio.h
138 * The #GDBusConnection type is used for D-Bus connections to remote
139 * peers such as a message buses. It is a low-level API that offers a
140 * lot of flexibility. For instance, it lets you establish a connection
141 * over any transport that can by represented as an #GIOStream.
143 * This class is rarely used directly in D-Bus clients. If you are writing
144 * an D-Bus client, it is often easier to use the g_bus_own_name(),
145 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
147 * As an exception to the usual GLib rule that a particular object must not
148 * be used by two threads at the same time, #GDBusConnection's methods may be
149 * called from any thread. This is so that g_bus_get() and g_bus_get_sync()
150 * can safely return the same #GDBusConnection when called from any thread.
152 * Most of the ways to obtain a #GDBusConnection automatically initialize it
153 * (i.e. connect to D-Bus): for instance, g_dbus_connection_new() and
154 * g_bus_get(), and the synchronous versions of those methods, give you an
155 * initialized connection. Language bindings for GIO should use
156 * g_initable_new() or g_async_initable_new_async(), which also initialize the
159 * If you construct an uninitialized #GDBusConnection, such as via
160 * g_object_new(), you must initialize it via g_initable_init() or
161 * g_async_initable_init_async() before using its methods or properties.
162 * Calling methods or accessing properties on a #GDBusConnection that has not
163 * completed initialization successfully is considered to be invalid, and leads
164 * to undefined behaviour. In particular, if initialization fails with a
165 * #GError, the only valid thing you can do with that #GDBusConnection is to
166 * free it with g_object_unref().
168 * <example id="gdbus-server"><title>D-Bus server example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-server.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
170 * <example id="gdbus-subtree-server"><title>D-Bus subtree example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-subtree.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
172 * <example id="gdbus-unix-fd-client"><title>D-Bus UNIX File Descriptor example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-unix-fd-client.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
174 * <example id="gdbus-export"><title>Exporting a GObject</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-export.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
177 /* ---------------------------------------------------------------------------------------------------- */
179 typedef struct _GDBusConnectionClass GDBusConnectionClass;
182 * GDBusConnectionClass:
183 * @closed: Signal class handler for the #GDBusConnection::closed signal.
185 * Class structure for #GDBusConnection.
189 struct _GDBusConnectionClass
192 GObjectClass parent_class;
196 void (*closed) (GDBusConnection *connection,
197 gboolean remote_peer_vanished,
201 G_LOCK_DEFINE_STATIC (message_bus_lock);
203 static GWeakRef the_session_bus;
204 static GWeakRef the_system_bus;
206 /* Extra pseudo-member of GDBusSendMessageFlags.
207 * Set by initable_init() to indicate that despite not being initialized yet,
208 * enough of the only-valid-after-init members are set that we can send a
209 * message, and we're being called from its thread, so no memory barrier is
210 * required before accessing them.
212 #define SEND_MESSAGE_FLAGS_INITIALIZING (1<<31)
214 /* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
215 #define CALL_FLAGS_INITIALIZING (1<<31)
217 /* ---------------------------------------------------------------------------------------------------- */
221 GDestroyNotify callback;
223 GMainContext *context;
224 } CallDestroyNotifyData;
227 call_destroy_notify_data_in_idle (gpointer user_data)
229 CallDestroyNotifyData *data = user_data;
230 data->callback (data->user_data);
235 call_destroy_notify_data_free (CallDestroyNotifyData *data)
237 if (data->context != NULL)
238 g_main_context_unref (data->context);
243 * call_destroy_notify: <internal>
244 * @context: (allow-none): A #GMainContext or %NULL.
245 * @callback: (allow-none): A #GDestroyNotify or %NULL.
246 * @user_data: Data to pass to @callback.
248 * Schedules @callback to run in @context.
251 call_destroy_notify (GMainContext *context,
252 GDestroyNotify callback,
255 GSource *idle_source;
256 CallDestroyNotifyData *data;
258 if (callback == NULL)
261 data = g_new0 (CallDestroyNotifyData, 1);
262 data->callback = callback;
263 data->user_data = user_data;
264 data->context = context;
265 if (data->context != NULL)
266 g_main_context_ref (data->context);
268 idle_source = g_idle_source_new ();
269 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
270 g_source_set_callback (idle_source,
271 call_destroy_notify_data_in_idle,
273 (GDestroyNotify) call_destroy_notify_data_free);
274 g_source_attach (idle_source, data->context);
275 g_source_unref (idle_source);
281 /* ---------------------------------------------------------------------------------------------------- */
284 _g_strv_has_string (const gchar* const *haystack,
289 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
291 if (g_strcmp0 (haystack[n], needle) == 0)
297 /* ---------------------------------------------------------------------------------------------------- */
300 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
302 // TODO: for some reason this doesn't work on Windows
303 #define CONNECTION_ENSURE_LOCK(obj) do { \
304 if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock))) \
306 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
307 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
312 #define CONNECTION_LOCK(obj) do { \
313 g_mutex_lock (&(obj)->lock); \
316 #define CONNECTION_UNLOCK(obj) do { \
317 g_mutex_unlock (&(obj)->lock); \
320 /* Flags in connection->atomic_flags */
322 FLAG_INITIALIZED = 1 << 0,
323 FLAG_EXIT_ON_CLOSE = 1 << 1,
330 * The #GDBusConnection structure contains only private data and
331 * should only be accessed using the provided API.
335 struct _GDBusConnection
338 GObject parent_instance;
340 /* ------------------------------------------------------------------------ */
341 /* -- General object state ------------------------------------------------ */
342 /* ------------------------------------------------------------------------ */
344 /* General-purpose lock for most fields */
347 /* A lock used in the init() method of the GInitable interface - see comments
348 * in initable_init() for why a separate lock is needed.
350 * If you need both @lock and @init_lock, you must take @init_lock first.
354 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
355 * someone calls org.freedesktop.DBus.Peer.GetMachineId(). Protected by @lock.
359 /* The underlying stream used for communication
360 * Read-only after initable_init(), so it may be read if you either
361 * hold @init_lock or check for initialization first.
365 /* The object used for authentication (if any).
366 * Read-only after initable_init(), so it may be read if you either
367 * hold @init_lock or check for initialization first.
371 /* Last serial used. Protected by @lock. */
374 /* The object used to send/receive messages.
375 * Read-only after initable_init(), so it may be read if you either
376 * hold @init_lock or check for initialization first.
380 /* If connected to a message bus, this contains the unique name assigned to
381 * us by the bus (e.g. ":1.42").
382 * Read-only after initable_init(), so it may be read if you either
383 * hold @init_lock or check for initialization first.
385 gchar *bus_unique_name;
387 /* The GUID returned by the other side if we authenticed as a client or
388 * the GUID to use if authenticating as a server.
389 * Read-only after initable_init(), so it may be read if you either
390 * hold @init_lock or check for initialization first.
394 /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
395 * Inspect @initialization_error to see whether it succeeded or failed.
397 * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
399 * FLAG_CLOSED is the closed property. It may be read at any time, but
400 * may only be written while holding @lock.
402 volatile gint atomic_flags;
404 /* If the connection could not be established during initable_init(),
405 * this GError will be set.
406 * Read-only after initable_init(), so it may be read if you either
407 * hold @init_lock or check for initialization first.
409 GError *initialization_error;
411 /* The result of g_main_context_ref_thread_default() when the object
412 * was created (the GObject _init() function) - this is used for delivery
413 * of the :closed GObject signal.
415 * Only set in the GObject init function, so no locks are needed.
417 GMainContext *main_context_at_construction;
419 /* Read-only construct properties, no locks needed */
421 GDBusConnectionFlags flags;
423 /* Map used for managing method replies, protected by @lock */
424 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
426 /* Maps used for managing signal subscription, protected by @lock */
427 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
428 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
429 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
431 /* Maps used for managing exported objects and subtrees,
434 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
435 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
436 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
437 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
439 /* Map used for storing last used serials for each thread, protected by @lock */
440 GHashTable *map_thread_to_last_serial;
442 /* Structure used for message filters, protected by @lock */
445 /* Capabilities negotiated during authentication
446 * Read-only after initable_init(), so it may be read without holding a
447 * lock, if you check for initialization first.
449 GDBusCapabilityFlags capabilities;
451 /* Protected by @init_lock */
452 GDBusAuthObserver *authentication_observer;
454 /* Read-only after initable_init(), so it may be read if you either
455 * hold @init_lock or check for initialization first.
457 GCredentials *credentials;
459 /* set to TRUE when finalizing */
463 typedef struct ExportedObject ExportedObject;
464 static void exported_object_free (ExportedObject *eo);
466 typedef struct ExportedSubtree ExportedSubtree;
467 static void exported_subtree_free (ExportedSubtree *es);
485 PROP_CAPABILITY_FLAGS,
486 PROP_AUTHENTICATION_OBSERVER,
489 static void distribute_signals (GDBusConnection *connection,
490 GDBusMessage *message);
492 static void distribute_method_call (GDBusConnection *connection,
493 GDBusMessage *message);
495 static gboolean handle_generic_unlocked (GDBusConnection *connection,
496 GDBusMessage *message);
499 static void purge_all_signal_subscriptions (GDBusConnection *connection);
500 static void purge_all_filters (GDBusConnection *connection);
502 static void schedule_method_call (GDBusConnection *connection,
503 GDBusMessage *message,
504 guint registration_id,
505 guint subtree_registration_id,
506 const GDBusInterfaceInfo *interface_info,
507 const GDBusMethodInfo *method_info,
508 const GDBusPropertyInfo *property_info,
509 GVariant *parameters,
510 const GDBusInterfaceVTable *vtable,
511 GMainContext *main_context,
514 #define _G_ENSURE_LOCK(name) do { \
515 if (G_UNLIKELY (G_TRYLOCK(name))) \
517 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
518 "_G_ENSURE_LOCK: Lock '" #name "' is not locked"); \
522 static guint signals[LAST_SIGNAL] = { 0 };
524 static void initable_iface_init (GInitableIface *initable_iface);
525 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
527 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
528 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
529 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
533 * Check that all members of @connection that can only be accessed after
534 * the connection is initialized can safely be accessed. If not,
535 * log a critical warning. This function is a memory barrier.
537 * Returns: %TRUE if initialized
540 check_initialized (GDBusConnection *connection)
542 /* The access to @atomic_flags isn't conditional, so that this function
543 * provides a memory barrier for thread-safety even if checks are disabled.
544 * (If you don't want this stricter guarantee, you can call
545 * g_return_if_fail (check_initialized (c)).)
547 * This isn't strictly necessary now that we've decided use of an
548 * uninitialized GDBusConnection is undefined behaviour, but it seems
549 * better to be as deterministic as is feasible.
551 * (Anything that could suffer a crash from seeing undefined values
552 * must have a race condition - thread A initializes the connection while
553 * thread B calls a method without initialization, hoping that thread A will
554 * win the race - so its behaviour is undefined anyway.)
556 gint flags = g_atomic_int_get (&connection->atomic_flags);
558 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
560 /* We can safely access this, due to the memory barrier above */
561 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
567 MAY_BE_UNINITIALIZED = (1<<1)
568 } CheckUnclosedFlags;
571 * Check the same thing as check_initialized(), and also that the
572 * connection is not closed. If the connection is uninitialized,
573 * raise a critical warning (it's programmer error); if it's closed,
574 * raise a recoverable GError (it's a runtime error).
576 * This function is a memory barrier.
578 * Returns: %TRUE if initialized and not closed
581 check_unclosed (GDBusConnection *connection,
582 CheckUnclosedFlags check,
585 /* check_initialized() is effectively inlined, so we don't waste time
586 * doing two memory barriers
588 gint flags = g_atomic_int_get (&connection->atomic_flags);
590 if (!(check & MAY_BE_UNINITIALIZED))
592 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
593 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
596 if (flags & FLAG_CLOSED)
598 g_set_error_literal (error,
601 _("The connection is closed"));
608 static GHashTable *alive_connections = NULL;
611 g_dbus_connection_dispose (GObject *object)
613 GDBusConnection *connection = G_DBUS_CONNECTION (object);
615 G_LOCK (message_bus_lock);
616 CONNECTION_LOCK (connection);
617 if (connection->worker != NULL)
619 _g_dbus_worker_stop (connection->worker);
620 connection->worker = NULL;
621 if (alive_connections != NULL)
622 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
626 if (alive_connections != NULL)
627 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
629 CONNECTION_UNLOCK (connection);
630 G_UNLOCK (message_bus_lock);
632 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
633 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
637 g_dbus_connection_finalize (GObject *object)
639 GDBusConnection *connection = G_DBUS_CONNECTION (object);
641 connection->finalizing = TRUE;
643 purge_all_signal_subscriptions (connection);
645 purge_all_filters (connection);
646 g_ptr_array_unref (connection->filters);
648 if (connection->authentication_observer != NULL)
649 g_object_unref (connection->authentication_observer);
651 if (connection->auth != NULL)
652 g_object_unref (connection->auth);
654 if (connection->credentials)
655 g_object_unref (connection->credentials);
657 if (connection->stream != NULL)
659 g_object_unref (connection->stream);
660 connection->stream = NULL;
663 g_free (connection->address);
665 g_free (connection->guid);
666 g_free (connection->bus_unique_name);
668 if (connection->initialization_error != NULL)
669 g_error_free (connection->initialization_error);
671 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
673 g_hash_table_unref (connection->map_rule_to_signal_data);
674 g_hash_table_unref (connection->map_id_to_signal_data);
675 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
677 g_hash_table_unref (connection->map_id_to_ei);
678 g_hash_table_unref (connection->map_object_path_to_eo);
679 g_hash_table_unref (connection->map_id_to_es);
680 g_hash_table_unref (connection->map_object_path_to_es);
682 g_hash_table_unref (connection->map_thread_to_last_serial);
684 g_main_context_unref (connection->main_context_at_construction);
686 g_free (connection->machine_id);
688 g_mutex_clear (&connection->init_lock);
689 g_mutex_clear (&connection->lock);
691 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
694 /* called in any user thread, with the connection's lock not held */
696 g_dbus_connection_get_property (GObject *object,
701 GDBusConnection *connection = G_DBUS_CONNECTION (object);
706 g_value_set_object (value, g_dbus_connection_get_stream (connection));
710 g_value_set_string (value, g_dbus_connection_get_guid (connection));
713 case PROP_UNIQUE_NAME:
714 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
718 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
721 case PROP_EXIT_ON_CLOSE:
722 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
725 case PROP_CAPABILITY_FLAGS:
726 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
730 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
735 /* called in any user thread, with the connection's lock not held */
737 g_dbus_connection_set_property (GObject *object,
742 GDBusConnection *connection = G_DBUS_CONNECTION (object);
747 connection->stream = g_value_dup_object (value);
751 connection->guid = g_value_dup_string (value);
755 connection->address = g_value_dup_string (value);
759 connection->flags = g_value_get_flags (value);
762 case PROP_EXIT_ON_CLOSE:
763 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
766 case PROP_AUTHENTICATION_OBSERVER:
767 connection->authentication_observer = g_value_dup_object (value);
771 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
776 /* Base-class implementation of GDBusConnection::closed.
778 * Called in a user thread, by the main context that was thread-default when
779 * the object was constructed.
782 g_dbus_connection_real_closed (GDBusConnection *connection,
783 gboolean remote_peer_vanished,
786 gint flags = g_atomic_int_get (&connection->atomic_flags);
788 /* Because atomic int access is a memory barrier, we can safely read
789 * initialization_error without a lock, as long as we do it afterwards.
791 if (remote_peer_vanished &&
792 (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
793 (flags & FLAG_INITIALIZED) != 0 &&
794 connection->initialization_error == NULL)
798 g_printerr ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
801 g_quark_to_string (error->domain), error->code);
805 g_printerr ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
812 g_dbus_connection_class_init (GDBusConnectionClass *klass)
814 GObjectClass *gobject_class;
816 gobject_class = G_OBJECT_CLASS (klass);
818 gobject_class->finalize = g_dbus_connection_finalize;
819 gobject_class->dispose = g_dbus_connection_dispose;
820 gobject_class->set_property = g_dbus_connection_set_property;
821 gobject_class->get_property = g_dbus_connection_get_property;
823 klass->closed = g_dbus_connection_real_closed;
826 * GDBusConnection:stream:
828 * The underlying #GIOStream used for I/O.
830 * If this is passed on construction and is a #GSocketConnection,
831 * then the corresponding #GSocket will be put into non-blocking mode.
833 * While the #GDBusConnection is active, it will interact with this
834 * stream from a worker thread, so it is not safe to interact with
835 * the stream directly.
839 g_object_class_install_property (gobject_class,
841 g_param_spec_object ("stream",
843 P_("The underlying streams used for I/O"),
847 G_PARAM_CONSTRUCT_ONLY |
848 G_PARAM_STATIC_NAME |
849 G_PARAM_STATIC_BLURB |
850 G_PARAM_STATIC_NICK));
853 * GDBusConnection:address:
855 * A D-Bus address specifying potential endpoints that can be used
856 * when establishing the connection.
860 g_object_class_install_property (gobject_class,
862 g_param_spec_string ("address",
864 P_("D-Bus address specifying potential socket endpoints"),
867 G_PARAM_CONSTRUCT_ONLY |
868 G_PARAM_STATIC_NAME |
869 G_PARAM_STATIC_BLURB |
870 G_PARAM_STATIC_NICK));
873 * GDBusConnection:flags:
875 * Flags from the #GDBusConnectionFlags enumeration.
879 g_object_class_install_property (gobject_class,
881 g_param_spec_flags ("flags",
884 G_TYPE_DBUS_CONNECTION_FLAGS,
885 G_DBUS_CONNECTION_FLAGS_NONE,
887 G_PARAM_CONSTRUCT_ONLY |
888 G_PARAM_STATIC_NAME |
889 G_PARAM_STATIC_BLURB |
890 G_PARAM_STATIC_NICK));
893 * GDBusConnection:guid:
895 * The GUID of the peer performing the role of server when
898 * If you are constructing a #GDBusConnection and pass
899 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
900 * #GDBusConnection:flags property then you MUST also set this
901 * property to a valid guid.
903 * If you are constructing a #GDBusConnection and pass
904 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
905 * #GDBusConnection:flags property you will be able to read the GUID
906 * of the other peer here after the connection has been successfully
911 g_object_class_install_property (gobject_class,
913 g_param_spec_string ("guid",
915 P_("GUID of the server peer"),
919 G_PARAM_CONSTRUCT_ONLY |
920 G_PARAM_STATIC_NAME |
921 G_PARAM_STATIC_BLURB |
922 G_PARAM_STATIC_NICK));
925 * GDBusConnection:unique-name:
927 * The unique name as assigned by the message bus or %NULL if the
928 * connection is not open or not a message bus connection.
932 g_object_class_install_property (gobject_class,
934 g_param_spec_string ("unique-name",
936 P_("Unique name of bus connection"),
939 G_PARAM_STATIC_NAME |
940 G_PARAM_STATIC_BLURB |
941 G_PARAM_STATIC_NICK));
944 * GDBusConnection:closed:
946 * A boolean specifying whether the connection has been closed.
950 g_object_class_install_property (gobject_class,
952 g_param_spec_boolean ("closed",
954 P_("Whether the connection is closed"),
957 G_PARAM_STATIC_NAME |
958 G_PARAM_STATIC_BLURB |
959 G_PARAM_STATIC_NICK));
962 * GDBusConnection:exit-on-close:
964 * A boolean specifying whether the process will be terminated (by
965 * calling <literal>raise(SIGTERM)</literal>) if the connection
966 * is closed by the remote peer.
968 * Note that #GDBusConnection objects returned by g_bus_get_finish() and
969 * g_bus_get_sync() will (usually) have this property set to %TRUE.
973 g_object_class_install_property (gobject_class,
975 g_param_spec_boolean ("exit-on-close",
977 P_("Whether the process is terminated when the connection is closed"),
981 G_PARAM_STATIC_NAME |
982 G_PARAM_STATIC_BLURB |
983 G_PARAM_STATIC_NICK));
986 * GDBusConnection:capabilities:
988 * Flags from the #GDBusCapabilityFlags enumeration
989 * representing connection features negotiated with the other peer.
993 g_object_class_install_property (gobject_class,
994 PROP_CAPABILITY_FLAGS,
995 g_param_spec_flags ("capabilities",
998 G_TYPE_DBUS_CAPABILITY_FLAGS,
999 G_DBUS_CAPABILITY_FLAGS_NONE,
1001 G_PARAM_STATIC_NAME |
1002 G_PARAM_STATIC_BLURB |
1003 G_PARAM_STATIC_NICK));
1006 * GDBusConnection:authentication-observer:
1008 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
1012 g_object_class_install_property (gobject_class,
1013 PROP_AUTHENTICATION_OBSERVER,
1014 g_param_spec_object ("authentication-observer",
1015 P_("Authentication Observer"),
1016 P_("Object used to assist in the authentication process"),
1017 G_TYPE_DBUS_AUTH_OBSERVER,
1019 G_PARAM_CONSTRUCT_ONLY |
1020 G_PARAM_STATIC_NAME |
1021 G_PARAM_STATIC_BLURB |
1022 G_PARAM_STATIC_NICK));
1025 * GDBusConnection::closed:
1026 * @connection: The #GDBusConnection emitting the signal.
1027 * @remote_peer_vanished: %TRUE if @connection is closed because the
1028 * remote peer closed its end of the connection.
1029 * @error: (allow-none): A #GError with more details about the event or %NULL.
1031 * Emitted when the connection is closed.
1033 * The cause of this event can be
1036 * If g_dbus_connection_close() is called. In this case
1037 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
1038 * </para></listitem>
1040 * If the remote peer closes the connection. In this case
1041 * @remote_peer_vanished is set to %TRUE and @error is set.
1042 * </para></listitem>
1044 * If the remote peer sends invalid or malformed data. In this
1045 * case @remote_peer_vanished is set to %FALSE and @error
1047 * </para></listitem>
1050 * Upon receiving this signal, you should give up your reference to
1051 * @connection. You are guaranteed that this signal is emitted only
1056 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
1057 G_TYPE_DBUS_CONNECTION,
1059 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1070 g_dbus_connection_init (GDBusConnection *connection)
1072 g_mutex_init (&connection->lock);
1073 g_mutex_init (&connection->init_lock);
1075 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
1077 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1079 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1081 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1084 (GDestroyNotify) g_ptr_array_unref);
1086 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1089 (GDestroyNotify) exported_object_free);
1091 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1094 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1097 (GDestroyNotify) exported_subtree_free);
1099 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1102 connection->map_thread_to_last_serial = g_hash_table_new (g_direct_hash,
1105 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1107 connection->filters = g_ptr_array_new ();
1111 * g_dbus_connection_get_stream:
1112 * @connection: a #GDBusConnection
1114 * Gets the underlying stream used for IO.
1116 * While the #GDBusConnection is active, it will interact with this
1117 * stream from a worker thread, so it is not safe to interact with
1118 * the stream directly.
1120 * Returns: (transfer none): the stream used for IO
1125 g_dbus_connection_get_stream (GDBusConnection *connection)
1127 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1129 /* do not use g_return_val_if_fail(), we want the memory barrier */
1130 if (!check_initialized (connection))
1133 return connection->stream;
1137 * g_dbus_connection_start_message_processing:
1138 * @connection: A #GDBusConnection.
1140 * If @connection was created with
1141 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1142 * starts processing messages. Does nothing on if @connection wasn't
1143 * created with this flag or if the method has already been called.
1148 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1150 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1152 /* do not use g_return_val_if_fail(), we want the memory barrier */
1153 if (!check_initialized (connection))
1156 g_assert (connection->worker != NULL);
1157 _g_dbus_worker_unfreeze (connection->worker);
1161 * g_dbus_connection_is_closed:
1162 * @connection: A #GDBusConnection.
1164 * Gets whether @connection is closed.
1166 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
1171 g_dbus_connection_is_closed (GDBusConnection *connection)
1175 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1177 flags = g_atomic_int_get (&connection->atomic_flags);
1179 return (flags & FLAG_CLOSED) ? TRUE : FALSE;
1183 * g_dbus_connection_get_capabilities:
1184 * @connection: A #GDBusConnection.
1186 * Gets the capabilities negotiated with the remote peer
1188 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
1192 GDBusCapabilityFlags
1193 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1195 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1197 /* do not use g_return_val_if_fail(), we want the memory barrier */
1198 if (!check_initialized (connection))
1199 return G_DBUS_CAPABILITY_FLAGS_NONE;
1201 return connection->capabilities;
1204 /* ---------------------------------------------------------------------------------------------------- */
1206 /* Called in a temporary thread without holding locks. */
1208 flush_in_thread_func (GSimpleAsyncResult *res,
1210 GCancellable *cancellable)
1215 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1218 g_simple_async_result_take_error (res, error);
1222 * g_dbus_connection_flush:
1223 * @connection: A #GDBusConnection.
1224 * @cancellable: (allow-none): A #GCancellable or %NULL.
1225 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1226 * satisfied or %NULL if you don't care about the result.
1227 * @user_data: The data to pass to @callback.
1229 * Asynchronously flushes @connection, that is, writes all queued
1230 * outgoing message to the transport and then flushes the transport
1231 * (using g_output_stream_flush_async()). This is useful in programs
1232 * that wants to emit a D-Bus signal and then exit
1233 * immediately. Without flushing the connection, there is no guarantee
1234 * that the message has been sent to the networking buffers in the OS
1237 * This is an asynchronous method. When the operation is finished,
1238 * @callback will be invoked in the <link
1239 * linkend="g-main-context-push-thread-default">thread-default main
1240 * loop</link> of the thread you are calling this method from. You can
1241 * then call g_dbus_connection_flush_finish() to get the result of the
1242 * operation. See g_dbus_connection_flush_sync() for the synchronous
1248 g_dbus_connection_flush (GDBusConnection *connection,
1249 GCancellable *cancellable,
1250 GAsyncReadyCallback callback,
1253 GSimpleAsyncResult *simple;
1255 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1257 simple = g_simple_async_result_new (G_OBJECT (connection),
1260 g_dbus_connection_flush);
1261 g_simple_async_result_set_check_cancellable (simple, cancellable);
1262 g_simple_async_result_run_in_thread (simple,
1263 flush_in_thread_func,
1266 g_object_unref (simple);
1270 * g_dbus_connection_flush_finish:
1271 * @connection: A #GDBusConnection.
1272 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_flush().
1273 * @error: Return location for error or %NULL.
1275 * Finishes an operation started with g_dbus_connection_flush().
1277 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1282 g_dbus_connection_flush_finish (GDBusConnection *connection,
1286 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1291 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1292 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1293 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1295 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1297 if (g_simple_async_result_propagate_error (simple, error))
1307 * g_dbus_connection_flush_sync:
1308 * @connection: A #GDBusConnection.
1309 * @cancellable: (allow-none): A #GCancellable or %NULL.
1310 * @error: Return location for error or %NULL.
1312 * Synchronously flushes @connection. The calling thread is blocked
1313 * until this is done. See g_dbus_connection_flush() for the
1314 * asynchronous version of this method and more details about what it
1317 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1322 g_dbus_connection_flush_sync (GDBusConnection *connection,
1323 GCancellable *cancellable,
1328 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1329 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1333 /* This is only a best-effort attempt to see whether the connection is
1334 * closed, so it doesn't need the lock. If the connection closes just
1335 * after this check, but before scheduling the flush operation, the
1336 * result will be more or less the same as if the connection closed while
1337 * the flush operation was pending - it'll fail with either CLOSED or
1340 if (!check_unclosed (connection, 0, error))
1343 g_assert (connection->worker != NULL);
1345 ret = _g_dbus_worker_flush_sync (connection->worker,
1353 /* ---------------------------------------------------------------------------------------------------- */
1357 GDBusConnection *connection;
1359 gboolean remote_peer_vanished;
1363 emit_closed_data_free (EmitClosedData *data)
1365 g_object_unref (data->connection);
1366 if (data->error != NULL)
1367 g_error_free (data->error);
1371 /* Called in a user thread that has acquired the main context that was
1372 * thread-default when the object was constructed
1375 emit_closed_in_idle (gpointer user_data)
1377 EmitClosedData *data = user_data;
1380 g_object_notify (G_OBJECT (data->connection), "closed");
1381 g_signal_emit (data->connection,
1382 signals[CLOSED_SIGNAL],
1384 data->remote_peer_vanished,
1390 /* Can be called from any thread, must hold lock.
1391 * FLAG_CLOSED must already have been set.
1394 schedule_closed_unlocked (GDBusConnection *connection,
1395 gboolean remote_peer_vanished,
1398 GSource *idle_source;
1399 EmitClosedData *data;
1401 CONNECTION_ENSURE_LOCK (connection);
1403 data = g_new0 (EmitClosedData, 1);
1404 data->connection = g_object_ref (connection);
1405 data->remote_peer_vanished = remote_peer_vanished;
1406 data->error = error != NULL ? g_error_copy (error) : NULL;
1408 idle_source = g_idle_source_new ();
1409 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1410 g_source_set_callback (idle_source,
1411 emit_closed_in_idle,
1413 (GDestroyNotify) emit_closed_data_free);
1414 g_source_attach (idle_source, connection->main_context_at_construction);
1415 g_source_unref (idle_source);
1418 /* ---------------------------------------------------------------------------------------------------- */
1421 * g_dbus_connection_close:
1422 * @connection: A #GDBusConnection.
1423 * @cancellable: (allow-none): A #GCancellable or %NULL.
1424 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1425 * satisfied or %NULL if you don't care about the result.
1426 * @user_data: The data to pass to @callback.
1428 * Closes @connection. Note that this never causes the process to
1429 * exit (this might only happen if the other end of a shared message
1430 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1432 * Once the connection is closed, operations such as sending a message
1433 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1434 * will not automatically flush the connection so queued messages may
1435 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1437 * If @connection is already closed, this method fails with
1438 * %G_IO_ERROR_CLOSED.
1440 * When @connection has been closed, the #GDBusConnection::closed
1441 * signal is emitted in the <link
1442 * linkend="g-main-context-push-thread-default">thread-default main
1443 * loop</link> of the thread that @connection was constructed in.
1445 * This is an asynchronous method. When the operation is finished,
1446 * @callback will be invoked in the <link
1447 * linkend="g-main-context-push-thread-default">thread-default main
1448 * loop</link> of the thread you are calling this method from. You can
1449 * then call g_dbus_connection_close_finish() to get the result of the
1450 * operation. See g_dbus_connection_close_sync() for the synchronous
1456 g_dbus_connection_close (GDBusConnection *connection,
1457 GCancellable *cancellable,
1458 GAsyncReadyCallback callback,
1461 GSimpleAsyncResult *simple;
1463 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1465 /* do not use g_return_val_if_fail(), we want the memory barrier */
1466 if (!check_initialized (connection))
1469 g_assert (connection->worker != NULL);
1471 simple = g_simple_async_result_new (G_OBJECT (connection),
1474 g_dbus_connection_close);
1475 g_simple_async_result_set_check_cancellable (simple, cancellable);
1476 _g_dbus_worker_close (connection->worker, cancellable, simple);
1477 g_object_unref (simple);
1481 * g_dbus_connection_close_finish:
1482 * @connection: A #GDBusConnection.
1483 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_close().
1484 * @error: Return location for error or %NULL.
1486 * Finishes an operation started with g_dbus_connection_close().
1488 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1493 g_dbus_connection_close_finish (GDBusConnection *connection,
1497 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1502 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1503 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1504 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1506 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1508 if (g_simple_async_result_propagate_error (simple, error))
1519 GAsyncResult *result;
1522 /* Can be called by any thread, without the connection lock */
1524 sync_close_cb (GObject *source_object,
1528 SyncCloseData *data = user_data;
1530 data->result = g_object_ref (res);
1531 g_main_loop_quit (data->loop);
1535 * g_dbus_connection_close_sync:
1536 * @connection: A #GDBusConnection.
1537 * @cancellable: (allow-none): A #GCancellable or %NULL.
1538 * @error: Return location for error or %NULL.
1540 * Synchronously closees @connection. The calling thread is blocked
1541 * until this is done. See g_dbus_connection_close() for the
1542 * asynchronous version of this method and more details about what it
1545 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1550 g_dbus_connection_close_sync (GDBusConnection *connection,
1551 GCancellable *cancellable,
1556 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1557 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1561 if (check_unclosed (connection, 0, error))
1563 GMainContext *context;
1566 context = g_main_context_new ();
1567 g_main_context_push_thread_default (context);
1568 data.loop = g_main_loop_new (context, TRUE);
1571 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1572 g_main_loop_run (data.loop);
1573 ret = g_dbus_connection_close_finish (connection, data.result, error);
1575 g_object_unref (data.result);
1576 g_main_loop_unref (data.loop);
1577 g_main_context_pop_thread_default (context);
1578 g_main_context_unref (context);
1584 /* ---------------------------------------------------------------------------------------------------- */
1587 * g_dbus_connection_get_last_serial:
1588 * @connection: A #GDBusConnection.
1590 * Retrieves the last serial number assigned to a #GDBusMessage on
1591 * the current thread. This includes messages sent via both low-level
1592 * API such as g_dbus_connection_send_message() as well as
1593 * high-level API such as g_dbus_connection_emit_signal(),
1594 * g_dbus_connection_call() or g_dbus_proxy_call().
1596 * Returns: the last used serial or zero when no message has been sent
1597 * within the current thread.
1602 g_dbus_connection_get_last_serial (GDBusConnection *connection)
1606 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
1608 CONNECTION_LOCK (connection);
1609 ret = GPOINTER_TO_UINT (g_hash_table_lookup (connection->map_thread_to_last_serial,
1611 CONNECTION_UNLOCK (connection);
1616 /* ---------------------------------------------------------------------------------------------------- */
1618 /* Can be called by any thread, with the connection lock held */
1620 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1621 GDBusMessage *message,
1622 GDBusSendMessageFlags flags,
1623 volatile guint32 *out_serial,
1628 guint32 serial_to_use;
1631 CONNECTION_ENSURE_LOCK (connection);
1633 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1634 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1636 /* TODO: check all necessary headers are present */
1641 if (out_serial != NULL)
1644 /* If we're in initable_init(), don't check for being initialized, to avoid
1645 * chicken-and-egg problems. initable_init() is responsible for setting up
1646 * our prerequisites (mainly connection->worker), and only calling us
1647 * from its own thread (so no memory barrier is needed).
1649 if (!check_unclosed (connection,
1650 (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
1654 blob = g_dbus_message_to_blob (message,
1656 connection->capabilities,
1661 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1662 serial_to_use = g_dbus_message_get_serial (message);
1664 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1669 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1672 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1675 g_assert_not_reached ();
1680 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1681 blob_size, serial_to_use, connection);
1682 g_printerr ("----\n");
1683 hexdump (blob, blob_size);
1684 g_printerr ("----\n");
1687 /* TODO: use connection->auth to encode the blob */
1689 if (out_serial != NULL)
1690 *out_serial = serial_to_use;
1692 /* store used serial for the current thread */
1693 /* TODO: watch the thread disposal and remove associated record
1695 * - see https://bugzilla.gnome.org/show_bug.cgi?id=676825#c7
1697 g_hash_table_replace (connection->map_thread_to_last_serial,
1699 GUINT_TO_POINTER (serial_to_use));
1701 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
1702 g_dbus_message_set_serial (message, serial_to_use);
1704 g_dbus_message_lock (message);
1705 _g_dbus_worker_send_message (connection->worker,
1709 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1720 * g_dbus_connection_send_message:
1721 * @connection: A #GDBusConnection.
1722 * @message: A #GDBusMessage
1723 * @flags: Flags affecting how the message is sent.
1724 * @out_serial: (out) (allow-none): Return location for serial number assigned
1725 * to @message when sending it or %NULL.
1726 * @error: Return location for error or %NULL.
1728 * Asynchronously sends @message to the peer represented by @connection.
1730 * Unless @flags contain the
1731 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1732 * will be assigned by @connection and set on @message via
1733 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1734 * serial number used will be written to this location prior to
1735 * submitting the message to the underlying transport.
1737 * If @connection is closed then the operation will fail with
1738 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1739 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1741 * See <xref linkend="gdbus-server"/> and <xref
1742 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1743 * low-level API to send and receive UNIX file descriptors.
1745 * Note that @message must be unlocked, unless @flags contain the
1746 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1748 * Returns: %TRUE if the message was well-formed and queued for
1749 * transmission, %FALSE if @error is set.
1754 g_dbus_connection_send_message (GDBusConnection *connection,
1755 GDBusMessage *message,
1756 GDBusSendMessageFlags flags,
1757 volatile guint32 *out_serial,
1762 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1763 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1764 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1765 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1767 CONNECTION_LOCK (connection);
1768 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1769 CONNECTION_UNLOCK (connection);
1773 /* ---------------------------------------------------------------------------------------------------- */
1777 volatile gint ref_count;
1778 GDBusConnection *connection;
1780 GSimpleAsyncResult *simple;
1782 GMainContext *main_context;
1784 GCancellable *cancellable;
1786 gulong cancellable_handler_id;
1788 GSource *timeout_source;
1793 /* Can be called from any thread with or without lock held */
1794 static SendMessageData *
1795 send_message_data_ref (SendMessageData *data)
1797 g_atomic_int_inc (&data->ref_count);
1801 /* Can be called from any thread with or without lock held */
1803 send_message_data_unref (SendMessageData *data)
1805 if (g_atomic_int_dec_and_test (&data->ref_count))
1807 g_assert (data->timeout_source == NULL);
1808 g_assert (data->simple == NULL);
1809 g_assert (data->cancellable_handler_id == 0);
1810 g_object_unref (data->connection);
1811 if (data->cancellable != NULL)
1812 g_object_unref (data->cancellable);
1813 g_main_context_unref (data->main_context);
1818 /* ---------------------------------------------------------------------------------------------------- */
1820 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1822 send_message_with_reply_deliver (SendMessageData *data, gboolean remove)
1824 CONNECTION_ENSURE_LOCK (data->connection);
1826 g_assert (!data->delivered);
1828 data->delivered = TRUE;
1830 g_simple_async_result_complete_in_idle (data->simple);
1831 g_object_unref (data->simple);
1832 data->simple = NULL;
1834 if (data->timeout_source != NULL)
1836 g_source_destroy (data->timeout_source);
1837 data->timeout_source = NULL;
1839 if (data->cancellable_handler_id > 0)
1841 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1842 data->cancellable_handler_id = 0;
1847 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
1848 GUINT_TO_POINTER (data->serial)));
1851 send_message_data_unref (data);
1854 /* ---------------------------------------------------------------------------------------------------- */
1856 /* Can be called from any thread with lock held */
1858 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1859 GDBusMessage *reply)
1861 if (data->delivered)
1864 g_simple_async_result_set_op_res_gpointer (data->simple,
1865 g_object_ref (reply),
1868 send_message_with_reply_deliver (data, TRUE);
1874 /* ---------------------------------------------------------------------------------------------------- */
1876 /* Called from a user thread, lock is not held */
1878 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1880 SendMessageData *data = user_data;
1882 CONNECTION_LOCK (data->connection);
1883 if (data->delivered)
1886 g_simple_async_result_set_error (data->simple,
1888 G_IO_ERROR_CANCELLED,
1889 _("Operation was cancelled"));
1891 send_message_with_reply_deliver (data, TRUE);
1894 CONNECTION_UNLOCK (data->connection);
1898 /* Can be called from any thread with or without lock held */
1900 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1903 SendMessageData *data = user_data;
1904 GSource *idle_source;
1906 /* postpone cancellation to idle handler since we may be called directly
1907 * via g_cancellable_connect() (e.g. holding lock)
1909 idle_source = g_idle_source_new ();
1910 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1911 g_source_set_callback (idle_source,
1912 send_message_with_reply_cancelled_idle_cb,
1913 send_message_data_ref (data),
1914 (GDestroyNotify) send_message_data_unref);
1915 g_source_attach (idle_source, data->main_context);
1916 g_source_unref (idle_source);
1919 /* ---------------------------------------------------------------------------------------------------- */
1921 /* Called from a user thread, lock is not held */
1923 send_message_with_reply_timeout_cb (gpointer user_data)
1925 SendMessageData *data = user_data;
1927 CONNECTION_LOCK (data->connection);
1928 if (data->delivered)
1931 g_simple_async_result_set_error (data->simple,
1933 G_IO_ERROR_TIMED_OUT,
1934 _("Timeout was reached"));
1936 send_message_with_reply_deliver (data, TRUE);
1939 CONNECTION_UNLOCK (data->connection);
1944 /* ---------------------------------------------------------------------------------------------------- */
1946 /* Called from a user thread, connection's lock is held */
1948 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1949 GDBusMessage *message,
1950 GDBusSendMessageFlags flags,
1952 volatile guint32 *out_serial,
1953 GCancellable *cancellable,
1954 GAsyncReadyCallback callback,
1957 GSimpleAsyncResult *simple;
1958 SendMessageData *data;
1960 volatile guint32 serial;
1964 if (out_serial == NULL)
1965 out_serial = &serial;
1967 if (timeout_msec == -1)
1968 timeout_msec = 25 * 1000;
1970 simple = g_simple_async_result_new (G_OBJECT (connection),
1973 g_dbus_connection_send_message_with_reply);
1974 g_simple_async_result_set_check_cancellable (simple, cancellable);
1976 if (g_cancellable_is_cancelled (cancellable))
1978 g_simple_async_result_set_error (simple,
1980 G_IO_ERROR_CANCELLED,
1981 _("Operation was cancelled"));
1982 g_simple_async_result_complete_in_idle (simple);
1983 g_object_unref (simple);
1988 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1990 g_simple_async_result_take_error (simple, error);
1991 g_simple_async_result_complete_in_idle (simple);
1992 g_object_unref (simple);
1996 data = g_new0 (SendMessageData, 1);
1997 data->ref_count = 1;
1998 data->connection = g_object_ref (connection);
1999 data->simple = simple;
2000 data->serial = *out_serial;
2001 data->main_context = g_main_context_ref_thread_default ();
2003 if (cancellable != NULL)
2005 data->cancellable = g_object_ref (cancellable);
2006 data->cancellable_handler_id = g_cancellable_connect (cancellable,
2007 G_CALLBACK (send_message_with_reply_cancelled_cb),
2008 send_message_data_ref (data),
2009 (GDestroyNotify) send_message_data_unref);
2012 if (timeout_msec != G_MAXINT)
2014 data->timeout_source = g_timeout_source_new (timeout_msec);
2015 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
2016 g_source_set_callback (data->timeout_source,
2017 send_message_with_reply_timeout_cb,
2018 send_message_data_ref (data),
2019 (GDestroyNotify) send_message_data_unref);
2020 g_source_attach (data->timeout_source, data->main_context);
2021 g_source_unref (data->timeout_source);
2024 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
2025 GUINT_TO_POINTER (*out_serial),
2033 * g_dbus_connection_send_message_with_reply:
2034 * @connection: A #GDBusConnection.
2035 * @message: A #GDBusMessage.
2036 * @flags: Flags affecting how the message is sent.
2037 * @timeout_msec: The timeout in milliseconds, -1 to use the default
2038 * timeout or %G_MAXINT for no timeout.
2039 * @out_serial: (out) (allow-none): Return location for serial number assigned
2040 * to @message when sending it or %NULL.
2041 * @cancellable: (allow-none): A #GCancellable or %NULL.
2042 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
2043 * satisfied or %NULL if you don't care about the result.
2044 * @user_data: The data to pass to @callback.
2046 * Asynchronously sends @message to the peer represented by @connection.
2048 * Unless @flags contain the
2049 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2050 * will be assigned by @connection and set on @message via
2051 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2052 * serial number used will be written to this location prior to
2053 * submitting the message to the underlying transport.
2055 * If @connection is closed then the operation will fail with
2056 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2057 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2058 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2060 * This is an asynchronous method. When the operation is finished, @callback will be invoked
2061 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
2062 * of the thread you are calling this method from. You can then call
2063 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
2064 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
2066 * Note that @message must be unlocked, unless @flags contain the
2067 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2069 * See <xref linkend="gdbus-server"/> and <xref
2070 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2071 * low-level API to send and receive UNIX file descriptors.
2076 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
2077 GDBusMessage *message,
2078 GDBusSendMessageFlags flags,
2080 volatile guint32 *out_serial,
2081 GCancellable *cancellable,
2082 GAsyncReadyCallback callback,
2085 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2086 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2087 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2088 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2090 CONNECTION_LOCK (connection);
2091 g_dbus_connection_send_message_with_reply_unlocked (connection,
2099 CONNECTION_UNLOCK (connection);
2103 * g_dbus_connection_send_message_with_reply_finish:
2104 * @connection: a #GDBusConnection
2105 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
2106 * @error: Return location for error or %NULL.
2108 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2110 * Note that @error is only set if a local in-process error
2111 * occurred. That is to say that the returned #GDBusMessage object may
2112 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2113 * g_dbus_message_to_gerror() to transcode this to a #GError.
2115 * See <xref linkend="gdbus-server"/> and <xref
2116 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2117 * low-level API to send and receive UNIX file descriptors.
2119 * Returns: (transfer full): A locked #GDBusMessage or %NULL if @error is set.
2124 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2128 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2129 GDBusMessage *reply;
2131 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2132 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2136 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
2138 if (g_simple_async_result_propagate_error (simple, error))
2141 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
2147 /* ---------------------------------------------------------------------------------------------------- */
2152 GMainContext *context;
2154 } SendMessageSyncData;
2156 /* Called from a user thread, lock is not held */
2158 send_message_with_reply_sync_cb (GDBusConnection *connection,
2162 SendMessageSyncData *data = user_data;
2163 data->res = g_object_ref (res);
2164 g_main_loop_quit (data->loop);
2168 * g_dbus_connection_send_message_with_reply_sync:
2169 * @connection: A #GDBusConnection.
2170 * @message: A #GDBusMessage.
2171 * @flags: Flags affecting how the message is sent.
2172 * @timeout_msec: The timeout in milliseconds, -1 to use the default
2173 * timeout or %G_MAXINT for no timeout.
2174 * @out_serial: (out) (allow-none): Return location for serial number assigned
2175 * to @message when sending it or %NULL.
2176 * @cancellable: (allow-none): A #GCancellable or %NULL.
2177 * @error: Return location for error or %NULL.
2179 * Synchronously sends @message to the peer represented by @connection
2180 * and blocks the calling thread until a reply is received or the
2181 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2182 * for the asynchronous version of this method.
2184 * Unless @flags contain the
2185 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2186 * will be assigned by @connection and set on @message via
2187 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2188 * serial number used will be written to this location prior to
2189 * submitting the message to the underlying transport.
2191 * If @connection is closed then the operation will fail with
2192 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2193 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2194 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2196 * Note that @error is only set if a local in-process error
2197 * occurred. That is to say that the returned #GDBusMessage object may
2198 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2199 * g_dbus_message_to_gerror() to transcode this to a #GError.
2201 * See <xref linkend="gdbus-server"/> and <xref
2202 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2203 * low-level API to send and receive UNIX file descriptors.
2205 * Note that @message must be unlocked, unless @flags contain the
2206 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2208 * Returns: (transfer full): A locked #GDBusMessage that is the reply to @message or %NULL if @error is set.
2213 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2214 GDBusMessage *message,
2215 GDBusSendMessageFlags flags,
2217 volatile guint32 *out_serial,
2218 GCancellable *cancellable,
2221 SendMessageSyncData *data;
2222 GDBusMessage *reply;
2224 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2225 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2226 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2227 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2228 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2230 data = g_new0 (SendMessageSyncData, 1);
2231 data->context = g_main_context_new ();
2232 data->loop = g_main_loop_new (data->context, FALSE);
2234 g_main_context_push_thread_default (data->context);
2236 g_dbus_connection_send_message_with_reply (connection,
2242 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2244 g_main_loop_run (data->loop);
2245 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2249 g_main_context_pop_thread_default (data->context);
2251 g_main_context_unref (data->context);
2252 g_main_loop_unref (data->loop);
2253 g_object_unref (data->res);
2259 /* ---------------------------------------------------------------------------------------------------- */
2263 GDBusMessageFilterFunction func;
2270 GDBusMessageFilterFunction filter_function;
2272 GDestroyNotify user_data_free_func;
2275 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2277 on_worker_message_received (GDBusWorker *worker,
2278 GDBusMessage *message,
2281 GDBusConnection *connection;
2282 FilterCallback *filters;
2287 G_LOCK (message_bus_lock);
2288 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2291 G_UNLOCK (message_bus_lock);
2294 connection = G_DBUS_CONNECTION (user_data);
2295 g_object_ref (connection);
2296 G_UNLOCK (message_bus_lock);
2298 //g_debug ("in on_worker_message_received");
2300 g_object_ref (message);
2301 g_dbus_message_lock (message);
2303 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2305 /* First collect the set of callback functions */
2306 CONNECTION_LOCK (connection);
2307 num_filters = connection->filters->len;
2308 filters = g_new0 (FilterCallback, num_filters);
2309 for (n = 0; n < num_filters; n++)
2311 FilterData *data = connection->filters->pdata[n];
2312 filters[n].func = data->filter_function;
2313 filters[n].user_data = data->user_data;
2315 CONNECTION_UNLOCK (connection);
2317 /* then call the filters in order (without holding the lock) */
2318 for (n = 0; n < num_filters; n++)
2320 message = filters[n].func (connection,
2323 filters[n].user_data);
2324 if (message == NULL)
2326 g_dbus_message_lock (message);
2329 /* Standard dispatch unless the filter ate the message - no need to
2330 * do anything if the message was altered
2332 if (message != NULL)
2334 GDBusMessageType message_type;
2336 message_type = g_dbus_message_get_message_type (message);
2337 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2339 guint32 reply_serial;
2340 SendMessageData *send_message_data;
2342 reply_serial = g_dbus_message_get_reply_serial (message);
2343 CONNECTION_LOCK (connection);
2344 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2345 GUINT_TO_POINTER (reply_serial));
2346 if (send_message_data != NULL)
2348 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2349 send_message_data_deliver_reply_unlocked (send_message_data, message);
2353 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2355 CONNECTION_UNLOCK (connection);
2357 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2359 CONNECTION_LOCK (connection);
2360 distribute_signals (connection, message);
2361 CONNECTION_UNLOCK (connection);
2363 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2365 CONNECTION_LOCK (connection);
2366 distribute_method_call (connection, message);
2367 CONNECTION_UNLOCK (connection);
2371 if (message != NULL)
2372 g_object_unref (message);
2373 g_object_unref (connection);
2377 /* Called in GDBusWorker's thread, lock is not held */
2378 static GDBusMessage *
2379 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2380 GDBusMessage *message,
2383 GDBusConnection *connection;
2384 FilterCallback *filters;
2389 G_LOCK (message_bus_lock);
2390 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2393 G_UNLOCK (message_bus_lock);
2396 connection = G_DBUS_CONNECTION (user_data);
2397 g_object_ref (connection);
2398 G_UNLOCK (message_bus_lock);
2400 //g_debug ("in on_worker_message_about_to_be_sent");
2402 /* First collect the set of callback functions */
2403 CONNECTION_LOCK (connection);
2404 num_filters = connection->filters->len;
2405 filters = g_new0 (FilterCallback, num_filters);
2406 for (n = 0; n < num_filters; n++)
2408 FilterData *data = connection->filters->pdata[n];
2409 filters[n].func = data->filter_function;
2410 filters[n].user_data = data->user_data;
2412 CONNECTION_UNLOCK (connection);
2414 /* then call the filters in order (without holding the lock) */
2415 for (n = 0; n < num_filters; n++)
2417 g_dbus_message_lock (message);
2418 message = filters[n].func (connection,
2421 filters[n].user_data);
2422 if (message == NULL)
2426 g_object_unref (connection);
2432 /* called with connection lock held, in GDBusWorker thread */
2434 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2436 SendMessageData *data = value;
2438 if (data->delivered)
2441 g_simple_async_result_set_error (data->simple,
2444 _("The connection is closed"));
2446 /* Ask send_message_with_reply_deliver not to remove the element from the
2447 * hash table - we're in the middle of a foreach; that would be unsafe.
2448 * Instead, return TRUE from this function so that it gets removed safely.
2450 send_message_with_reply_deliver (data, FALSE);
2454 /* Called in GDBusWorker's thread - we must not block - without lock held */
2456 on_worker_closed (GDBusWorker *worker,
2457 gboolean remote_peer_vanished,
2461 GDBusConnection *connection;
2463 guint old_atomic_flags;
2465 G_LOCK (message_bus_lock);
2466 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2469 G_UNLOCK (message_bus_lock);
2472 connection = G_DBUS_CONNECTION (user_data);
2473 g_object_ref (connection);
2474 G_UNLOCK (message_bus_lock);
2476 //g_debug ("in on_worker_closed: %s", error->message);
2478 CONNECTION_LOCK (connection);
2479 /* Even though this is atomic, we do it inside the lock to avoid breaking
2480 * assumptions in remove_match_rule(). We'd need the lock in a moment
2481 * anyway, so, no loss.
2483 old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
2485 if (!(old_atomic_flags & FLAG_CLOSED))
2487 g_hash_table_foreach_remove (connection->map_method_serial_to_send_message_data, cancel_method_on_close, NULL);
2488 schedule_closed_unlocked (connection, remote_peer_vanished, error);
2490 CONNECTION_UNLOCK (connection);
2492 g_object_unref (connection);
2495 /* ---------------------------------------------------------------------------------------------------- */
2497 /* Determines the biggest set of capabilities we can support on this
2500 * Called with the init_lock held.
2502 static GDBusCapabilityFlags
2503 get_offered_capabilities_max (GDBusConnection *connection)
2505 GDBusCapabilityFlags ret;
2506 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2508 if (G_IS_UNIX_CONNECTION (connection->stream))
2509 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2514 /* Called in a user thread, lock is not held */
2516 initable_init (GInitable *initable,
2517 GCancellable *cancellable,
2520 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2523 /* This method needs to be idempotent to work with the singleton
2524 * pattern. See the docs for g_initable_init(). We implement this by
2527 * Unfortunately we can't use the main lock since the on_worker_*()
2528 * callbacks above needs the lock during initialization (for message
2529 * bus connections we do a synchronous Hello() call on the bus).
2531 g_mutex_lock (&connection->init_lock);
2535 /* Make this a no-op if we're already initialized (successfully or
2538 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
2540 ret = (connection->initialization_error == NULL);
2544 /* Because of init_lock, we can't get here twice in different threads */
2545 g_assert (connection->initialization_error == NULL);
2547 /* The user can pass multiple (but mutally exclusive) construct
2550 * - stream (of type GIOStream)
2551 * - address (of type gchar*)
2553 * At the end of the day we end up with a non-NULL GIOStream
2554 * object in connection->stream.
2556 if (connection->address != NULL)
2558 g_assert (connection->stream == NULL);
2560 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2561 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2563 g_set_error_literal (&connection->initialization_error,
2565 G_IO_ERROR_INVALID_ARGUMENT,
2566 _("Unsupported flags encountered when constructing a client-side connection"));
2570 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2571 NULL, /* TODO: out_guid */
2573 &connection->initialization_error);
2574 if (connection->stream == NULL)
2577 else if (connection->stream != NULL)
2583 g_assert_not_reached ();
2586 /* Authenticate the connection */
2587 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2589 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2590 g_assert (connection->guid != NULL);
2591 connection->auth = _g_dbus_auth_new (connection->stream);
2592 if (!_g_dbus_auth_run_server (connection->auth,
2593 connection->authentication_observer,
2595 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2596 get_offered_capabilities_max (connection),
2597 &connection->capabilities,
2598 &connection->credentials,
2600 &connection->initialization_error))
2603 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2605 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2606 g_assert (connection->guid == NULL);
2607 connection->auth = _g_dbus_auth_new (connection->stream);
2608 connection->guid = _g_dbus_auth_run_client (connection->auth,
2609 connection->authentication_observer,
2610 get_offered_capabilities_max (connection),
2611 &connection->capabilities,
2613 &connection->initialization_error);
2614 if (connection->guid == NULL)
2618 if (connection->authentication_observer != NULL)
2620 g_object_unref (connection->authentication_observer);
2621 connection->authentication_observer = NULL;
2624 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2626 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2629 /* We want all IO operations to be non-blocking since they happen in
2630 * the worker thread which is shared by _all_ connections.
2632 if (G_IS_SOCKET_CONNECTION (connection->stream))
2634 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2638 G_LOCK (message_bus_lock);
2639 if (alive_connections == NULL)
2640 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2641 g_hash_table_insert (alive_connections, connection, connection);
2642 G_UNLOCK (message_bus_lock);
2644 connection->worker = _g_dbus_worker_new (connection->stream,
2645 connection->capabilities,
2646 ((connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) != 0),
2647 on_worker_message_received,
2648 on_worker_message_about_to_be_sent,
2652 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2653 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2655 GVariant *hello_result;
2657 /* we could lift this restriction by adding code in gdbusprivate.c */
2658 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2660 g_set_error_literal (&connection->initialization_error,
2663 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2667 hello_result = g_dbus_connection_call_sync (connection,
2668 "org.freedesktop.DBus", /* name */
2669 "/org/freedesktop/DBus", /* path */
2670 "org.freedesktop.DBus", /* interface */
2672 NULL, /* parameters */
2673 G_VARIANT_TYPE ("(s)"),
2674 CALL_FLAGS_INITIALIZING,
2676 NULL, /* TODO: cancellable */
2677 &connection->initialization_error);
2678 if (hello_result == NULL)
2681 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2682 g_variant_unref (hello_result);
2683 //g_debug ("unique name is '%s'", connection->bus_unique_name);
2690 g_assert (connection->initialization_error != NULL);
2691 g_propagate_error (error, g_error_copy (connection->initialization_error));
2694 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
2695 g_mutex_unlock (&connection->init_lock);
2701 initable_iface_init (GInitableIface *initable_iface)
2703 initable_iface->init = initable_init;
2706 /* ---------------------------------------------------------------------------------------------------- */
2709 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2714 /* ---------------------------------------------------------------------------------------------------- */
2717 * g_dbus_connection_new:
2718 * @stream: A #GIOStream.
2719 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2720 * @flags: Flags describing how to make the connection.
2721 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2722 * @cancellable: (allow-none): A #GCancellable or %NULL.
2723 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2724 * @user_data: The data to pass to @callback.
2726 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2727 * with the end represented by @stream.
2729 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2730 * will be put into non-blocking mode.
2732 * The D-Bus connection will interact with @stream from a worker thread.
2733 * As a result, the caller should not interact with @stream after this
2734 * method has been called, except by calling g_object_unref() on it.
2736 * If @observer is not %NULL it may be used to control the
2737 * authentication process.
2739 * When the operation is finished, @callback will be invoked. You can
2740 * then call g_dbus_connection_new_finish() to get the result of the
2743 * This is a asynchronous failable constructor. See
2744 * g_dbus_connection_new_sync() for the synchronous
2750 g_dbus_connection_new (GIOStream *stream,
2752 GDBusConnectionFlags flags,
2753 GDBusAuthObserver *observer,
2754 GCancellable *cancellable,
2755 GAsyncReadyCallback callback,
2758 g_return_if_fail (G_IS_IO_STREAM (stream));
2759 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2767 "authentication-observer", observer,
2772 * g_dbus_connection_new_finish:
2773 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2774 * @error: Return location for error or %NULL.
2776 * Finishes an operation started with g_dbus_connection_new().
2778 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2783 g_dbus_connection_new_finish (GAsyncResult *res,
2787 GObject *source_object;
2789 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2790 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2792 source_object = g_async_result_get_source_object (res);
2793 g_assert (source_object != NULL);
2794 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2797 g_object_unref (source_object);
2799 return G_DBUS_CONNECTION (object);
2805 * g_dbus_connection_new_sync:
2806 * @stream: A #GIOStream.
2807 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2808 * @flags: Flags describing how to make the connection.
2809 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2810 * @cancellable: (allow-none): A #GCancellable or %NULL.
2811 * @error: Return location for error or %NULL.
2813 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2814 * with the end represented by @stream.
2816 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2817 * will be put into non-blocking mode.
2819 * The D-Bus connection will interact with @stream from a worker thread.
2820 * As a result, the caller should not interact with @stream after this
2821 * method has been called, except by calling g_object_unref() on it.
2823 * If @observer is not %NULL it may be used to control the
2824 * authentication process.
2826 * This is a synchronous failable constructor. See
2827 * g_dbus_connection_new() for the asynchronous version.
2829 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2834 g_dbus_connection_new_sync (GIOStream *stream,
2836 GDBusConnectionFlags flags,
2837 GDBusAuthObserver *observer,
2838 GCancellable *cancellable,
2841 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2842 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2843 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2849 "authentication-observer", observer,
2853 /* ---------------------------------------------------------------------------------------------------- */
2856 * g_dbus_connection_new_for_address:
2857 * @address: A D-Bus address.
2858 * @flags: Flags describing how to make the connection.
2859 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2860 * @cancellable: (allow-none): A #GCancellable or %NULL.
2861 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2862 * @user_data: The data to pass to @callback.
2864 * Asynchronously connects and sets up a D-Bus client connection for
2865 * exchanging D-Bus messages with an endpoint specified by @address
2866 * which must be in the D-Bus address format.
2868 * This constructor can only be used to initiate client-side
2869 * connections - use g_dbus_connection_new() if you need to act as the
2870 * server. In particular, @flags cannot contain the
2871 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2872 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2874 * When the operation is finished, @callback will be invoked. You can
2875 * then call g_dbus_connection_new_finish() to get the result of the
2878 * If @observer is not %NULL it may be used to control the
2879 * authentication process.
2881 * This is a asynchronous failable constructor. See
2882 * g_dbus_connection_new_for_address_sync() for the synchronous
2888 g_dbus_connection_new_for_address (const gchar *address,
2889 GDBusConnectionFlags flags,
2890 GDBusAuthObserver *observer,
2891 GCancellable *cancellable,
2892 GAsyncReadyCallback callback,
2895 g_return_if_fail (address != NULL);
2896 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2903 "authentication-observer", observer,
2908 * g_dbus_connection_new_for_address_finish:
2909 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2910 * @error: Return location for error or %NULL.
2912 * Finishes an operation started with g_dbus_connection_new_for_address().
2914 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2919 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2923 GObject *source_object;
2925 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2926 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2928 source_object = g_async_result_get_source_object (res);
2929 g_assert (source_object != NULL);
2930 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2933 g_object_unref (source_object);
2935 return G_DBUS_CONNECTION (object);
2941 * g_dbus_connection_new_for_address_sync:
2942 * @address: A D-Bus address.
2943 * @flags: Flags describing how to make the connection.
2944 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2945 * @cancellable: (allow-none): A #GCancellable or %NULL.
2946 * @error: Return location for error or %NULL.
2948 * Synchronously connects and sets up a D-Bus client connection for
2949 * exchanging D-Bus messages with an endpoint specified by @address
2950 * which must be in the D-Bus address format.
2952 * This constructor can only be used to initiate client-side
2953 * connections - use g_dbus_connection_new_sync() if you need to act
2954 * as the server. In particular, @flags cannot contain the
2955 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2956 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2958 * This is a synchronous failable constructor. See
2959 * g_dbus_connection_new_for_address() for the asynchronous version.
2961 * If @observer is not %NULL it may be used to control the
2962 * authentication process.
2964 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2969 g_dbus_connection_new_for_address_sync (const gchar *address,
2970 GDBusConnectionFlags flags,
2971 GDBusAuthObserver *observer,
2972 GCancellable *cancellable,
2975 g_return_val_if_fail (address != NULL, NULL);
2976 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2977 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2982 "authentication-observer", observer,
2986 /* ---------------------------------------------------------------------------------------------------- */
2989 * g_dbus_connection_set_exit_on_close:
2990 * @connection: A #GDBusConnection.
2991 * @exit_on_close: Whether the process should be terminated
2992 * when @connection is closed by the remote peer.
2994 * Sets whether the process should be terminated when @connection is
2995 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2998 * Note that this function should be used with care. Most modern UNIX
2999 * desktops tie the notion of a user session the session bus, and expect
3000 * all of a users applications to quit when their bus connection goes away.
3001 * If you are setting @exit_on_close to %FALSE for the shared session
3002 * bus connection, you should make sure that your application exits
3003 * when the user session ends.
3008 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
3009 gboolean exit_on_close)
3011 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3014 g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
3016 g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
3021 * g_dbus_connection_get_exit_on_close:
3022 * @connection: A #GDBusConnection.
3024 * Gets whether the process is terminated when @connection is
3025 * closed by the remote peer. See
3026 * #GDBusConnection:exit-on-close for more details.
3028 * Returns: Whether the process is terminated when @connection is
3029 * closed by the remote peer.
3034 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
3036 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3038 if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
3045 * g_dbus_connection_get_guid:
3046 * @connection: A #GDBusConnection.
3048 * The GUID of the peer performing the role of server when
3049 * authenticating. See #GDBusConnection:guid for more details.
3051 * Returns: The GUID. Do not free this string, it is owned by
3057 g_dbus_connection_get_guid (GDBusConnection *connection)
3059 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3060 return connection->guid;
3064 * g_dbus_connection_get_unique_name:
3065 * @connection: A #GDBusConnection.
3067 * Gets the unique name of @connection as assigned by the message
3068 * bus. This can also be used to figure out if @connection is a
3069 * message bus connection.
3071 * Returns: The unique name or %NULL if @connection is not a message
3072 * bus connection. Do not free this string, it is owned by
3078 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3080 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3082 /* do not use g_return_val_if_fail(), we want the memory barrier */
3083 if (!check_initialized (connection))
3086 return connection->bus_unique_name;
3090 * g_dbus_connection_get_peer_credentials:
3091 * @connection: A #GDBusConnection.
3093 * Gets the credentials of the authenticated peer. This will always
3094 * return %NULL unless @connection acted as a server
3095 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3096 * when set up and the client passed credentials as part of the
3097 * authentication process.
3099 * In a message bus setup, the message bus is always the server and
3100 * each application is a client. So this method will always return
3101 * %NULL for message bus clients.
3103 * Returns: (transfer none): A #GCredentials or %NULL if not available. Do not free
3104 * this object, it is owned by @connection.
3109 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3111 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3113 /* do not use g_return_val_if_fail(), we want the memory barrier */
3114 if (!check_initialized (connection))
3117 return connection->credentials;
3120 /* ---------------------------------------------------------------------------------------------------- */
3122 static guint _global_filter_id = 1;
3125 * g_dbus_connection_add_filter:
3126 * @connection: A #GDBusConnection.
3127 * @filter_function: A filter function.
3128 * @user_data: User data to pass to @filter_function.
3129 * @user_data_free_func: Function to free @user_data with when filter
3130 * is removed or %NULL.
3132 * Adds a message filter. Filters are handlers that are run on all
3133 * incoming and outgoing messages, prior to standard dispatch. Filters
3134 * are run in the order that they were added. The same handler can be
3135 * added as a filter more than once, in which case it will be run more
3136 * than once. Filters added during a filter callback won't be run on
3137 * the message being processed. Filter functions are allowed to modify
3138 * and even drop messages.
3140 * Note that filters are run in a dedicated message handling thread so
3141 * they can't block and, generally, can't do anything but signal a
3142 * worker thread. Also note that filters are rarely needed - use API
3143 * such as g_dbus_connection_send_message_with_reply(),
3144 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3146 * If a filter consumes an incoming message the message is not
3147 * dispatched anywhere else - not even the standard dispatch machinery
3148 * (that API such as g_dbus_connection_signal_subscribe() and
3149 * g_dbus_connection_send_message_with_reply() relies on) will see the
3150 * message. Similary, if a filter consumes an outgoing message, the
3151 * message will not be sent to the other peer.
3153 * Returns: A filter identifier that can be used with
3154 * g_dbus_connection_remove_filter().
3159 g_dbus_connection_add_filter (GDBusConnection *connection,
3160 GDBusMessageFilterFunction filter_function,
3162 GDestroyNotify user_data_free_func)
3166 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3167 g_return_val_if_fail (filter_function != NULL, 0);
3168 g_return_val_if_fail (check_initialized (connection), 0);
3170 CONNECTION_LOCK (connection);
3171 data = g_new0 (FilterData, 1);
3172 data->id = _global_filter_id++; /* TODO: overflow etc. */
3173 data->filter_function = filter_function;
3174 data->user_data = user_data;
3175 data->user_data_free_func = user_data_free_func;
3176 g_ptr_array_add (connection->filters, data);
3177 CONNECTION_UNLOCK (connection);
3182 /* only called from finalize(), removes all filters */
3184 purge_all_filters (GDBusConnection *connection)
3187 for (n = 0; n < connection->filters->len; n++)
3189 FilterData *data = connection->filters->pdata[n];
3190 if (data->user_data_free_func != NULL)
3191 data->user_data_free_func (data->user_data);
3197 * g_dbus_connection_remove_filter:
3198 * @connection: a #GDBusConnection
3199 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3206 g_dbus_connection_remove_filter (GDBusConnection *connection,
3210 FilterData *to_destroy;
3212 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3213 g_return_if_fail (check_initialized (connection));
3215 CONNECTION_LOCK (connection);
3217 for (n = 0; n < connection->filters->len; n++)
3219 FilterData *data = connection->filters->pdata[n];
3220 if (data->id == filter_id)
3222 g_ptr_array_remove_index (connection->filters, n);
3227 CONNECTION_UNLOCK (connection);
3229 /* do free without holding lock */
3230 if (to_destroy != NULL)
3232 if (to_destroy->user_data_free_func != NULL)
3233 to_destroy->user_data_free_func (to_destroy->user_data);
3234 g_free (to_destroy);
3238 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3242 /* ---------------------------------------------------------------------------------------------------- */
3248 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3249 gchar *interface_name;
3253 GDBusSignalFlags flags;
3254 GArray *subscribers;
3259 GDBusSignalCallback callback;
3261 GDestroyNotify user_data_free_func;
3263 GMainContext *context;
3267 signal_data_free (SignalData *signal_data)
3269 g_free (signal_data->rule);
3270 g_free (signal_data->sender);
3271 g_free (signal_data->sender_unique_name);
3272 g_free (signal_data->interface_name);
3273 g_free (signal_data->member);
3274 g_free (signal_data->object_path);
3275 g_free (signal_data->arg0);
3276 g_array_free (signal_data->subscribers, TRUE);
3277 g_free (signal_data);
3281 args_to_rule (const gchar *sender,
3282 const gchar *interface_name,
3283 const gchar *member,
3284 const gchar *object_path,
3286 GDBusSignalFlags flags)
3290 rule = g_string_new ("type='signal'");
3291 if (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE)
3292 g_string_prepend_c (rule, '-');
3294 g_string_append_printf (rule, ",sender='%s'", sender);
3295 if (interface_name != NULL)
3296 g_string_append_printf (rule, ",interface='%s'", interface_name);
3298 g_string_append_printf (rule, ",member='%s'", member);
3299 if (object_path != NULL)
3300 g_string_append_printf (rule, ",path='%s'", object_path);
3304 if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3305 g_string_append_printf (rule, ",arg0path='%s'", arg0);
3306 else if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3307 g_string_append_printf (rule, ",arg0namespace='%s'", arg0);
3309 g_string_append_printf (rule, ",arg0='%s'", arg0);
3312 return g_string_free (rule, FALSE);
3315 static guint _global_subscriber_id = 1;
3316 static guint _global_registration_id = 1;
3317 static guint _global_subtree_registration_id = 1;
3319 /* ---------------------------------------------------------------------------------------------------- */
3321 /* Called in a user thread, lock is held */
3323 add_match_rule (GDBusConnection *connection,
3324 const gchar *match_rule)
3327 GDBusMessage *message;
3329 if (match_rule[0] == '-')
3332 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3333 "/org/freedesktop/DBus", /* path */
3334 "org.freedesktop.DBus", /* interface */
3336 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3338 if (!g_dbus_connection_send_message_unlocked (connection,
3340 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3344 g_critical ("Error while sending AddMatch() message: %s", error->message);
3345 g_error_free (error);
3347 g_object_unref (message);
3350 /* ---------------------------------------------------------------------------------------------------- */
3352 /* Called in a user thread, lock is held */
3354 remove_match_rule (GDBusConnection *connection,
3355 const gchar *match_rule)
3358 GDBusMessage *message;
3360 if (match_rule[0] == '-')
3363 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3364 "/org/freedesktop/DBus", /* path */
3365 "org.freedesktop.DBus", /* interface */
3367 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3370 if (!g_dbus_connection_send_message_unlocked (connection,
3372 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3376 /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
3377 * critical; but we're holding the lock, and our caller checked whether
3378 * we were already closed, so we can't get that error.
3380 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3381 g_error_free (error);
3383 g_object_unref (message);
3386 /* ---------------------------------------------------------------------------------------------------- */
3389 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3391 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3392 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3393 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3394 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3395 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3398 /* ---------------------------------------------------------------------------------------------------- */
3401 * g_dbus_connection_signal_subscribe:
3402 * @connection: A #GDBusConnection.
3403 * @sender: (allow-none): Sender name to match on (unique or well-known name)
3404 * or %NULL to listen from all senders.
3405 * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3406 * match on all interfaces.
3407 * @member: (allow-none): D-Bus signal name to match on or %NULL to match on all signals.
3408 * @object_path: (allow-none): Object path to match on or %NULL to match on all object paths.
3409 * @arg0: (allow-none): Contents of first string argument to match on or %NULL
3410 * to match on all kinds of arguments.
3411 * @flags: Flags describing how to subscribe to the signal (currently unused).
3412 * @callback: Callback to invoke when there is a signal matching the requested data.
3413 * @user_data: User data to pass to @callback.
3414 * @user_data_free_func: (allow-none): Function to free @user_data with when
3415 * subscription is removed or %NULL.
3417 * Subscribes to signals on @connection and invokes @callback with a
3418 * whenever the signal is received. Note that @callback
3419 * will be invoked in the <link
3420 * linkend="g-main-context-push-thread-default">thread-default main
3421 * loop</link> of the thread you are calling this method from.
3423 * If @connection is not a message bus connection, @sender must be
3426 * If @sender is a well-known name note that @callback is invoked with
3427 * the unique name for the owner of @sender, not the well-known name
3428 * as one would expect. This is because the message bus rewrites the
3429 * name. As such, to avoid certain race conditions, users should be
3430 * tracking the name owner of the well-known name and use that when
3431 * processing the received signal.
3433 * If one of %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE or
3434 * %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH are given, @arg0 is
3435 * interpreted as part of a namespace or path. The first argument
3436 * of a signal is matched against that part as specified by D-Bus.
3438 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
3443 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3444 const gchar *sender,
3445 const gchar *interface_name,
3446 const gchar *member,
3447 const gchar *object_path,
3449 GDBusSignalFlags flags,
3450 GDBusSignalCallback callback,
3452 GDestroyNotify user_data_free_func)
3455 SignalData *signal_data;
3456 SignalSubscriber subscriber;
3457 GPtrArray *signal_data_array;
3458 const gchar *sender_unique_name;
3460 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3461 * an OOM condition. We might want to change that but that would involve making
3462 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3463 * handle that. And there's really no sensible way of handling this short of retrying
3464 * to add the match rule... and then there's the little thing that, hey, maybe there's
3465 * a reason the bus in an OOM condition.
3467 * Doable, but not really sure it's worth it...
3470 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3471 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3472 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3473 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3474 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3475 g_return_val_if_fail (callback != NULL, 0);
3476 g_return_val_if_fail (check_initialized (connection), 0);
3477 g_return_val_if_fail (!((flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH) && (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)), 0);
3478 g_return_val_if_fail (!(arg0 == NULL && (flags & (G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH | G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE))), 0);
3480 CONNECTION_LOCK (connection);
3482 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3483 * with a '-' character to prefix the rule (which will otherwise be
3486 * This allows us to hash the rule and do our lifecycle tracking in
3487 * the usual way, but the '-' prevents the match rule from ever
3488 * actually being send to the bus (either for add or remove).
3490 rule = args_to_rule (sender, interface_name, member, object_path, arg0, flags);
3492 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3493 sender_unique_name = sender;
3495 sender_unique_name = "";
3497 subscriber.callback = callback;
3498 subscriber.user_data = user_data;
3499 subscriber.user_data_free_func = user_data_free_func;
3500 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3501 subscriber.context = g_main_context_ref_thread_default ();
3503 /* see if we've already have this rule */
3504 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3505 if (signal_data != NULL)
3507 g_array_append_val (signal_data->subscribers, subscriber);
3512 signal_data = g_new0 (SignalData, 1);
3513 signal_data->rule = rule;
3514 signal_data->sender = g_strdup (sender);
3515 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3516 signal_data->interface_name = g_strdup (interface_name);
3517 signal_data->member = g_strdup (member);
3518 signal_data->object_path = g_strdup (object_path);
3519 signal_data->arg0 = g_strdup (arg0);
3520 signal_data->flags = flags;
3521 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3522 g_array_append_val (signal_data->subscribers, subscriber);
3524 g_hash_table_insert (connection->map_rule_to_signal_data,
3528 /* Add the match rule to the bus...
3530 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3531 * always send such messages to us.
3533 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3535 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3536 add_match_rule (connection, signal_data->rule);
3539 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3540 signal_data->sender_unique_name);
3541 if (signal_data_array == NULL)
3543 signal_data_array = g_ptr_array_new ();
3544 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3545 g_strdup (signal_data->sender_unique_name),
3548 g_ptr_array_add (signal_data_array, signal_data);
3551 g_hash_table_insert (connection->map_id_to_signal_data,
3552 GUINT_TO_POINTER (subscriber.id),
3555 CONNECTION_UNLOCK (connection);
3557 return subscriber.id;
3560 /* ---------------------------------------------------------------------------------------------------- */
3562 /* called in any thread */
3563 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3565 unsubscribe_id_internal (GDBusConnection *connection,
3566 guint subscription_id,
3567 GArray *out_removed_subscribers)
3569 SignalData *signal_data;
3570 GPtrArray *signal_data_array;
3573 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3574 GUINT_TO_POINTER (subscription_id));
3575 if (signal_data == NULL)
3577 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3581 for (n = 0; n < signal_data->subscribers->len; n++)
3583 SignalSubscriber *subscriber;
3585 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3586 if (subscriber->id != subscription_id)
3589 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3590 GUINT_TO_POINTER (subscription_id)));
3591 g_array_append_val (out_removed_subscribers, *subscriber);
3592 g_array_remove_index (signal_data->subscribers, n);
3594 if (signal_data->subscribers->len == 0)
3596 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3598 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3599 signal_data->sender_unique_name);
3600 g_warn_if_fail (signal_data_array != NULL);
3601 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3603 if (signal_data_array->len == 0)
3605 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3606 signal_data->sender_unique_name));
3609 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3610 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
3611 !is_signal_data_for_name_lost_or_acquired (signal_data) &&
3612 !g_dbus_connection_is_closed (connection) &&
3613 !connection->finalizing)
3615 /* The check for g_dbus_connection_is_closed() means that
3616 * sending the RemoveMatch message can't fail with
3617 * G_IO_ERROR_CLOSED, because we're holding the lock,
3618 * so on_worker_closed() can't happen between the check we just
3619 * did, and releasing the lock later.
3621 remove_match_rule (connection, signal_data->rule);
3624 signal_data_free (signal_data);
3630 g_assert_not_reached ();
3637 * g_dbus_connection_signal_unsubscribe:
3638 * @connection: A #GDBusConnection.
3639 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
3641 * Unsubscribes from signals.
3646 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3647 guint subscription_id)
3649 GArray *subscribers;
3652 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3653 g_return_if_fail (check_initialized (connection));
3655 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3657 CONNECTION_LOCK (connection);
3658 unsubscribe_id_internal (connection,
3661 CONNECTION_UNLOCK (connection);
3664 g_assert (subscribers->len == 0 || subscribers->len == 1);
3666 /* call GDestroyNotify without lock held */
3667 for (n = 0; n < subscribers->len; n++)
3669 SignalSubscriber *subscriber;
3670 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3671 call_destroy_notify (subscriber->context,
3672 subscriber->user_data_free_func,
3673 subscriber->user_data);
3674 g_main_context_unref (subscriber->context);
3677 g_array_free (subscribers, TRUE);
3680 /* ---------------------------------------------------------------------------------------------------- */
3684 guint subscription_id;
3685 GDBusSignalCallback callback;
3687 GDBusMessage *message;
3688 GDBusConnection *connection;
3689 const gchar *sender;
3691 const gchar *interface;
3692 const gchar *member;
3695 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3699 emit_signal_instance_in_idle_cb (gpointer data)
3701 SignalInstance *signal_instance = data;
3702 GVariant *parameters;
3703 gboolean has_subscription;
3705 parameters = g_dbus_message_get_body (signal_instance->message);
3706 if (parameters == NULL)
3708 parameters = g_variant_new ("()");
3709 g_variant_ref_sink (parameters);
3713 g_variant_ref_sink (parameters);
3717 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3718 signal_instance->subscription_id,
3719 signal_instance->sender,
3720 signal_instance->path,
3721 signal_instance->interface,
3722 signal_instance->member,
3723 g_variant_print (parameters, TRUE));
3726 /* Careful here, don't do the callback if we no longer has the subscription */
3727 CONNECTION_LOCK (signal_instance->connection);
3728 has_subscription = FALSE;
3729 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3730 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3731 has_subscription = TRUE;
3732 CONNECTION_UNLOCK (signal_instance->connection);
3734 if (has_subscription)
3735 signal_instance->callback (signal_instance->connection,
3736 signal_instance->sender,
3737 signal_instance->path,
3738 signal_instance->interface,
3739 signal_instance->member,
3741 signal_instance->user_data);
3743 g_variant_unref (parameters);
3749 signal_instance_free (SignalInstance *signal_instance)
3751 g_object_unref (signal_instance->message);
3752 g_object_unref (signal_instance->connection);
3753 g_free (signal_instance);
3757 namespace_rule_matches (const gchar *namespace,
3763 len_namespace = strlen (namespace);
3764 len_name = strlen (name);
3766 if (len_name < len_namespace)
3769 if (memcmp (namespace, name, len_namespace) != 0)
3772 return len_namespace == len_name || name[len_namespace] == '.';
3776 path_rule_matches (const gchar *path_a,
3777 const gchar *path_b)
3781 len_a = strlen (path_a);
3782 len_b = strlen (path_b);
3784 if (len_a < len_b && path_a[len_a - 1] != '/')
3787 if (len_b < len_a && path_b[len_b - 1] != '/')
3790 return memcmp (path_a, path_b, MIN (len_a, len_b)) == 0;
3793 /* called in GDBusWorker thread WITH lock held */
3795 schedule_callbacks (GDBusConnection *connection,
3796 GPtrArray *signal_data_array,
3797 GDBusMessage *message,
3798 const gchar *sender)
3801 const gchar *interface;
3802 const gchar *member;
3811 interface = g_dbus_message_get_interface (message);
3812 member = g_dbus_message_get_member (message);
3813 path = g_dbus_message_get_path (message);
3814 arg0 = g_dbus_message_get_arg0 (message);
3817 g_print ("In schedule_callbacks:\n"
3819 " interface = '%s'\n"
3830 /* TODO: if this is slow, then we can change signal_data_array into
3831 * map_object_path_to_signal_data_array or something.
3833 for (n = 0; n < signal_data_array->len; n++)
3835 SignalData *signal_data = signal_data_array->pdata[n];
3837 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3840 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3843 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3846 if (signal_data->arg0 != NULL)
3851 if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3853 if (!namespace_rule_matches (signal_data->arg0, arg0))
3856 else if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3858 if (!path_rule_matches (signal_data->arg0, arg0))
3861 else if (!g_str_equal (signal_data->arg0, arg0))
3865 for (m = 0; m < signal_data->subscribers->len; m++)
3867 SignalSubscriber *subscriber;
3868 GSource *idle_source;
3869 SignalInstance *signal_instance;
3871 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3873 signal_instance = g_new0 (SignalInstance, 1);
3874 signal_instance->subscription_id = subscriber->id;
3875 signal_instance->callback = subscriber->callback;
3876 signal_instance->user_data = subscriber->user_data;
3877 signal_instance->message = g_object_ref (message);
3878 signal_instance->connection = g_object_ref (connection);
3879 signal_instance->sender = sender;
3880 signal_instance->path = path;
3881 signal_instance->interface = interface;
3882 signal_instance->member = member;
3884 idle_source = g_idle_source_new ();
3885 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3886 g_source_set_callback (idle_source,
3887 emit_signal_instance_in_idle_cb,
3889 (GDestroyNotify) signal_instance_free);
3890 g_source_attach (idle_source, subscriber->context);
3891 g_source_unref (idle_source);
3896 /* called in GDBusWorker thread with lock held */
3898 distribute_signals (GDBusConnection *connection,
3899 GDBusMessage *message)
3901 GPtrArray *signal_data_array;
3902 const gchar *sender;
3904 sender = g_dbus_message_get_sender (message);
3906 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3908 _g_dbus_debug_print_lock ();
3909 g_print ("========================================================================\n"
3910 "GDBus-debug:Signal:\n"
3911 " <<<< RECEIVED SIGNAL %s.%s\n"
3913 " sent by name %s\n",
3914 g_dbus_message_get_interface (message),
3915 g_dbus_message_get_member (message),
3916 g_dbus_message_get_path (message),
3917 sender != NULL ? sender : "(none)");
3918 _g_dbus_debug_print_unlock ();
3921 /* collect subscribers that match on sender */
3924 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3925 if (signal_data_array != NULL)
3926 schedule_callbacks (connection, signal_data_array, message, sender);
3929 /* collect subscribers not matching on sender */
3930 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3931 if (signal_data_array != NULL)
3932 schedule_callbacks (connection, signal_data_array, message, sender);
3935 /* ---------------------------------------------------------------------------------------------------- */
3937 /* only called from finalize(), removes all subscriptions */
3939 purge_all_signal_subscriptions (GDBusConnection *connection)
3941 GHashTableIter iter;
3944 GArray *subscribers;
3947 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3948 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3949 while (g_hash_table_iter_next (&iter, &key, NULL))
3951 guint subscription_id = GPOINTER_TO_UINT (key);
3952 g_array_append_val (ids, subscription_id);
3955 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3956 for (n = 0; n < ids->len; n++)
3958 guint subscription_id = g_array_index (ids, guint, n);
3959 unsubscribe_id_internal (connection,
3963 g_array_free (ids, TRUE);
3965 /* call GDestroyNotify without lock held */
3966 for (n = 0; n < subscribers->len; n++)
3968 SignalSubscriber *subscriber;
3969 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3970 call_destroy_notify (subscriber->context,
3971 subscriber->user_data_free_func,
3972 subscriber->user_data);
3973 g_main_context_unref (subscriber->context);
3976 g_array_free (subscribers, TRUE);
3979 /* ---------------------------------------------------------------------------------------------------- */
3981 static GDBusInterfaceVTable *
3982 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3984 /* Don't waste memory by copying padding - remember to update this
3985 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3987 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3991 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
3996 /* ---------------------------------------------------------------------------------------------------- */
3998 static GDBusSubtreeVTable *
3999 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
4001 /* Don't waste memory by copying padding - remember to update this
4002 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
4004 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4008 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
4013 /* ---------------------------------------------------------------------------------------------------- */
4015 struct ExportedObject
4018 GDBusConnection *connection;
4020 /* maps gchar* -> ExportedInterface* */
4021 GHashTable *map_if_name_to_ei;
4024 /* only called with lock held */
4026 exported_object_free (ExportedObject *eo)
4028 g_free (eo->object_path);
4029 g_hash_table_unref (eo->map_if_name_to_ei);
4038 gchar *interface_name;
4039 GDBusInterfaceVTable *vtable;
4040 GDBusInterfaceInfo *interface_info;
4042 GMainContext *context;
4044 GDestroyNotify user_data_free_func;
4045 } ExportedInterface;
4047 /* called with lock held */
4049 exported_interface_free (ExportedInterface *ei)
4051 g_dbus_interface_info_cache_release (ei->interface_info);
4052 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
4054 call_destroy_notify (ei->context,
4055 ei->user_data_free_func,
4058 g_main_context_unref (ei->context);
4060 g_free (ei->interface_name);
4061 _g_dbus_interface_vtable_free (ei->vtable);
4065 /* ---------------------------------------------------------------------------------------------------- */
4067 /* Convenience function to check if @registration_id (if not zero) or
4068 * @subtree_registration_id (if not zero) has been unregistered. If
4069 * so, returns %TRUE.
4071 * May be called by any thread. Caller must *not* hold lock.
4074 has_object_been_unregistered (GDBusConnection *connection,
4075 guint registration_id,
4076 guint subtree_registration_id)
4080 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4084 CONNECTION_LOCK (connection);
4085 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
4086 GUINT_TO_POINTER (registration_id)) == NULL)
4090 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
4091 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
4095 CONNECTION_UNLOCK (connection);
4100 /* ---------------------------------------------------------------------------------------------------- */
4104 GDBusConnection *connection;
4105 GDBusMessage *message;
4107 const gchar *property_name;
4108 const GDBusInterfaceVTable *vtable;
4109 GDBusInterfaceInfo *interface_info;
4110 const GDBusPropertyInfo *property_info;
4111 guint registration_id;
4112 guint subtree_registration_id;
4116 property_data_free (PropertyData *data)
4118 g_object_unref (data->connection);
4119 g_object_unref (data->message);
4123 /* called in thread where object was registered - no locks held */
4125 invoke_get_property_in_idle_cb (gpointer _data)
4127 PropertyData *data = _data;
4130 GDBusMessage *reply;
4132 if (has_object_been_unregistered (data->connection,
4133 data->registration_id,
4134 data->subtree_registration_id))
4136 reply = g_dbus_message_new_method_error (data->message,
4137 "org.freedesktop.DBus.Error.UnknownMethod",
4138 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4139 g_dbus_message_get_path (data->message));
4140 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4141 g_object_unref (reply);
4146 value = data->vtable->get_property (data->connection,
4147 g_dbus_message_get_sender (data->message),
4148 g_dbus_message_get_path (data->message),
4149 data->interface_info->name,
4150 data->property_name,
4157 g_assert_no_error (error);
4159 g_variant_take_ref (value);
4160 reply = g_dbus_message_new_method_reply (data->message);
4161 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4162 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4163 g_variant_unref (value);
4164 g_object_unref (reply);
4168 gchar *dbus_error_name;
4169 g_assert (error != NULL);
4170 dbus_error_name = g_dbus_error_encode_gerror (error);
4171 reply = g_dbus_message_new_method_error_literal (data->message,
4174 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4175 g_free (dbus_error_name);
4176 g_error_free (error);
4177 g_object_unref (reply);
4184 /* called in thread where object was registered - no locks held */
4186 invoke_set_property_in_idle_cb (gpointer _data)
4188 PropertyData *data = _data;
4190 GDBusMessage *reply;
4196 g_variant_get (g_dbus_message_get_body (data->message),
4202 if (!data->vtable->set_property (data->connection,
4203 g_dbus_message_get_sender (data->message),
4204 g_dbus_message_get_path (data->message),
4205 data->interface_info->name,
4206 data->property_name,
4211 gchar *dbus_error_name;
4212 g_assert (error != NULL);
4213 dbus_error_name = g_dbus_error_encode_gerror (error);
4214 reply = g_dbus_message_new_method_error_literal (data->message,
4217 g_free (dbus_error_name);
4218 g_error_free (error);
4222 reply = g_dbus_message_new_method_reply (data->message);
4225 g_assert (reply != NULL);
4226 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4227 g_object_unref (reply);
4228 g_variant_unref (value);
4233 /* called in any thread with connection's lock held */
4235 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4236 GDBusMessage *message,
4237 guint registration_id,
4238 guint subtree_registration_id,
4240 GDBusInterfaceInfo *interface_info,
4241 const GDBusInterfaceVTable *vtable,
4242 GMainContext *main_context,
4246 const char *interface_name;
4247 const char *property_name;
4248 const GDBusPropertyInfo *property_info;
4249 GSource *idle_source;
4250 PropertyData *property_data;
4251 GDBusMessage *reply;
4256 g_variant_get (g_dbus_message_get_body (message),
4261 g_variant_get (g_dbus_message_get_body (message),
4270 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4272 property_info = NULL;
4274 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4275 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4276 if (property_info == NULL)
4278 reply = g_dbus_message_new_method_error (message,
4279 "org.freedesktop.DBus.Error.InvalidArgs",
4280 _("No such property '%s'"),
4282 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4283 g_object_unref (reply);
4288 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4290 reply = g_dbus_message_new_method_error (message,
4291 "org.freedesktop.DBus.Error.InvalidArgs",
4292 _("Property '%s' is not readable"),
4294 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4295 g_object_unref (reply);
4299 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4301 reply = g_dbus_message_new_method_error (message,
4302 "org.freedesktop.DBus.Error.InvalidArgs",
4303 _("Property '%s' is not writable"),
4305 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4306 g_object_unref (reply);
4315 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4316 * of the given value is wrong
4318 g_variant_get_child (g_dbus_message_get_body (message), 2, "v", &value);
4319 if (g_strcmp0 (g_variant_get_type_string (value), property_info->signature) != 0)
4321 reply = g_dbus_message_new_method_error (message,
4322 "org.freedesktop.DBus.Error.InvalidArgs",
4323 _("Error setting property '%s': Expected type '%s' but got '%s'"),
4324 property_name, property_info->signature,
4325 g_variant_get_type_string (value));
4326 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4327 g_variant_unref (value);
4328 g_object_unref (reply);
4333 g_variant_unref (value);
4336 /* If the vtable pointer for get_property() resp. set_property() is
4337 * NULL then dispatch the call via the method_call() handler.
4341 if (vtable->get_property == NULL)
4343 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4344 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4345 vtable, main_context, user_data);
4352 if (vtable->set_property == NULL)
4354 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4355 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4356 vtable, main_context, user_data);
4362 /* ok, got the property info - call user code in an idle handler */
4363 property_data = g_new0 (PropertyData, 1);
4364 property_data->connection = g_object_ref (connection);
4365 property_data->message = g_object_ref (message);
4366 property_data->user_data = user_data;
4367 property_data->property_name = property_name;
4368 property_data->vtable = vtable;
4369 property_data->interface_info = interface_info;
4370 property_data->property_info = property_info;
4371 property_data->registration_id = registration_id;
4372 property_data->subtree_registration_id = subtree_registration_id;
4374 idle_source = g_idle_source_new ();
4375 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4376 g_source_set_callback (idle_source,
4377 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4379 (GDestroyNotify) property_data_free);
4380 g_source_attach (idle_source, main_context);
4381 g_source_unref (idle_source);
4389 /* called in GDBusWorker thread with connection's lock held */
4391 handle_getset_property (GDBusConnection *connection,
4393 GDBusMessage *message,
4396 ExportedInterface *ei;
4398 const char *interface_name;
4399 const char *property_name;
4404 g_variant_get (g_dbus_message_get_body (message),
4409 g_variant_get (g_dbus_message_get_body (message),
4415 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4416 * no such interface registered
4418 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4421 GDBusMessage *reply;
4422 reply = g_dbus_message_new_method_error (message,
4423 "org.freedesktop.DBus.Error.InvalidArgs",
4424 _("No such interface '%s'"),
4426 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4427 g_object_unref (reply);
4432 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4445 /* ---------------------------------------------------------------------------------------------------- */
4449 GDBusConnection *connection;
4450 GDBusMessage *message;
4452 const GDBusInterfaceVTable *vtable;
4453 GDBusInterfaceInfo *interface_info;
4454 guint registration_id;
4455 guint subtree_registration_id;
4456 } PropertyGetAllData;
4459 property_get_all_data_free (PropertyData *data)
4461 g_object_unref (data->connection);
4462 g_object_unref (data->message);
4466 /* called in thread where object was registered - no locks held */
4468 invoke_get_all_properties_in_idle_cb (gpointer _data)
4470 PropertyGetAllData *data = _data;
4471 GVariantBuilder builder;
4472 GDBusMessage *reply;
4475 if (has_object_been_unregistered (data->connection,
4476 data->registration_id,
4477 data->subtree_registration_id))
4479 reply = g_dbus_message_new_method_error (data->message,
4480 "org.freedesktop.DBus.Error.UnknownMethod",
4481 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4482 g_dbus_message_get_path (data->message));
4483 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4484 g_object_unref (reply);
4488 /* TODO: Right now we never fail this call - we just omit values if
4489 * a get_property() call is failing.
4491 * We could fail the whole call if just a single get_property() call
4492 * returns an error. We need clarification in the D-Bus spec about this.
4494 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4495 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4496 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4498 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4501 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4504 value = data->vtable->get_property (data->connection,
4505 g_dbus_message_get_sender (data->message),
4506 g_dbus_message_get_path (data->message),
4507 data->interface_info->name,
4508 property_info->name,
4515 g_variant_take_ref (value);
4516 g_variant_builder_add (&builder,
4518 property_info->name,
4520 g_variant_unref (value);
4522 g_variant_builder_close (&builder);
4524 reply = g_dbus_message_new_method_reply (data->message);
4525 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4526 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4527 g_object_unref (reply);
4534 interface_has_readable_properties (GDBusInterfaceInfo *interface_info)
4538 if (!interface_info->properties)
4541 for (i = 0; interface_info->properties[i]; i++)
4542 if (interface_info->properties[i]->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE)
4548 /* called in any thread with connection's lock held */
4550 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4551 GDBusMessage *message,
4552 guint registration_id,
4553 guint subtree_registration_id,
4554 GDBusInterfaceInfo *interface_info,
4555 const GDBusInterfaceVTable *vtable,
4556 GMainContext *main_context,
4560 GSource *idle_source;
4561 PropertyGetAllData *property_get_all_data;
4568 /* If the vtable pointer for get_property() is NULL but we have a
4569 * non-zero number of readable properties, then dispatch the call via
4570 * the method_call() handler.
4572 if (vtable->get_property == NULL && interface_has_readable_properties (interface_info))
4574 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4575 interface_info, NULL, NULL, g_dbus_message_get_body (message),
4576 vtable, main_context, user_data);
4581 /* ok, got the property info - call user in an idle handler */
4582 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4583 property_get_all_data->connection = g_object_ref (connection);
4584 property_get_all_data->message = g_object_ref (message);
4585 property_get_all_data->user_data = user_data;
4586 property_get_all_data->vtable = vtable;
4587 property_get_all_data->interface_info = interface_info;
4588 property_get_all_data->registration_id = registration_id;
4589 property_get_all_data->subtree_registration_id = subtree_registration_id;
4591 idle_source = g_idle_source_new ();
4592 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4593 g_source_set_callback (idle_source,
4594 invoke_get_all_properties_in_idle_cb,
4595 property_get_all_data,
4596 (GDestroyNotify) property_get_all_data_free);
4597 g_source_attach (idle_source, main_context);
4598 g_source_unref (idle_source);
4606 /* called in GDBusWorker thread with connection's lock held */
4608 handle_get_all_properties (GDBusConnection *connection,
4610 GDBusMessage *message)
4612 ExportedInterface *ei;
4614 const char *interface_name;
4618 g_variant_get (g_dbus_message_get_body (message),
4622 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4623 * no such interface registered
4625 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4628 GDBusMessage *reply;
4629 reply = g_dbus_message_new_method_error (message,
4630 "org.freedesktop.DBus.Error.InvalidArgs",
4631 _("No such interface"),
4633 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4634 g_object_unref (reply);
4639 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4651 /* ---------------------------------------------------------------------------------------------------- */
4653 static const gchar introspect_header[] =
4654 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4655 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4656 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4659 static const gchar introspect_tail[] =
4662 static const gchar introspect_properties_interface[] =
4663 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4664 " <method name=\"Get\">\n"
4665 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4666 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4667 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4669 " <method name=\"GetAll\">\n"
4670 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4671 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4673 " <method name=\"Set\">\n"
4674 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4675 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4676 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4678 " <signal name=\"PropertiesChanged\">\n"
4679 " <arg type=\"s\" name=\"interface_name\"/>\n"
4680 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4681 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4685 static const gchar introspect_introspectable_interface[] =
4686 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4687 " <method name=\"Introspect\">\n"
4688 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4691 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4692 " <method name=\"Ping\"/>\n"
4693 " <method name=\"GetMachineId\">\n"
4694 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4699 introspect_append_header (GString *s)
4701 g_string_append (s, introspect_header);
4705 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4707 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4713 begin = object_path + path_len;
4714 end = strchr (begin, '/');
4716 s = g_strndup (begin, end - begin);
4718 s = g_strdup (begin);
4720 if (g_hash_table_lookup (set, s) == NULL)
4721 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
4727 /* TODO: we want a nicer public interface for this */
4728 /* called in any thread with connection's lock held */
4730 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4735 GHashTableIter hash_iter;
4736 const gchar *object_path;
4742 CONNECTION_ENSURE_LOCK (connection);
4744 path_len = strlen (path);
4748 set = g_hash_table_new (g_str_hash, g_str_equal);
4750 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4751 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4752 maybe_add_path (path, path_len, object_path, set);
4754 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4755 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4756 maybe_add_path (path, path_len, object_path, set);
4758 p = g_ptr_array_new ();
4759 keys = g_hash_table_get_keys (set);
4760 for (l = keys; l != NULL; l = l->next)
4761 g_ptr_array_add (p, l->data);
4762 g_hash_table_unref (set);
4765 g_ptr_array_add (p, NULL);
4766 ret = (gchar **) g_ptr_array_free (p, FALSE);
4770 /* called in any thread with connection's lock not held */
4772 g_dbus_connection_list_registered (GDBusConnection *connection,
4776 CONNECTION_LOCK (connection);
4777 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4778 CONNECTION_UNLOCK (connection);
4782 /* called in GDBusWorker thread with connection's lock held */
4784 handle_introspect (GDBusConnection *connection,
4786 GDBusMessage *message)
4790 GDBusMessage *reply;
4791 GHashTableIter hash_iter;
4792 ExportedInterface *ei;
4795 /* first the header with the standard interfaces */
4796 s = g_string_sized_new (sizeof (introspect_header) +
4797 sizeof (introspect_properties_interface) +
4798 sizeof (introspect_introspectable_interface) +
4799 sizeof (introspect_tail));
4800 introspect_append_header (s);
4801 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4802 "org.freedesktop.DBus.Properties"))
4803 g_string_append (s, introspect_properties_interface);
4805 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4806 "org.freedesktop.DBus.Introspectable"))
4807 g_string_append (s, introspect_introspectable_interface);
4809 /* then include the registered interfaces */
4810 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4811 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4812 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4814 /* finally include nodes registered below us */
4815 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4816 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4817 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4818 g_strfreev (registered);
4819 g_string_append (s, introspect_tail);
4821 reply = g_dbus_message_new_method_reply (message);
4822 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4823 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4824 g_object_unref (reply);
4825 g_string_free (s, TRUE);
4830 /* called in thread where object was registered - no locks held */
4832 call_in_idle_cb (gpointer user_data)
4834 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4835 GDBusInterfaceVTable *vtable;
4836 guint registration_id;
4837 guint subtree_registration_id;
4839 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4840 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4842 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4844 subtree_registration_id))
4846 GDBusMessage *reply;
4847 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4848 "org.freedesktop.DBus.Error.UnknownMethod",
4849 _("No such interface '%s' on object at path %s"),
4850 g_dbus_method_invocation_get_interface_name (invocation),
4851 g_dbus_method_invocation_get_object_path (invocation));
4852 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4853 g_object_unref (reply);
4857 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4858 g_assert (vtable != NULL && vtable->method_call != NULL);
4860 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4861 g_dbus_method_invocation_get_sender (invocation),
4862 g_dbus_method_invocation_get_object_path (invocation),
4863 g_dbus_method_invocation_get_interface_name (invocation),
4864 g_dbus_method_invocation_get_method_name (invocation),
4865 g_dbus_method_invocation_get_parameters (invocation),
4866 g_object_ref (invocation),
4867 g_dbus_method_invocation_get_user_data (invocation));
4873 /* called in GDBusWorker thread with connection's lock held */
4875 schedule_method_call (GDBusConnection *connection,
4876 GDBusMessage *message,
4877 guint registration_id,
4878 guint subtree_registration_id,
4879 const GDBusInterfaceInfo *interface_info,
4880 const GDBusMethodInfo *method_info,
4881 const GDBusPropertyInfo *property_info,
4882 GVariant *parameters,
4883 const GDBusInterfaceVTable *vtable,
4884 GMainContext *main_context,
4887 GDBusMethodInvocation *invocation;
4888 GSource *idle_source;
4890 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4891 g_dbus_message_get_path (message),
4892 g_dbus_message_get_interface (message),
4893 g_dbus_message_get_member (message),
4901 /* TODO: would be nicer with a real MethodData like we already
4902 * have PropertyData and PropertyGetAllData... */
4903 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4904 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4905 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4907 idle_source = g_idle_source_new ();
4908 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4909 g_source_set_callback (idle_source,
4913 g_source_attach (idle_source, main_context);
4914 g_source_unref (idle_source);
4917 /* called in GDBusWorker thread with connection's lock held */
4919 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4920 GDBusMessage *message,
4921 guint registration_id,
4922 guint subtree_registration_id,
4923 GDBusInterfaceInfo *interface_info,
4924 const GDBusInterfaceVTable *vtable,
4925 GMainContext *main_context,
4928 GDBusMethodInfo *method_info;
4929 GDBusMessage *reply;
4930 GVariant *parameters;
4932 GVariantType *in_type;
4936 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4937 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4939 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4940 * error to the caller
4942 if (method_info == NULL)
4944 reply = g_dbus_message_new_method_error (message,
4945 "org.freedesktop.DBus.Error.UnknownMethod",
4946 _("No such method '%s'"),
4947 g_dbus_message_get_member (message));
4948 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4949 g_object_unref (reply);
4954 parameters = g_dbus_message_get_body (message);
4955 if (parameters == NULL)
4957 parameters = g_variant_new ("()");
4958 g_variant_ref_sink (parameters);
4962 g_variant_ref (parameters);
4965 /* Check that the incoming args are of the right type - if they are not, return
4966 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4968 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4969 if (!g_variant_is_of_type (parameters, in_type))
4973 type_string = g_variant_type_dup_string (in_type);
4975 reply = g_dbus_message_new_method_error (message,
4976 "org.freedesktop.DBus.Error.InvalidArgs",
4977 _("Type of message, '%s', does not match expected type '%s'"),
4978 g_variant_get_type_string (parameters),
4980 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4981 g_variant_type_free (in_type);
4982 g_variant_unref (parameters);
4983 g_object_unref (reply);
4984 g_free (type_string);
4988 g_variant_type_free (in_type);
4990 /* schedule the call in idle */
4991 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4992 interface_info, method_info, NULL, parameters,
4993 vtable, main_context, user_data);
4994 g_variant_unref (parameters);
5001 /* ---------------------------------------------------------------------------------------------------- */
5003 /* called in GDBusWorker thread with connection's lock held */
5005 obj_message_func (GDBusConnection *connection,
5007 GDBusMessage *message)
5009 const gchar *interface_name;
5010 const gchar *member;
5011 const gchar *signature;
5016 interface_name = g_dbus_message_get_interface (message);
5017 member = g_dbus_message_get_member (message);
5018 signature = g_dbus_message_get_signature (message);
5020 /* see if we have an interface for handling this call */
5021 if (interface_name != NULL)
5023 ExportedInterface *ei;
5024 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5027 /* we do - invoke the handler in idle in the right thread */
5029 /* handle no vtable or handler being present */
5030 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
5033 handled = validate_and_maybe_schedule_method_call (connection,
5045 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5046 g_strcmp0 (member, "Introspect") == 0 &&
5047 g_strcmp0 (signature, "") == 0)
5049 handled = handle_introspect (connection, eo, message);
5052 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5053 g_strcmp0 (member, "Get") == 0 &&
5054 g_strcmp0 (signature, "ss") == 0)
5056 handled = handle_getset_property (connection, eo, message, TRUE);
5059 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5060 g_strcmp0 (member, "Set") == 0 &&
5061 g_strcmp0 (signature, "ssv") == 0)
5063 handled = handle_getset_property (connection, eo, message, FALSE);
5066 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5067 g_strcmp0 (member, "GetAll") == 0 &&
5068 g_strcmp0 (signature, "s") == 0)
5070 handled = handle_get_all_properties (connection, eo, message);
5079 * g_dbus_connection_register_object:
5080 * @connection: A #GDBusConnection.
5081 * @object_path: The object path to register at.
5082 * @interface_info: Introspection data for the interface.
5083 * @vtable: (allow-none): A #GDBusInterfaceVTable to call into or %NULL.
5084 * @user_data: (allow-none): Data to pass to functions in @vtable.
5085 * @user_data_free_func: Function to call when the object path is unregistered.
5086 * @error: Return location for error or %NULL.
5088 * Registers callbacks for exported objects at @object_path with the
5089 * D-Bus interface that is described in @interface_info.
5091 * Calls to functions in @vtable (and @user_data_free_func) will
5092 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
5093 * loop</link> of the thread you are calling this method from.
5095 * Note that all #GVariant values passed to functions in @vtable will match
5096 * the signature given in @interface_info - if a remote caller passes
5097 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
5098 * is returned to the remote caller.
5100 * Additionally, if the remote caller attempts to invoke methods or
5101 * access properties not mentioned in @interface_info the
5102 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
5103 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
5104 * are returned to the caller.
5106 * It is considered a programming error if the
5107 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
5108 * #GVariant of incorrect type.
5110 * If an existing callback is already registered at @object_path and
5111 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
5113 * GDBus automatically implements the standard D-Bus interfaces
5114 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
5115 * and org.freedesktop.Peer, so you don't have to implement those for
5116 * the objects you export. You <emphasis>can</emphasis> implement
5117 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
5118 * and setting of properties asynchronously.
5120 * Note that the reference count on @interface_info will be
5121 * incremented by 1 (unless allocated statically, e.g. if the
5122 * reference count is -1, see g_dbus_interface_info_ref()) for as long
5123 * as the object is exported. Also note that @vtable will be copied.
5125 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
5127 * Returns: 0 if @error is set, otherwise a registration id (never 0)
5128 * that can be used with g_dbus_connection_unregister_object() .
5133 g_dbus_connection_register_object (GDBusConnection *connection,
5134 const gchar *object_path,
5135 GDBusInterfaceInfo *interface_info,
5136 const GDBusInterfaceVTable *vtable,
5138 GDestroyNotify user_data_free_func,
5142 ExportedInterface *ei;
5145 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5146 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5147 g_return_val_if_fail (interface_info != NULL, 0);
5148 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
5149 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5150 g_return_val_if_fail (check_initialized (connection), 0);
5154 CONNECTION_LOCK (connection);
5156 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5159 eo = g_new0 (ExportedObject, 1);
5160 eo->object_path = g_strdup (object_path);
5161 eo->connection = connection;
5162 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
5165 (GDestroyNotify) exported_interface_free);
5166 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
5169 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
5175 _("An object is already exported for the interface %s at %s"),
5176 interface_info->name,
5181 ei = g_new0 (ExportedInterface, 1);
5182 ei->id = _global_registration_id++; /* TODO: overflow etc. */
5184 ei->user_data = user_data;
5185 ei->user_data_free_func = user_data_free_func;
5186 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
5187 ei->interface_info = g_dbus_interface_info_ref (interface_info);
5188 g_dbus_interface_info_cache_build (ei->interface_info);
5189 ei->interface_name = g_strdup (interface_info->name);
5190 ei->context = g_main_context_ref_thread_default ();
5192 g_hash_table_insert (eo->map_if_name_to_ei,
5193 (gpointer) ei->interface_name,
5195 g_hash_table_insert (connection->map_id_to_ei,
5196 GUINT_TO_POINTER (ei->id),
5202 CONNECTION_UNLOCK (connection);
5208 * g_dbus_connection_unregister_object:
5209 * @connection: A #GDBusConnection.
5210 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
5212 * Unregisters an object.
5214 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
5219 g_dbus_connection_unregister_object (GDBusConnection *connection,
5220 guint registration_id)
5222 ExportedInterface *ei;
5226 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5227 g_return_val_if_fail (check_initialized (connection), FALSE);
5231 CONNECTION_LOCK (connection);
5233 ei = g_hash_table_lookup (connection->map_id_to_ei,
5234 GUINT_TO_POINTER (registration_id));
5240 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5241 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5242 /* unregister object path if we have no more exported interfaces */
5243 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5244 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5250 CONNECTION_UNLOCK (connection);
5255 /* ---------------------------------------------------------------------------------------------------- */
5258 * g_dbus_connection_emit_signal:
5259 * @connection: A #GDBusConnection.
5260 * @destination_bus_name: (allow-none): The unique bus name for the destination
5261 * for the signal or %NULL to emit to all listeners.
5262 * @object_path: Path of remote object.
5263 * @interface_name: D-Bus interface to emit a signal on.
5264 * @signal_name: The name of the signal to emit.
5265 * @parameters: (allow-none): A #GVariant tuple with parameters for the signal
5266 * or %NULL if not passing parameters.
5267 * @error: Return location for error or %NULL.
5271 * If the parameters GVariant is floating, it is consumed.
5273 * This can only fail if @parameters is not compatible with the D-Bus protocol.
5275 * Returns: %TRUE unless @error is set.
5280 g_dbus_connection_emit_signal (GDBusConnection *connection,
5281 const gchar *destination_bus_name,
5282 const gchar *object_path,
5283 const gchar *interface_name,
5284 const gchar *signal_name,
5285 GVariant *parameters,
5288 GDBusMessage *message;
5294 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5295 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5296 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5297 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5298 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5299 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5300 g_return_val_if_fail (check_initialized (connection), FALSE);
5302 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5304 _g_dbus_debug_print_lock ();
5305 g_print ("========================================================================\n"
5306 "GDBus-debug:Emission:\n"
5307 " >>>> SIGNAL EMISSION %s.%s()\n"
5309 " destination %s\n",
5310 interface_name, signal_name,
5312 destination_bus_name != NULL ? destination_bus_name : "(none)");
5313 _g_dbus_debug_print_unlock ();
5316 message = g_dbus_message_new_signal (object_path,
5320 if (destination_bus_name != NULL)
5321 g_dbus_message_set_header (message,
5322 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5323 g_variant_new_string (destination_bus_name));
5325 if (parameters != NULL)
5326 g_dbus_message_set_body (message, parameters);
5328 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5329 g_object_unref (message);
5335 add_call_flags (GDBusMessage *message,
5336 GDBusCallFlags flags)
5338 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5339 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
5343 decode_method_reply (GDBusMessage *reply,
5344 const gchar *method_name,
5345 const GVariantType *reply_type,
5346 GUnixFDList **out_fd_list,
5352 switch (g_dbus_message_get_message_type (reply))
5354 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5355 result = g_dbus_message_get_body (reply);
5358 result = g_variant_new ("()");
5359 g_variant_ref_sink (result);
5363 g_variant_ref (result);
5366 if (!g_variant_is_of_type (result, reply_type))
5368 gchar *type_string = g_variant_type_dup_string (reply_type);
5372 G_IO_ERROR_INVALID_ARGUMENT,
5373 _("Method '%s' returned type '%s', but expected '%s'"),
5374 method_name, g_variant_get_type_string (result), type_string);
5376 g_variant_unref (result);
5377 g_free (type_string);
5384 if (out_fd_list != NULL)
5386 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5387 if (*out_fd_list != NULL)
5388 g_object_ref (*out_fd_list);
5394 case G_DBUS_MESSAGE_TYPE_ERROR:
5395 g_dbus_message_to_gerror (reply, error);
5399 g_assert_not_reached ();
5409 GSimpleAsyncResult *simple;
5410 GVariantType *reply_type;
5411 gchar *method_name; /* for error message */
5415 GUnixFDList *fd_list;
5419 call_state_free (CallState *state)
5421 g_variant_type_free (state->reply_type);
5422 g_free (state->method_name);
5424 if (state->value != NULL)
5425 g_variant_unref (state->value);
5426 if (state->fd_list != NULL)
5427 g_object_unref (state->fd_list);
5428 g_slice_free (CallState, state);
5431 /* called in any thread, with the connection's lock not held */
5433 g_dbus_connection_call_done (GObject *source,
5434 GAsyncResult *result,
5437 GSimpleAsyncResult *simple;
5438 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5439 CallState *state = user_data;
5441 GDBusMessage *reply;
5444 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5448 if (G_UNLIKELY (_g_dbus_debug_call ()))
5450 _g_dbus_debug_print_lock ();
5451 g_print ("========================================================================\n"
5452 "GDBus-debug:Call:\n"
5453 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5459 g_print ("SUCCESS\n");
5463 g_print ("FAILED: %s\n",
5466 _g_dbus_debug_print_unlock ();
5470 state->value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5472 simple = state->simple; /* why? because state is freed before we unref simple.. */
5475 g_simple_async_result_take_error (state->simple, error);
5476 g_simple_async_result_complete (state->simple);
5477 call_state_free (state);
5481 g_simple_async_result_set_op_res_gpointer (state->simple, state, (GDestroyNotify) call_state_free);
5482 g_simple_async_result_complete (state->simple);
5484 g_clear_object (&reply);
5485 g_object_unref (simple);
5488 /* called in any thread, with the connection's lock not held */
5490 g_dbus_connection_call_internal (GDBusConnection *connection,
5491 const gchar *bus_name,
5492 const gchar *object_path,
5493 const gchar *interface_name,
5494 const gchar *method_name,
5495 GVariant *parameters,
5496 const GVariantType *reply_type,
5497 GDBusCallFlags flags,
5499 GUnixFDList *fd_list,
5500 GCancellable *cancellable,
5501 GAsyncReadyCallback callback,
5504 GDBusMessage *message;
5507 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5508 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5509 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5510 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5511 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5512 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5513 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5514 g_return_if_fail (check_initialized (connection));
5516 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5518 g_return_if_fail (fd_list == NULL);
5521 message = g_dbus_message_new_method_call (bus_name,
5525 add_call_flags (message, flags);
5526 if (parameters != NULL)
5527 g_dbus_message_set_body (message, parameters);
5530 if (fd_list != NULL)
5531 g_dbus_message_set_unix_fd_list (message, fd_list);
5534 /* If the user has no callback then we can just send the message with
5535 * the G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set and skip all
5536 * the logic for processing the reply. If the service sends the reply
5537 * anyway then it will just be ignored.
5539 if (callback != NULL)
5543 state = g_slice_new0 (CallState);
5544 state->simple = g_simple_async_result_new (G_OBJECT (connection),
5545 callback, user_data,
5546 g_dbus_connection_call_internal);
5547 g_simple_async_result_set_check_cancellable (state->simple, cancellable);
5548 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5550 if (reply_type == NULL)
5551 reply_type = G_VARIANT_TYPE_ANY;
5553 state->reply_type = g_variant_type_copy (reply_type);
5555 g_dbus_connection_send_message_with_reply (connection,
5557 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5561 g_dbus_connection_call_done,
5563 serial = state->serial;
5567 GDBusMessageFlags flags;
5569 flags = g_dbus_message_get_flags (message);
5570 flags |= G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
5571 g_dbus_message_set_flags (message, flags);
5573 g_dbus_connection_send_message (connection,
5575 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5579 if (G_UNLIKELY (_g_dbus_debug_call ()))
5581 _g_dbus_debug_print_lock ();
5582 g_print ("========================================================================\n"
5583 "GDBus-debug:Call:\n"
5584 " >>>> ASYNC %s.%s()\n"
5586 " owned by name %s (serial %d)\n",
5590 bus_name != NULL ? bus_name : "(none)",
5592 _g_dbus_debug_print_unlock ();
5595 if (message != NULL)
5596 g_object_unref (message);
5599 /* called in any thread, with the connection's lock not held */
5601 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
5602 GUnixFDList **out_fd_list,
5606 GSimpleAsyncResult *simple;
5609 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5610 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
5611 g_dbus_connection_call_internal), NULL);
5612 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5614 simple = G_SIMPLE_ASYNC_RESULT (res);
5616 if (g_simple_async_result_propagate_error (simple, error))
5619 state = g_simple_async_result_get_op_res_gpointer (simple);
5620 if (out_fd_list != NULL)
5621 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
5622 return g_variant_ref (state->value);
5625 /* called in any user thread, with the connection's lock not held */
5627 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
5628 const gchar *bus_name,
5629 const gchar *object_path,
5630 const gchar *interface_name,
5631 const gchar *method_name,
5632 GVariant *parameters,
5633 const GVariantType *reply_type,
5634 GDBusCallFlags flags,
5636 GUnixFDList *fd_list,
5637 GUnixFDList **out_fd_list,
5638 GCancellable *cancellable,
5641 GDBusMessage *message;
5642 GDBusMessage *reply;
5644 GError *local_error;
5645 GDBusSendMessageFlags send_flags;
5651 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5652 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5653 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5654 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5655 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5656 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5657 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5659 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
5661 g_return_val_if_fail (fd_list == NULL, NULL);
5663 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5665 if (!(flags & CALL_FLAGS_INITIALIZING))
5666 g_return_val_if_fail (check_initialized (connection), FALSE);
5668 if (reply_type == NULL)
5669 reply_type = G_VARIANT_TYPE_ANY;
5671 message = g_dbus_message_new_method_call (bus_name,
5675 add_call_flags (message, flags);
5676 if (parameters != NULL)
5677 g_dbus_message_set_body (message, parameters);
5680 if (fd_list != NULL)
5681 g_dbus_message_set_unix_fd_list (message, fd_list);
5684 if (G_UNLIKELY (_g_dbus_debug_call ()))
5686 _g_dbus_debug_print_lock ();
5687 g_print ("========================================================================\n"
5688 "GDBus-debug:Call:\n"
5689 " >>>> SYNC %s.%s()\n"
5691 " owned by name %s\n",
5695 bus_name != NULL ? bus_name : "(none)");
5696 _g_dbus_debug_print_unlock ();
5701 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
5703 /* translate from one flavour of flags to another... */
5704 if (flags & CALL_FLAGS_INITIALIZING)
5705 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
5707 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5711 NULL, /* volatile guint32 *out_serial */
5715 if (G_UNLIKELY (_g_dbus_debug_call ()))
5717 _g_dbus_debug_print_lock ();
5718 g_print ("========================================================================\n"
5719 "GDBus-debug:Call:\n"
5720 " <<<< SYNC COMPLETE %s.%s()\n"
5726 g_print ("SUCCESS\n");
5730 g_print ("FAILED: %s\n",
5731 local_error->message);
5733 _g_dbus_debug_print_unlock ();
5739 *error = local_error;
5741 g_error_free (local_error);
5745 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
5748 if (message != NULL)
5749 g_object_unref (message);
5751 g_object_unref (reply);
5756 /* ---------------------------------------------------------------------------------------------------- */
5759 * g_dbus_connection_call:
5760 * @connection: A #GDBusConnection.
5761 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5762 * @connection is not a message bus connection.
5763 * @object_path: Path of remote object.
5764 * @interface_name: D-Bus interface to invoke method on.
5765 * @method_name: The name of the method to invoke.
5766 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5767 * or %NULL if not passing parameters.
5768 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5769 * @flags: Flags from the #GDBusCallFlags enumeration.
5770 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5771 * timeout or %G_MAXINT for no timeout.
5772 * @cancellable: (allow-none): A #GCancellable or %NULL.
5773 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5774 * satisfied or %NULL if you don't care about the result of the
5775 * method invocation.
5776 * @user_data: The data to pass to @callback.
5778 * Asynchronously invokes the @method_name method on the
5779 * @interface_name D-Bus interface on the remote object at
5780 * @object_path owned by @bus_name.
5782 * If @connection is closed then the operation will fail with
5783 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
5784 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
5785 * not compatible with the D-Bus protocol, the operation fails with
5786 * %G_IO_ERROR_INVALID_ARGUMENT.
5788 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
5789 * error will be raised if it does not match. Said another way, if you give a @reply_type
5790 * then any non-%NULL return value will be of this type.
5792 * If the @parameters #GVariant is floating, it is consumed. This allows
5793 * convenient 'inline' use of g_variant_new(), e.g.:
5795 * g_dbus_connection_call (connection,
5796 * "org.freedesktop.StringThings",
5797 * "/org/freedesktop/StringThings",
5798 * "org.freedesktop.StringThings",
5800 * g_variant_new ("(ss)",
5804 * G_DBUS_CALL_FLAGS_NONE,
5807 * (GAsyncReadyCallback) two_strings_done,
5811 * This is an asynchronous method. When the operation is finished, @callback will be invoked
5812 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
5813 * of the thread you are calling this method from. You can then call
5814 * g_dbus_connection_call_finish() to get the result of the operation.
5815 * See g_dbus_connection_call_sync() for the synchronous version of this
5818 * If @callback is %NULL then the D-Bus method call message will be sent with
5819 * the %G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set.
5824 g_dbus_connection_call (GDBusConnection *connection,
5825 const gchar *bus_name,
5826 const gchar *object_path,
5827 const gchar *interface_name,
5828 const gchar *method_name,
5829 GVariant *parameters,
5830 const GVariantType *reply_type,
5831 GDBusCallFlags flags,
5833 GCancellable *cancellable,
5834 GAsyncReadyCallback callback,
5837 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);
5841 * g_dbus_connection_call_finish:
5842 * @connection: A #GDBusConnection.
5843 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
5844 * @error: Return location for error or %NULL.
5846 * Finishes an operation started with g_dbus_connection_call().
5848 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5849 * return values. Free with g_variant_unref().
5854 g_dbus_connection_call_finish (GDBusConnection *connection,
5858 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
5862 * g_dbus_connection_call_sync:
5863 * @connection: A #GDBusConnection.
5864 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5865 * @connection is not a message bus connection.
5866 * @object_path: Path of remote object.
5867 * @interface_name: D-Bus interface to invoke method on.
5868 * @method_name: The name of the method to invoke.
5869 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5870 * or %NULL if not passing parameters.
5871 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5872 * @flags: Flags from the #GDBusCallFlags enumeration.
5873 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5874 * timeout or %G_MAXINT for no timeout.
5875 * @cancellable: (allow-none): A #GCancellable or %NULL.
5876 * @error: Return location for error or %NULL.
5878 * Synchronously invokes the @method_name method on the
5879 * @interface_name D-Bus interface on the remote object at
5880 * @object_path owned by @bus_name.
5882 * If @connection is closed then the operation will fail with
5883 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
5884 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
5885 * contains a value not compatible with the D-Bus protocol, the operation
5886 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
5888 * If @reply_type is non-%NULL then the reply will be checked for having
5889 * this type and an error will be raised if it does not match. Said
5890 * another way, if you give a @reply_type then any non-%NULL return
5891 * value will be of this type.
5893 * If the @parameters #GVariant is floating, it is consumed.
5894 * This allows convenient 'inline' use of g_variant_new(), e.g.:
5896 * g_dbus_connection_call_sync (connection,
5897 * "org.freedesktop.StringThings",
5898 * "/org/freedesktop/StringThings",
5899 * "org.freedesktop.StringThings",
5901 * g_variant_new ("(ss)",
5905 * G_DBUS_CALL_FLAGS_NONE,
5911 * The calling thread is blocked until a reply is received. See
5912 * g_dbus_connection_call() for the asynchronous version of
5915 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5916 * return values. Free with g_variant_unref().
5921 g_dbus_connection_call_sync (GDBusConnection *connection,
5922 const gchar *bus_name,
5923 const gchar *object_path,
5924 const gchar *interface_name,
5925 const gchar *method_name,
5926 GVariant *parameters,
5927 const GVariantType *reply_type,
5928 GDBusCallFlags flags,
5930 GCancellable *cancellable,
5933 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);
5936 /* ---------------------------------------------------------------------------------------------------- */
5941 * g_dbus_connection_call_with_unix_fd_list:
5942 * @connection: A #GDBusConnection.
5943 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5944 * @connection is not a message bus connection.
5945 * @object_path: Path of remote object.
5946 * @interface_name: D-Bus interface to invoke method on.
5947 * @method_name: The name of the method to invoke.
5948 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5949 * or %NULL if not passing parameters.
5950 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5951 * @flags: Flags from the #GDBusCallFlags enumeration.
5952 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5953 * timeout or %G_MAXINT for no timeout.
5954 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
5955 * @cancellable: (allow-none): A #GCancellable or %NULL.
5956 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5957 * satisfied or %NULL if you don't * care about the result of the
5958 * method invocation.
5959 * @user_data: The data to pass to @callback.
5961 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
5963 * This method is only available on UNIX.
5968 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
5969 const gchar *bus_name,
5970 const gchar *object_path,
5971 const gchar *interface_name,
5972 const gchar *method_name,
5973 GVariant *parameters,
5974 const GVariantType *reply_type,
5975 GDBusCallFlags flags,
5977 GUnixFDList *fd_list,
5978 GCancellable *cancellable,
5979 GAsyncReadyCallback callback,
5982 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);
5986 * g_dbus_connection_call_with_unix_fd_list_finish:
5987 * @connection: A #GDBusConnection.
5988 * @out_fd_list: (out) (allow-none): Return location for a #GUnixFDList or %NULL.
5989 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call_with_unix_fd_list().
5990 * @error: Return location for error or %NULL.
5992 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
5994 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5995 * return values. Free with g_variant_unref().
6000 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
6001 GUnixFDList **out_fd_list,
6005 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
6009 * g_dbus_connection_call_with_unix_fd_list_sync:
6010 * @connection: A #GDBusConnection.
6011 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
6012 * @connection is not a message bus connection.
6013 * @object_path: Path of remote object.
6014 * @interface_name: D-Bus interface to invoke method on.
6015 * @method_name: The name of the method to invoke.
6016 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
6017 * or %NULL if not passing parameters.
6018 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
6019 * @flags: Flags from the #GDBusCallFlags enumeration.
6020 * @timeout_msec: The timeout in milliseconds, -1 to use the default
6021 * timeout or %G_MAXINT for no timeout.
6022 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
6023 * @out_fd_list: (out) (allow-none): Return location for a #GUnixFDList or %NULL.
6024 * @cancellable: (allow-none): A #GCancellable or %NULL.
6025 * @error: Return location for error or %NULL.
6027 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
6029 * This method is only available on UNIX.
6031 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6032 * return values. Free with g_variant_unref().
6037 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
6038 const gchar *bus_name,
6039 const gchar *object_path,
6040 const gchar *interface_name,
6041 const gchar *method_name,
6042 GVariant *parameters,
6043 const GVariantType *reply_type,
6044 GDBusCallFlags flags,
6046 GUnixFDList *fd_list,
6047 GUnixFDList **out_fd_list,
6048 GCancellable *cancellable,
6051 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);
6054 #endif /* G_OS_UNIX */
6056 /* ---------------------------------------------------------------------------------------------------- */
6058 struct ExportedSubtree
6062 GDBusConnection *connection;
6063 GDBusSubtreeVTable *vtable;
6064 GDBusSubtreeFlags flags;
6066 GMainContext *context;
6068 GDestroyNotify user_data_free_func;
6072 exported_subtree_free (ExportedSubtree *es)
6074 call_destroy_notify (es->context,
6075 es->user_data_free_func,
6078 g_main_context_unref (es->context);
6080 _g_dbus_subtree_vtable_free (es->vtable);
6081 g_free (es->object_path);
6085 /* called without lock held in the thread where the caller registered
6089 handle_subtree_introspect (GDBusConnection *connection,
6090 ExportedSubtree *es,
6091 GDBusMessage *message)
6095 GDBusMessage *reply;
6098 const gchar *sender;
6099 const gchar *requested_object_path;
6100 const gchar *requested_node;
6101 GDBusInterfaceInfo **interfaces;
6103 gchar **subnode_paths;
6104 gboolean has_properties_interface;
6105 gboolean has_introspectable_interface;
6109 requested_object_path = g_dbus_message_get_path (message);
6110 sender = g_dbus_message_get_sender (message);
6111 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6113 s = g_string_new (NULL);
6114 introspect_append_header (s);
6116 /* Strictly we don't need the children in dynamic mode, but we avoid the
6117 * conditionals to preserve code clarity
6119 children = es->vtable->enumerate (es->connection,
6126 requested_node = strrchr (requested_object_path, '/') + 1;
6128 /* Assert existence of object if we are not dynamic */
6129 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
6130 !_g_strv_has_string ((const gchar * const *) children, requested_node))
6135 requested_node = NULL;
6138 interfaces = es->vtable->introspect (es->connection,
6143 if (interfaces != NULL)
6145 has_properties_interface = FALSE;
6146 has_introspectable_interface = FALSE;
6148 for (n = 0; interfaces[n] != NULL; n++)
6150 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
6151 has_properties_interface = TRUE;
6152 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
6153 has_introspectable_interface = TRUE;
6155 if (!has_properties_interface)
6156 g_string_append (s, introspect_properties_interface);
6157 if (!has_introspectable_interface)
6158 g_string_append (s, introspect_introspectable_interface);
6160 for (n = 0; interfaces[n] != NULL; n++)
6162 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
6163 g_dbus_interface_info_unref (interfaces[n]);
6165 g_free (interfaces);
6168 /* then include <node> entries from the Subtree for the root */
6171 for (n = 0; children != NULL && children[n] != NULL; n++)
6172 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
6175 /* finally include nodes registered below us */
6176 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
6177 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
6178 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
6179 g_strfreev (subnode_paths);
6181 g_string_append (s, "</node>\n");
6183 reply = g_dbus_message_new_method_reply (message);
6184 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6185 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6186 g_object_unref (reply);
6191 g_string_free (s, TRUE);
6192 g_strfreev (children);
6196 /* called without lock held in the thread where the caller registered
6200 handle_subtree_method_invocation (GDBusConnection *connection,
6201 ExportedSubtree *es,
6202 GDBusMessage *message)
6205 const gchar *sender;
6206 const gchar *interface_name;
6207 const gchar *member;
6208 const gchar *signature;
6209 const gchar *requested_object_path;
6210 const gchar *requested_node;
6212 GDBusInterfaceInfo *interface_info;
6213 const GDBusInterfaceVTable *interface_vtable;
6214 gpointer interface_user_data;
6216 GDBusInterfaceInfo **interfaces;
6217 gboolean is_property_get;
6218 gboolean is_property_set;
6219 gboolean is_property_get_all;
6224 requested_object_path = g_dbus_message_get_path (message);
6225 sender = g_dbus_message_get_sender (message);
6226 interface_name = g_dbus_message_get_interface (message);
6227 member = g_dbus_message_get_member (message);
6228 signature = g_dbus_message_get_signature (message);
6229 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6231 is_property_get = FALSE;
6232 is_property_set = FALSE;
6233 is_property_get_all = FALSE;
6234 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6236 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6237 is_property_get = TRUE;
6238 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6239 is_property_set = TRUE;
6240 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6241 is_property_get_all = TRUE;
6246 requested_node = strrchr (requested_object_path, '/') + 1;
6248 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6250 /* We don't want to dispatch to unenumerated
6251 * nodes, so ensure that the child exists.
6256 children = es->vtable->enumerate (es->connection,
6261 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6262 g_strfreev (children);
6270 requested_node = NULL;
6273 /* get introspection data for the node */
6274 interfaces = es->vtable->introspect (es->connection,
6276 requested_object_path,
6280 if (interfaces == NULL)
6283 interface_info = NULL;
6284 for (n = 0; interfaces[n] != NULL; n++)
6286 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6287 interface_info = interfaces[n];
6290 /* dispatch the call if the user wants to handle it */
6291 if (interface_info != NULL)
6293 /* figure out where to dispatch the method call */
6294 interface_user_data = NULL;
6295 interface_vtable = es->vtable->dispatch (es->connection,
6300 &interface_user_data,
6302 if (interface_vtable == NULL)
6305 CONNECTION_LOCK (connection);
6306 handled = validate_and_maybe_schedule_method_call (es->connection,
6313 interface_user_data);
6314 CONNECTION_UNLOCK (connection);
6316 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6317 else if (is_property_get || is_property_set || is_property_get_all)
6319 if (is_property_get)
6320 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6321 else if (is_property_set)
6322 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6323 else if (is_property_get_all)
6324 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6326 g_assert_not_reached ();
6328 /* see if the object supports this interface at all */
6329 for (n = 0; interfaces[n] != NULL; n++)
6331 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6332 interface_info = interfaces[n];
6335 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6336 * claims it won't support the interface
6338 if (interface_info == NULL)
6340 GDBusMessage *reply;
6341 reply = g_dbus_message_new_method_error (message,
6342 "org.freedesktop.DBus.Error.InvalidArgs",
6343 _("No such interface '%s'"),
6345 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6346 g_object_unref (reply);
6351 /* figure out where to dispatch the property get/set/getall calls */
6352 interface_user_data = NULL;
6353 interface_vtable = es->vtable->dispatch (es->connection,
6358 &interface_user_data,
6360 if (interface_vtable == NULL)
6362 g_warning ("The subtree introspection function indicates that '%s' "
6363 "is a valid interface name, but calling the dispatch "
6364 "function on that interface gave us NULL", interface_name);
6368 if (is_property_get || is_property_set)
6370 CONNECTION_LOCK (connection);
6371 handled = validate_and_maybe_schedule_property_getset (es->connection,
6379 interface_user_data);
6380 CONNECTION_UNLOCK (connection);
6382 else if (is_property_get_all)
6384 CONNECTION_LOCK (connection);
6385 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6392 interface_user_data);
6393 CONNECTION_UNLOCK (connection);
6398 if (interfaces != NULL)
6400 for (n = 0; interfaces[n] != NULL; n++)
6401 g_dbus_interface_info_unref (interfaces[n]);
6402 g_free (interfaces);
6410 GDBusMessage *message;
6411 ExportedSubtree *es;
6412 } SubtreeDeferredData;
6415 subtree_deferred_data_free (SubtreeDeferredData *data)
6417 g_object_unref (data->message);
6421 /* called without lock held in the thread where the caller registered the subtree */
6423 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6425 SubtreeDeferredData *data = _data;
6430 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6431 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6432 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6433 handled = handle_subtree_introspect (data->es->connection,
6437 handled = handle_subtree_method_invocation (data->es->connection,
6443 CONNECTION_LOCK (data->es->connection);
6444 handled = handle_generic_unlocked (data->es->connection, data->message);
6445 CONNECTION_UNLOCK (data->es->connection);
6448 /* if we couldn't handle the request, just bail with the UnknownMethod error */
6451 GDBusMessage *reply;
6452 reply = g_dbus_message_new_method_error (data->message,
6453 "org.freedesktop.DBus.Error.UnknownMethod",
6454 _("Method '%s' on interface '%s' with signature '%s' does not exist"),
6455 g_dbus_message_get_member (data->message),
6456 g_dbus_message_get_interface (data->message),
6457 g_dbus_message_get_signature (data->message));
6458 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6459 g_object_unref (reply);
6465 /* called in GDBusWorker thread with connection's lock held */
6467 subtree_message_func (GDBusConnection *connection,
6468 ExportedSubtree *es,
6469 GDBusMessage *message)
6471 GSource *idle_source;
6472 SubtreeDeferredData *data;
6474 data = g_new0 (SubtreeDeferredData, 1);
6475 data->message = g_object_ref (message);
6478 /* defer this call to an idle handler in the right thread */
6479 idle_source = g_idle_source_new ();
6480 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
6481 g_source_set_callback (idle_source,
6482 process_subtree_vtable_message_in_idle_cb,
6484 (GDestroyNotify) subtree_deferred_data_free);
6485 g_source_attach (idle_source, es->context);
6486 g_source_unref (idle_source);
6488 /* since we own the entire subtree, handlers for objects not in the subtree have been
6489 * tried already by libdbus-1 - so we just need to ensure that we're always going
6490 * to reply to the message
6496 * g_dbus_connection_register_subtree:
6497 * @connection: A #GDBusConnection.
6498 * @object_path: The object path to register the subtree at.
6499 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
6500 * @flags: Flags used to fine tune the behavior of the subtree.
6501 * @user_data: Data to pass to functions in @vtable.
6502 * @user_data_free_func: Function to call when the subtree is unregistered.
6503 * @error: Return location for error or %NULL.
6505 * Registers a whole subtree of <quote>dynamic</quote> objects.
6507 * The @enumerate and @introspection functions in @vtable are used to
6508 * convey, to remote callers, what nodes exist in the subtree rooted
6511 * When handling remote calls into any node in the subtree, first the
6512 * @enumerate function is used to check if the node exists. If the node exists
6513 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6514 * the @introspection function is used to check if the node supports the
6515 * requested method. If so, the @dispatch function is used to determine
6516 * where to dispatch the call. The collected #GDBusInterfaceVTable and
6517 * #gpointer will be used to call into the interface vtable for processing
6520 * All calls into user-provided code will be invoked in the <link
6521 * linkend="g-main-context-push-thread-default">thread-default main
6522 * loop</link> of the thread you are calling this method from.
6524 * If an existing subtree is already registered at @object_path or
6525 * then @error is set to #G_IO_ERROR_EXISTS.
6527 * Note that it is valid to register regular objects (using
6528 * g_dbus_connection_register_object()) in a subtree registered with
6529 * g_dbus_connection_register_subtree() - if so, the subtree handler
6530 * is tried as the last resort. One way to think about a subtree
6531 * handler is to consider it a <quote>fallback handler</quote>
6532 * for object paths not registered via g_dbus_connection_register_object()
6533 * or other bindings.
6535 * Note that @vtable will be copied so you cannot change it after
6538 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
6540 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
6541 * that can be used with g_dbus_connection_unregister_subtree() .
6546 g_dbus_connection_register_subtree (GDBusConnection *connection,
6547 const gchar *object_path,
6548 const GDBusSubtreeVTable *vtable,
6549 GDBusSubtreeFlags flags,
6551 GDestroyNotify user_data_free_func,
6555 ExportedSubtree *es;
6557 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
6558 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
6559 g_return_val_if_fail (vtable != NULL, 0);
6560 g_return_val_if_fail (error == NULL || *error == NULL, 0);
6561 g_return_val_if_fail (check_initialized (connection), 0);
6565 CONNECTION_LOCK (connection);
6567 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6573 _("A subtree is already exported for %s"),
6578 es = g_new0 (ExportedSubtree, 1);
6579 es->object_path = g_strdup (object_path);
6580 es->connection = connection;
6582 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
6584 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
6585 es->user_data = user_data;
6586 es->user_data_free_func = user_data_free_func;
6587 es->context = g_main_context_ref_thread_default ();
6589 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
6590 g_hash_table_insert (connection->map_id_to_es,
6591 GUINT_TO_POINTER (es->id),
6597 CONNECTION_UNLOCK (connection);
6602 /* ---------------------------------------------------------------------------------------------------- */
6605 * g_dbus_connection_unregister_subtree:
6606 * @connection: A #GDBusConnection.
6607 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
6609 * Unregisters a subtree.
6611 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
6616 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
6617 guint registration_id)
6619 ExportedSubtree *es;
6622 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
6623 g_return_val_if_fail (check_initialized (connection), FALSE);
6627 CONNECTION_LOCK (connection);
6629 es = g_hash_table_lookup (connection->map_id_to_es,
6630 GUINT_TO_POINTER (registration_id));
6634 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
6635 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
6640 CONNECTION_UNLOCK (connection);
6645 /* ---------------------------------------------------------------------------------------------------- */
6647 /* may be called in any thread, with connection's lock held */
6649 handle_generic_ping_unlocked (GDBusConnection *connection,
6650 const gchar *object_path,
6651 GDBusMessage *message)
6653 GDBusMessage *reply;
6654 reply = g_dbus_message_new_method_reply (message);
6655 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6656 g_object_unref (reply);
6659 /* may be called in any thread, with connection's lock held */
6661 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
6662 const gchar *object_path,
6663 GDBusMessage *message)
6665 GDBusMessage *reply;
6668 if (connection->machine_id == NULL)
6673 connection->machine_id = _g_dbus_get_machine_id (&error);
6674 if (connection->machine_id == NULL)
6676 reply = g_dbus_message_new_method_error_literal (message,
6677 "org.freedesktop.DBus.Error.Failed",
6679 g_error_free (error);
6685 reply = g_dbus_message_new_method_reply (message);
6686 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
6688 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6689 g_object_unref (reply);
6692 /* may be called in any thread, with connection's lock held */
6694 handle_generic_introspect_unlocked (GDBusConnection *connection,
6695 const gchar *object_path,
6696 GDBusMessage *message)
6701 GDBusMessage *reply;
6703 /* first the header */
6704 s = g_string_new (NULL);
6705 introspect_append_header (s);
6707 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
6708 for (n = 0; registered != NULL && registered[n] != NULL; n++)
6709 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
6710 g_strfreev (registered);
6711 g_string_append (s, "</node>\n");
6713 reply = g_dbus_message_new_method_reply (message);
6714 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6715 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6716 g_object_unref (reply);
6717 g_string_free (s, TRUE);
6720 /* may be called in any thread, with connection's lock held */
6722 handle_generic_unlocked (GDBusConnection *connection,
6723 GDBusMessage *message)
6726 const gchar *interface_name;
6727 const gchar *member;
6728 const gchar *signature;
6731 CONNECTION_ENSURE_LOCK (connection);
6735 interface_name = g_dbus_message_get_interface (message);
6736 member = g_dbus_message_get_member (message);
6737 signature = g_dbus_message_get_signature (message);
6738 path = g_dbus_message_get_path (message);
6740 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
6741 g_strcmp0 (member, "Introspect") == 0 &&
6742 g_strcmp0 (signature, "") == 0)
6744 handle_generic_introspect_unlocked (connection, path, message);
6747 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6748 g_strcmp0 (member, "Ping") == 0 &&
6749 g_strcmp0 (signature, "") == 0)
6751 handle_generic_ping_unlocked (connection, path, message);
6754 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6755 g_strcmp0 (member, "GetMachineId") == 0 &&
6756 g_strcmp0 (signature, "") == 0)
6758 handle_generic_get_machine_id_unlocked (connection, path, message);
6765 /* ---------------------------------------------------------------------------------------------------- */
6767 /* called in GDBusWorker thread with connection's lock held */
6769 distribute_method_call (GDBusConnection *connection,
6770 GDBusMessage *message)
6772 GDBusMessage *reply;
6774 ExportedSubtree *es;
6775 const gchar *object_path;
6776 const gchar *interface_name;
6777 const gchar *member;
6779 gchar *subtree_path;
6782 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
6784 interface_name = g_dbus_message_get_interface (message);
6785 member = g_dbus_message_get_member (message);
6786 path = g_dbus_message_get_path (message);
6787 subtree_path = g_strdup (path);
6788 needle = strrchr (subtree_path, '/');
6789 if (needle != NULL && needle != subtree_path)
6795 g_free (subtree_path);
6796 subtree_path = NULL;
6800 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
6802 _g_dbus_debug_print_lock ();
6803 g_print ("========================================================================\n"
6804 "GDBus-debug:Incoming:\n"
6805 " <<<< METHOD INVOCATION %s.%s()\n"
6807 " invoked by name %s\n"
6809 interface_name, member,
6811 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
6812 g_dbus_message_get_serial (message));
6813 _g_dbus_debug_print_unlock ();
6816 object_path = g_dbus_message_get_path (message);
6817 g_assert (object_path != NULL);
6819 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
6822 if (obj_message_func (connection, eo, message))
6826 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6829 if (subtree_message_func (connection, es, message))
6833 if (subtree_path != NULL)
6835 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
6838 if (subtree_message_func (connection, es, message))
6843 if (handle_generic_unlocked (connection, message))
6846 /* if we end up here, the message has not been not handled - so return an error saying this */
6847 reply = g_dbus_message_new_method_error (message,
6848 "org.freedesktop.DBus.Error.UnknownMethod",
6849 _("No such interface '%s' on object at path %s"),
6852 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6853 g_object_unref (reply);
6856 g_free (subtree_path);
6859 /* ---------------------------------------------------------------------------------------------------- */
6861 /* Called in any user thread, with the message_bus_lock held. */
6863 message_bus_get_singleton (GBusType bus_type,
6867 const gchar *starter_bus;
6873 case G_BUS_TYPE_SESSION:
6874 ret = &the_session_bus;
6877 case G_BUS_TYPE_SYSTEM:
6878 ret = &the_system_bus;
6881 case G_BUS_TYPE_STARTER:
6882 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
6883 if (g_strcmp0 (starter_bus, "session") == 0)
6885 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
6888 else if (g_strcmp0 (starter_bus, "system") == 0)
6890 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
6895 if (starter_bus != NULL)
6899 G_IO_ERROR_INVALID_ARGUMENT,
6900 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
6901 " - unknown value '%s'"),
6906 g_set_error_literal (error,
6908 G_IO_ERROR_INVALID_ARGUMENT,
6909 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
6910 "variable is not set"));
6916 g_assert_not_reached ();
6924 /* Called in any user thread, without holding locks. */
6925 static GDBusConnection *
6926 get_uninitialized_connection (GBusType bus_type,
6927 GCancellable *cancellable,
6930 GWeakRef *singleton;
6931 GDBusConnection *ret;
6935 G_LOCK (message_bus_lock);
6936 singleton = message_bus_get_singleton (bus_type, error);
6937 if (singleton == NULL)
6940 ret = g_weak_ref_get (singleton);
6945 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
6946 if (address == NULL)
6948 ret = g_object_new (G_TYPE_DBUS_CONNECTION,
6950 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
6951 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
6952 "exit-on-close", TRUE,
6955 g_weak_ref_set (singleton, ret);
6959 g_assert (ret != NULL);
6962 G_UNLOCK (message_bus_lock);
6966 /* May be called from any thread. Must not hold message_bus_lock. */
6968 _g_bus_get_singleton_if_exists (GBusType bus_type)
6970 GWeakRef *singleton;
6971 GDBusConnection *ret = NULL;
6973 G_LOCK (message_bus_lock);
6974 singleton = message_bus_get_singleton (bus_type, NULL);
6975 if (singleton == NULL)
6978 ret = g_weak_ref_get (singleton);
6981 G_UNLOCK (message_bus_lock);
6987 * @bus_type: A #GBusType.
6988 * @cancellable: (allow-none): A #GCancellable or %NULL.
6989 * @error: Return location for error or %NULL.
6991 * Synchronously connects to the message bus specified by @bus_type.
6992 * Note that the returned object may shared with other callers,
6993 * e.g. if two separate parts of a process calls this function with
6994 * the same @bus_type, they will share the same object.
6996 * This is a synchronous failable function. See g_bus_get() and
6997 * g_bus_get_finish() for the asynchronous version.
6999 * The returned object is a singleton, that is, shared with other
7000 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7001 * event that you need a private message bus connection, use
7002 * g_dbus_address_get_for_bus_sync() and
7003 * g_dbus_connection_new_for_address().
7005 * Note that the returned #GDBusConnection object will (usually) have
7006 * the #GDBusConnection:exit-on-close property set to %TRUE.
7008 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
7013 g_bus_get_sync (GBusType bus_type,
7014 GCancellable *cancellable,
7017 GDBusConnection *connection;
7019 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7021 connection = get_uninitialized_connection (bus_type, cancellable, error);
7022 if (connection == NULL)
7025 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
7027 g_object_unref (connection);
7036 bus_get_async_initable_cb (GObject *source_object,
7040 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
7044 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
7048 g_assert (error != NULL);
7049 g_simple_async_result_take_error (simple, error);
7050 g_object_unref (source_object);
7054 g_simple_async_result_set_op_res_gpointer (simple,
7058 g_simple_async_result_complete_in_idle (simple);
7059 g_object_unref (simple);
7064 * @bus_type: A #GBusType.
7065 * @cancellable: (allow-none): A #GCancellable or %NULL.
7066 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
7067 * @user_data: The data to pass to @callback.
7069 * Asynchronously connects to the message bus specified by @bus_type.
7071 * When the operation is finished, @callback will be invoked. You can
7072 * then call g_bus_get_finish() to get the result of the operation.
7074 * This is a asynchronous failable function. See g_bus_get_sync() for
7075 * the synchronous version.
7080 g_bus_get (GBusType bus_type,
7081 GCancellable *cancellable,
7082 GAsyncReadyCallback callback,
7085 GDBusConnection *connection;
7086 GSimpleAsyncResult *simple;
7089 simple = g_simple_async_result_new (NULL,
7093 g_simple_async_result_set_check_cancellable (simple, cancellable);
7096 connection = get_uninitialized_connection (bus_type, cancellable, &error);
7097 if (connection == NULL)
7099 g_assert (error != NULL);
7100 g_simple_async_result_take_error (simple, error);
7101 g_simple_async_result_complete_in_idle (simple);
7102 g_object_unref (simple);
7106 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
7109 bus_get_async_initable_cb,
7116 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
7117 * @error: Return location for error or %NULL.
7119 * Finishes an operation started with g_bus_get().
7121 * The returned object is a singleton, that is, shared with other
7122 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7123 * event that you need a private message bus connection, use
7124 * g_dbus_address_get_for_bus_sync() and
7125 * g_dbus_connection_new_for_address().
7127 * Note that the returned #GDBusConnection object will (usually) have
7128 * the #GDBusConnection:exit-on-close property set to %TRUE.
7130 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
7135 g_bus_get_finish (GAsyncResult *res,
7138 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
7140 GDBusConnection *ret;
7142 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7144 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
7148 if (g_simple_async_result_propagate_error (simple, error))
7151 object = g_simple_async_result_get_op_res_gpointer (simple);
7152 g_assert (object != NULL);
7153 ret = g_object_ref (G_DBUS_CONNECTION (object));
7159 /* ---------------------------------------------------------------------------------------------------- */