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 be
148 * used by two threads at the same time, #GDBusConnection's methods may be
149 * called from any thread<footnote>
151 * This is so that g_bus_get() and g_bus_get_sync() can safely return the
152 * same #GDBusConnection when called from any thread.
156 * Most of the ways to obtain a #GDBusConnection automatically initialize it
157 * (i.e. connect to D-Bus): for instance, g_dbus_connection_new() and
158 * g_bus_get(), and the synchronous versions of those methods, give you an
159 * initialized connection. Language bindings for GIO should use
160 * g_initable_new() or g_async_initable_new_async(), which also initialize the
163 * If you construct an uninitialized #GDBusConnection, such as via
164 * g_object_new(), you must initialize it via g_initable_init() or
165 * g_async_initable_init_async() before using its methods or properties.
166 * Calling methods or accessing properties on a #GDBusConnection that has not
167 * completed initialization successfully is considered to be invalid, and leads
168 * to undefined behaviour. In particular, if initialization fails with a
169 * #GError, the only valid thing you can do with that #GDBusConnection is to
170 * free it with g_object_unref().
172 * <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>
174 * <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>
176 * <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>
178 * <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>
181 /* ---------------------------------------------------------------------------------------------------- */
183 typedef struct _GDBusConnectionClass GDBusConnectionClass;
186 * GDBusConnectionClass:
187 * @closed: Signal class handler for the #GDBusConnection::closed signal.
189 * Class structure for #GDBusConnection.
193 struct _GDBusConnectionClass
196 GObjectClass parent_class;
200 void (*closed) (GDBusConnection *connection,
201 gboolean remote_peer_vanished,
205 G_LOCK_DEFINE_STATIC (message_bus_lock);
207 static GWeakRef the_session_bus;
208 static GWeakRef the_system_bus;
210 /* Extra pseudo-member of GDBusSendMessageFlags.
211 * Set by initable_init() to indicate that despite not being initialized yet,
212 * enough of the only-valid-after-init members are set that we can send a
213 * message, and we're being called from its thread, so no memory barrier is
214 * required before accessing them.
216 #define SEND_MESSAGE_FLAGS_INITIALIZING (1<<31)
218 /* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
219 #define CALL_FLAGS_INITIALIZING (1<<31)
221 /* ---------------------------------------------------------------------------------------------------- */
225 GDestroyNotify callback;
227 GMainContext *context;
228 } CallDestroyNotifyData;
231 call_destroy_notify_data_in_idle (gpointer user_data)
233 CallDestroyNotifyData *data = user_data;
234 data->callback (data->user_data);
239 call_destroy_notify_data_free (CallDestroyNotifyData *data)
241 if (data->context != NULL)
242 g_main_context_unref (data->context);
247 * call_destroy_notify: <internal>
248 * @context: (allow-none): A #GMainContext or %NULL.
249 * @callback: (allow-none): A #GDestroyNotify or %NULL.
250 * @user_data: Data to pass to @callback.
252 * Schedules @callback to run in @context.
255 call_destroy_notify (GMainContext *context,
256 GDestroyNotify callback,
259 GSource *idle_source;
260 CallDestroyNotifyData *data;
262 if (callback == NULL)
265 data = g_new0 (CallDestroyNotifyData, 1);
266 data->callback = callback;
267 data->user_data = user_data;
268 data->context = context;
269 if (data->context != NULL)
270 g_main_context_ref (data->context);
272 idle_source = g_idle_source_new ();
273 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
274 g_source_set_callback (idle_source,
275 call_destroy_notify_data_in_idle,
277 (GDestroyNotify) call_destroy_notify_data_free);
278 g_source_attach (idle_source, data->context);
279 g_source_unref (idle_source);
285 /* ---------------------------------------------------------------------------------------------------- */
288 _g_strv_has_string (const gchar* const *haystack,
293 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
295 if (g_strcmp0 (haystack[n], needle) == 0)
301 /* ---------------------------------------------------------------------------------------------------- */
304 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
306 // TODO: for some reason this doesn't work on Windows
307 #define CONNECTION_ENSURE_LOCK(obj) do { \
308 if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock))) \
310 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
311 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
316 #define CONNECTION_LOCK(obj) do { \
317 g_mutex_lock (&(obj)->lock); \
320 #define CONNECTION_UNLOCK(obj) do { \
321 g_mutex_unlock (&(obj)->lock); \
324 /* Flags in connection->atomic_flags */
326 FLAG_INITIALIZED = 1 << 0,
327 FLAG_EXIT_ON_CLOSE = 1 << 1,
334 * The #GDBusConnection structure contains only private data and
335 * should only be accessed using the provided API.
339 struct _GDBusConnection
342 GObject parent_instance;
344 /* ------------------------------------------------------------------------ */
345 /* -- General object state ------------------------------------------------ */
346 /* ------------------------------------------------------------------------ */
348 /* General-purpose lock for most fields */
351 /* A lock used in the init() method of the GInitable interface - see comments
352 * in initable_init() for why a separate lock is needed.
354 * If you need both @lock and @init_lock, you must take @init_lock first.
358 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
359 * someone calls org.freedesktop.DBus.GetMachineId(). Protected by @lock.
363 /* The underlying stream used for communication
364 * Read-only after initable_init(), so it may be read if you either
365 * hold @init_lock or check for initialization first.
369 /* The object used for authentication (if any).
370 * Read-only after initable_init(), so it may be read if you either
371 * hold @init_lock or check for initialization first.
375 /* Last serial used. Protected by @lock. */
378 /* The object used to send/receive messages.
379 * Read-only after initable_init(), so it may be read if you either
380 * hold @init_lock or check for initialization first.
384 /* If connected to a message bus, this contains the unique name assigned to
385 * us by the bus (e.g. ":1.42").
386 * Read-only after initable_init(), so it may be read if you either
387 * hold @init_lock or check for initialization first.
389 gchar *bus_unique_name;
391 /* The GUID returned by the other side if we authenticed as a client or
392 * the GUID to use if authenticating as a server.
393 * Read-only after initable_init(), so it may be read if you either
394 * hold @init_lock or check for initialization first.
398 /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
399 * Inspect @initialization_error to see whether it succeeded or failed.
401 * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
403 * FLAG_CLOSED is the closed property. It may be read at any time, but
404 * may only be written while holding @lock.
406 volatile gint atomic_flags;
408 /* If the connection could not be established during initable_init(),
409 * this GError will be set.
410 * Read-only after initable_init(), so it may be read if you either
411 * hold @init_lock or check for initialization first.
413 GError *initialization_error;
415 /* The result of g_main_context_ref_thread_default() when the object
416 * was created (the GObject _init() function) - this is used for delivery
417 * of the :closed GObject signal.
419 * Only set in the GObject init function, so no locks are needed.
421 GMainContext *main_context_at_construction;
423 /* Read-only construct properties, no locks needed */
425 GDBusConnectionFlags flags;
427 /* Map used for managing method replies, protected by @lock */
428 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
430 /* Maps used for managing signal subscription, protected by @lock */
431 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
432 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
433 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
435 /* Maps used for managing exported objects and subtrees,
438 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
439 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
440 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
441 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
443 /* Map used for storing last used serials for each thread, protected by @lock */
444 GHashTable *map_thread_to_last_serial;
446 /* Structure used for message filters, protected by @lock */
449 /* Capabilities negotiated during authentication
450 * Read-only after initable_init(), so it may be read without holding a
451 * lock, if you check for initialization first.
453 GDBusCapabilityFlags capabilities;
455 /* Protected by @init_lock */
456 GDBusAuthObserver *authentication_observer;
458 /* Read-only after initable_init(), so it may be read if you either
459 * hold @init_lock or check for initialization first.
461 GCredentials *credentials;
463 /* set to TRUE when finalizing */
467 typedef struct ExportedObject ExportedObject;
468 static void exported_object_free (ExportedObject *eo);
470 typedef struct ExportedSubtree ExportedSubtree;
471 static void exported_subtree_free (ExportedSubtree *es);
489 PROP_CAPABILITY_FLAGS,
490 PROP_AUTHENTICATION_OBSERVER,
493 static void distribute_signals (GDBusConnection *connection,
494 GDBusMessage *message);
496 static void distribute_method_call (GDBusConnection *connection,
497 GDBusMessage *message);
499 static gboolean handle_generic_unlocked (GDBusConnection *connection,
500 GDBusMessage *message);
503 static void purge_all_signal_subscriptions (GDBusConnection *connection);
504 static void purge_all_filters (GDBusConnection *connection);
506 static void schedule_method_call (GDBusConnection *connection,
507 GDBusMessage *message,
508 guint registration_id,
509 guint subtree_registration_id,
510 const GDBusInterfaceInfo *interface_info,
511 const GDBusMethodInfo *method_info,
512 const GDBusPropertyInfo *property_info,
513 GVariant *parameters,
514 const GDBusInterfaceVTable *vtable,
515 GMainContext *main_context,
518 #define _G_ENSURE_LOCK(name) do { \
519 if (G_UNLIKELY (G_TRYLOCK(name))) \
521 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
522 "_G_ENSURE_LOCK: Lock '" #name "' is not locked"); \
526 static guint signals[LAST_SIGNAL] = { 0 };
528 static void initable_iface_init (GInitableIface *initable_iface);
529 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
531 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
532 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
533 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
537 * Check that all members of @connection that can only be accessed after
538 * the connection is initialized can safely be accessed. If not,
539 * log a critical warning. This function is a memory barrier.
541 * Returns: %TRUE if initialized
544 check_initialized (GDBusConnection *connection)
546 /* The access to @atomic_flags isn't conditional, so that this function
547 * provides a memory barrier for thread-safety even if checks are disabled.
548 * (If you don't want this stricter guarantee, you can call
549 * g_return_if_fail (check_initialized (c)).)
551 * This isn't strictly necessary now that we've decided use of an
552 * uninitialized GDBusConnection is undefined behaviour, but it seems
553 * better to be as deterministic as is feasible.
555 * (Anything that could suffer a crash from seeing undefined values
556 * must have a race condition - thread A initializes the connection while
557 * thread B calls a method without initialization, hoping that thread A will
558 * win the race - so its behaviour is undefined anyway.)
560 gint flags = g_atomic_int_get (&connection->atomic_flags);
562 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
564 /* We can safely access this, due to the memory barrier above */
565 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
571 MAY_BE_UNINITIALIZED = (1<<1)
572 } CheckUnclosedFlags;
575 * Check the same thing as check_initialized(), and also that the
576 * connection is not closed. If the connection is uninitialized,
577 * raise a critical warning (it's programmer error); if it's closed,
578 * raise a recoverable GError (it's a runtime error).
580 * This function is a memory barrier.
582 * Returns: %TRUE if initialized and not closed
585 check_unclosed (GDBusConnection *connection,
586 CheckUnclosedFlags check,
589 /* check_initialized() is effectively inlined, so we don't waste time
590 * doing two memory barriers
592 gint flags = g_atomic_int_get (&connection->atomic_flags);
594 if (!(check & MAY_BE_UNINITIALIZED))
596 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
597 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
600 if (flags & FLAG_CLOSED)
602 g_set_error_literal (error,
605 _("The connection is closed"));
612 static GHashTable *alive_connections = NULL;
615 g_dbus_connection_dispose (GObject *object)
617 GDBusConnection *connection = G_DBUS_CONNECTION (object);
619 G_LOCK (message_bus_lock);
620 CONNECTION_LOCK (connection);
621 if (connection->worker != NULL)
623 _g_dbus_worker_stop (connection->worker);
624 connection->worker = NULL;
625 if (alive_connections != NULL)
626 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
630 if (alive_connections != NULL)
631 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
633 CONNECTION_UNLOCK (connection);
634 G_UNLOCK (message_bus_lock);
636 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
637 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
641 g_dbus_connection_finalize (GObject *object)
643 GDBusConnection *connection = G_DBUS_CONNECTION (object);
645 connection->finalizing = TRUE;
647 purge_all_signal_subscriptions (connection);
649 purge_all_filters (connection);
650 g_ptr_array_unref (connection->filters);
652 if (connection->authentication_observer != NULL)
653 g_object_unref (connection->authentication_observer);
655 if (connection->auth != NULL)
656 g_object_unref (connection->auth);
658 if (connection->credentials)
659 g_object_unref (connection->credentials);
661 if (connection->stream != NULL)
663 g_object_unref (connection->stream);
664 connection->stream = NULL;
667 g_free (connection->address);
669 g_free (connection->guid);
670 g_free (connection->bus_unique_name);
672 if (connection->initialization_error != NULL)
673 g_error_free (connection->initialization_error);
675 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
677 g_hash_table_unref (connection->map_rule_to_signal_data);
678 g_hash_table_unref (connection->map_id_to_signal_data);
679 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
681 g_hash_table_unref (connection->map_id_to_ei);
682 g_hash_table_unref (connection->map_object_path_to_eo);
683 g_hash_table_unref (connection->map_id_to_es);
684 g_hash_table_unref (connection->map_object_path_to_es);
686 g_hash_table_unref (connection->map_thread_to_last_serial);
688 g_main_context_unref (connection->main_context_at_construction);
690 g_free (connection->machine_id);
692 g_mutex_clear (&connection->init_lock);
693 g_mutex_clear (&connection->lock);
695 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
698 /* called in any user thread, with the connection's lock not held */
700 g_dbus_connection_get_property (GObject *object,
705 GDBusConnection *connection = G_DBUS_CONNECTION (object);
710 g_value_set_object (value, g_dbus_connection_get_stream (connection));
714 g_value_set_string (value, g_dbus_connection_get_guid (connection));
717 case PROP_UNIQUE_NAME:
718 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
722 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
725 case PROP_EXIT_ON_CLOSE:
726 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
729 case PROP_CAPABILITY_FLAGS:
730 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
734 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
739 /* called in any user thread, with the connection's lock not held */
741 g_dbus_connection_set_property (GObject *object,
746 GDBusConnection *connection = G_DBUS_CONNECTION (object);
751 connection->stream = g_value_dup_object (value);
755 connection->guid = g_value_dup_string (value);
759 connection->address = g_value_dup_string (value);
763 connection->flags = g_value_get_flags (value);
766 case PROP_EXIT_ON_CLOSE:
767 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
770 case PROP_AUTHENTICATION_OBSERVER:
771 connection->authentication_observer = g_value_dup_object (value);
775 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
780 /* Base-class implementation of GDBusConnection::closed.
782 * Called in a user thread, by the main context that was thread-default when
783 * the object was constructed.
786 g_dbus_connection_real_closed (GDBusConnection *connection,
787 gboolean remote_peer_vanished,
790 gint flags = g_atomic_int_get (&connection->atomic_flags);
792 /* Because atomic int access is a memory barrier, we can safely read
793 * initialization_error without a lock, as long as we do it afterwards.
795 if (remote_peer_vanished &&
796 (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
797 (flags & FLAG_INITIALIZED) != 0 &&
798 connection->initialization_error == NULL)
802 g_print ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
805 g_quark_to_string (error->domain), error->code);
809 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
816 g_dbus_connection_class_init (GDBusConnectionClass *klass)
818 GObjectClass *gobject_class;
820 gobject_class = G_OBJECT_CLASS (klass);
822 gobject_class->finalize = g_dbus_connection_finalize;
823 gobject_class->dispose = g_dbus_connection_dispose;
824 gobject_class->set_property = g_dbus_connection_set_property;
825 gobject_class->get_property = g_dbus_connection_get_property;
827 klass->closed = g_dbus_connection_real_closed;
830 * GDBusConnection:stream:
832 * The underlying #GIOStream used for I/O.
834 * If this is passed on construction and is a #GSocketConnection,
835 * then the corresponding #GSocket will be put into non-blocking mode.
837 * While the #GDBusConnection is active, it will interact with this
838 * stream from a worker thread, so it is not safe to interact with
839 * the stream directly.
843 g_object_class_install_property (gobject_class,
845 g_param_spec_object ("stream",
847 P_("The underlying streams used for I/O"),
851 G_PARAM_CONSTRUCT_ONLY |
852 G_PARAM_STATIC_NAME |
853 G_PARAM_STATIC_BLURB |
854 G_PARAM_STATIC_NICK));
857 * GDBusConnection:address:
859 * A D-Bus address specifying potential endpoints that can be used
860 * when establishing the connection.
864 g_object_class_install_property (gobject_class,
866 g_param_spec_string ("address",
868 P_("D-Bus address specifying potential socket endpoints"),
871 G_PARAM_CONSTRUCT_ONLY |
872 G_PARAM_STATIC_NAME |
873 G_PARAM_STATIC_BLURB |
874 G_PARAM_STATIC_NICK));
877 * GDBusConnection:flags:
879 * Flags from the #GDBusConnectionFlags enumeration.
883 g_object_class_install_property (gobject_class,
885 g_param_spec_flags ("flags",
888 G_TYPE_DBUS_CONNECTION_FLAGS,
889 G_DBUS_CONNECTION_FLAGS_NONE,
891 G_PARAM_CONSTRUCT_ONLY |
892 G_PARAM_STATIC_NAME |
893 G_PARAM_STATIC_BLURB |
894 G_PARAM_STATIC_NICK));
897 * GDBusConnection:guid:
899 * The GUID of the peer performing the role of server when
902 * If you are constructing a #GDBusConnection and pass
903 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
904 * #GDBusConnection:flags property then you MUST also set this
905 * property to a valid guid.
907 * If you are constructing a #GDBusConnection and pass
908 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
909 * #GDBusConnection:flags property you will be able to read the GUID
910 * of the other peer here after the connection has been successfully
915 g_object_class_install_property (gobject_class,
917 g_param_spec_string ("guid",
919 P_("GUID of the server peer"),
923 G_PARAM_CONSTRUCT_ONLY |
924 G_PARAM_STATIC_NAME |
925 G_PARAM_STATIC_BLURB |
926 G_PARAM_STATIC_NICK));
929 * GDBusConnection:unique-name:
931 * The unique name as assigned by the message bus or %NULL if the
932 * connection is not open or not a message bus connection.
936 g_object_class_install_property (gobject_class,
938 g_param_spec_string ("unique-name",
940 P_("Unique name of bus connection"),
943 G_PARAM_STATIC_NAME |
944 G_PARAM_STATIC_BLURB |
945 G_PARAM_STATIC_NICK));
948 * GDBusConnection:closed:
950 * A boolean specifying whether the connection has been closed.
954 g_object_class_install_property (gobject_class,
956 g_param_spec_boolean ("closed",
958 P_("Whether the connection is closed"),
961 G_PARAM_STATIC_NAME |
962 G_PARAM_STATIC_BLURB |
963 G_PARAM_STATIC_NICK));
966 * GDBusConnection:exit-on-close:
968 * A boolean specifying whether the process will be terminated (by
969 * calling <literal>raise(SIGTERM)</literal>) if the connection
970 * is closed by the remote peer.
972 * Note that #GDBusConnection objects returned by g_bus_get_finish() and
973 * g_bus_get_sync() will (usually) have this property set to %TRUE.
977 g_object_class_install_property (gobject_class,
979 g_param_spec_boolean ("exit-on-close",
981 P_("Whether the process is terminated when the connection is closed"),
985 G_PARAM_STATIC_NAME |
986 G_PARAM_STATIC_BLURB |
987 G_PARAM_STATIC_NICK));
990 * GDBusConnection:capabilities:
992 * Flags from the #GDBusCapabilityFlags enumeration
993 * representing connection features negotiated with the other peer.
997 g_object_class_install_property (gobject_class,
998 PROP_CAPABILITY_FLAGS,
999 g_param_spec_flags ("capabilities",
1002 G_TYPE_DBUS_CAPABILITY_FLAGS,
1003 G_DBUS_CAPABILITY_FLAGS_NONE,
1005 G_PARAM_STATIC_NAME |
1006 G_PARAM_STATIC_BLURB |
1007 G_PARAM_STATIC_NICK));
1010 * GDBusConnection:authentication-observer:
1012 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
1016 g_object_class_install_property (gobject_class,
1017 PROP_AUTHENTICATION_OBSERVER,
1018 g_param_spec_object ("authentication-observer",
1019 P_("Authentication Observer"),
1020 P_("Object used to assist in the authentication process"),
1021 G_TYPE_DBUS_AUTH_OBSERVER,
1023 G_PARAM_CONSTRUCT_ONLY |
1024 G_PARAM_STATIC_NAME |
1025 G_PARAM_STATIC_BLURB |
1026 G_PARAM_STATIC_NICK));
1029 * GDBusConnection::closed:
1030 * @connection: The #GDBusConnection emitting the signal.
1031 * @remote_peer_vanished: %TRUE if @connection is closed because the
1032 * remote peer closed its end of the connection.
1033 * @error: (allow-none): A #GError with more details about the event or %NULL.
1035 * Emitted when the connection is closed.
1037 * The cause of this event can be
1040 * If g_dbus_connection_close() is called. In this case
1041 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
1042 * </para></listitem>
1044 * If the remote peer closes the connection. In this case
1045 * @remote_peer_vanished is set to %TRUE and @error is set.
1046 * </para></listitem>
1048 * If the remote peer sends invalid or malformed data. In this
1049 * case @remote_peer_vanished is set to %FALSE and @error
1051 * </para></listitem>
1054 * Upon receiving this signal, you should give up your reference to
1055 * @connection. You are guaranteed that this signal is emitted only
1060 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
1061 G_TYPE_DBUS_CONNECTION,
1063 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1074 g_dbus_connection_init (GDBusConnection *connection)
1076 g_mutex_init (&connection->lock);
1077 g_mutex_init (&connection->init_lock);
1079 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
1081 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1083 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1085 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1088 (GDestroyNotify) g_ptr_array_unref);
1090 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1093 (GDestroyNotify) exported_object_free);
1095 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1098 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1101 (GDestroyNotify) exported_subtree_free);
1103 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1106 connection->map_thread_to_last_serial = g_hash_table_new (g_direct_hash,
1109 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1111 connection->filters = g_ptr_array_new ();
1115 * g_dbus_connection_get_stream:
1116 * @connection: a #GDBusConnection
1118 * Gets the underlying stream used for IO.
1120 * While the #GDBusConnection is active, it will interact with this
1121 * stream from a worker thread, so it is not safe to interact with
1122 * the stream directly.
1124 * Returns: (transfer none): the stream used for IO
1129 g_dbus_connection_get_stream (GDBusConnection *connection)
1131 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1133 /* do not use g_return_val_if_fail(), we want the memory barrier */
1134 if (!check_initialized (connection))
1137 return connection->stream;
1141 * g_dbus_connection_start_message_processing:
1142 * @connection: A #GDBusConnection.
1144 * If @connection was created with
1145 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1146 * starts processing messages. Does nothing on if @connection wasn't
1147 * created with this flag or if the method has already been called.
1152 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1154 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1156 /* do not use g_return_val_if_fail(), we want the memory barrier */
1157 if (!check_initialized (connection))
1160 g_assert (connection->worker != NULL);
1161 _g_dbus_worker_unfreeze (connection->worker);
1165 * g_dbus_connection_is_closed:
1166 * @connection: A #GDBusConnection.
1168 * Gets whether @connection is closed.
1170 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
1175 g_dbus_connection_is_closed (GDBusConnection *connection)
1179 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1181 flags = g_atomic_int_get (&connection->atomic_flags);
1183 return (flags & FLAG_CLOSED) ? TRUE : FALSE;
1187 * g_dbus_connection_get_capabilities:
1188 * @connection: A #GDBusConnection.
1190 * Gets the capabilities negotiated with the remote peer
1192 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
1196 GDBusCapabilityFlags
1197 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1199 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1201 /* do not use g_return_val_if_fail(), we want the memory barrier */
1202 if (!check_initialized (connection))
1203 return G_DBUS_CAPABILITY_FLAGS_NONE;
1205 return connection->capabilities;
1208 /* ---------------------------------------------------------------------------------------------------- */
1210 /* Called in a temporary thread without holding locks. */
1212 flush_in_thread_func (GSimpleAsyncResult *res,
1214 GCancellable *cancellable)
1219 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1222 g_simple_async_result_take_error (res, error);
1226 * g_dbus_connection_flush:
1227 * @connection: A #GDBusConnection.
1228 * @cancellable: (allow-none): A #GCancellable or %NULL.
1229 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1230 * satisfied or %NULL if you don't care about the result.
1231 * @user_data: The data to pass to @callback.
1233 * Asynchronously flushes @connection, that is, writes all queued
1234 * outgoing message to the transport and then flushes the transport
1235 * (using g_output_stream_flush_async()). This is useful in programs
1236 * that wants to emit a D-Bus signal and then exit
1237 * immediately. Without flushing the connection, there is no guarantee
1238 * that the message has been sent to the networking buffers in the OS
1241 * This is an asynchronous method. When the operation is finished,
1242 * @callback will be invoked in the <link
1243 * linkend="g-main-context-push-thread-default">thread-default main
1244 * loop</link> of the thread you are calling this method from. You can
1245 * then call g_dbus_connection_flush_finish() to get the result of the
1246 * operation. See g_dbus_connection_flush_sync() for the synchronous
1252 g_dbus_connection_flush (GDBusConnection *connection,
1253 GCancellable *cancellable,
1254 GAsyncReadyCallback callback,
1257 GSimpleAsyncResult *simple;
1259 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1261 simple = g_simple_async_result_new (G_OBJECT (connection),
1264 g_dbus_connection_flush);
1265 g_simple_async_result_set_check_cancellable (simple, cancellable);
1266 g_simple_async_result_run_in_thread (simple,
1267 flush_in_thread_func,
1270 g_object_unref (simple);
1274 * g_dbus_connection_flush_finish:
1275 * @connection: A #GDBusConnection.
1276 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_flush().
1277 * @error: Return location for error or %NULL.
1279 * Finishes an operation started with g_dbus_connection_flush().
1281 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1286 g_dbus_connection_flush_finish (GDBusConnection *connection,
1290 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1295 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1296 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1297 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1299 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1301 if (g_simple_async_result_propagate_error (simple, error))
1311 * g_dbus_connection_flush_sync:
1312 * @connection: A #GDBusConnection.
1313 * @cancellable: (allow-none): A #GCancellable or %NULL.
1314 * @error: Return location for error or %NULL.
1316 * Synchronously flushes @connection. The calling thread is blocked
1317 * until this is done. See g_dbus_connection_flush() for the
1318 * asynchronous version of this method and more details about what it
1321 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1326 g_dbus_connection_flush_sync (GDBusConnection *connection,
1327 GCancellable *cancellable,
1332 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1333 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1337 /* This is only a best-effort attempt to see whether the connection is
1338 * closed, so it doesn't need the lock. If the connection closes just
1339 * after this check, but before scheduling the flush operation, the
1340 * result will be more or less the same as if the connection closed while
1341 * the flush operation was pending - it'll fail with either CLOSED or
1344 if (!check_unclosed (connection, 0, error))
1347 g_assert (connection->worker != NULL);
1349 ret = _g_dbus_worker_flush_sync (connection->worker,
1357 /* ---------------------------------------------------------------------------------------------------- */
1361 GDBusConnection *connection;
1363 gboolean remote_peer_vanished;
1367 emit_closed_data_free (EmitClosedData *data)
1369 g_object_unref (data->connection);
1370 if (data->error != NULL)
1371 g_error_free (data->error);
1375 /* Called in a user thread that has acquired the main context that was
1376 * thread-default when the object was constructed
1379 emit_closed_in_idle (gpointer user_data)
1381 EmitClosedData *data = user_data;
1384 g_object_notify (G_OBJECT (data->connection), "closed");
1385 g_signal_emit (data->connection,
1386 signals[CLOSED_SIGNAL],
1388 data->remote_peer_vanished,
1394 /* Can be called from any thread, must hold lock.
1395 * FLAG_CLOSED must already have been set.
1398 schedule_closed_unlocked (GDBusConnection *connection,
1399 gboolean remote_peer_vanished,
1402 GSource *idle_source;
1403 EmitClosedData *data;
1405 CONNECTION_ENSURE_LOCK (connection);
1407 data = g_new0 (EmitClosedData, 1);
1408 data->connection = g_object_ref (connection);
1409 data->remote_peer_vanished = remote_peer_vanished;
1410 data->error = error != NULL ? g_error_copy (error) : NULL;
1412 idle_source = g_idle_source_new ();
1413 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1414 g_source_set_callback (idle_source,
1415 emit_closed_in_idle,
1417 (GDestroyNotify) emit_closed_data_free);
1418 g_source_attach (idle_source, connection->main_context_at_construction);
1419 g_source_unref (idle_source);
1422 /* ---------------------------------------------------------------------------------------------------- */
1425 * g_dbus_connection_close:
1426 * @connection: A #GDBusConnection.
1427 * @cancellable: (allow-none): A #GCancellable or %NULL.
1428 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1429 * satisfied or %NULL if you don't care about the result.
1430 * @user_data: The data to pass to @callback.
1432 * Closes @connection. Note that this never causes the process to
1433 * exit (this might only happen if the other end of a shared message
1434 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1436 * Once the connection is closed, operations such as sending a message
1437 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1438 * will not automatically flush the connection so queued messages may
1439 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1441 * If @connection is already closed, this method fails with
1442 * %G_IO_ERROR_CLOSED.
1444 * When @connection has been closed, the #GDBusConnection::closed
1445 * signal is emitted in the <link
1446 * linkend="g-main-context-push-thread-default">thread-default main
1447 * loop</link> of the thread that @connection was constructed in.
1449 * This is an asynchronous method. When the operation is finished,
1450 * @callback will be invoked in the <link
1451 * linkend="g-main-context-push-thread-default">thread-default main
1452 * loop</link> of the thread you are calling this method from. You can
1453 * then call g_dbus_connection_close_finish() to get the result of the
1454 * operation. See g_dbus_connection_close_sync() for the synchronous
1460 g_dbus_connection_close (GDBusConnection *connection,
1461 GCancellable *cancellable,
1462 GAsyncReadyCallback callback,
1465 GSimpleAsyncResult *simple;
1467 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1469 /* do not use g_return_val_if_fail(), we want the memory barrier */
1470 if (!check_initialized (connection))
1473 g_assert (connection->worker != NULL);
1475 simple = g_simple_async_result_new (G_OBJECT (connection),
1478 g_dbus_connection_close);
1479 g_simple_async_result_set_check_cancellable (simple, cancellable);
1480 _g_dbus_worker_close (connection->worker, cancellable, simple);
1481 g_object_unref (simple);
1485 * g_dbus_connection_close_finish:
1486 * @connection: A #GDBusConnection.
1487 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_close().
1488 * @error: Return location for error or %NULL.
1490 * Finishes an operation started with g_dbus_connection_close().
1492 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1497 g_dbus_connection_close_finish (GDBusConnection *connection,
1501 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1506 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1507 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1508 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1510 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1512 if (g_simple_async_result_propagate_error (simple, error))
1523 GAsyncResult *result;
1526 /* Can be called by any thread, without the connection lock */
1528 sync_close_cb (GObject *source_object,
1532 SyncCloseData *data = user_data;
1534 data->result = g_object_ref (res);
1535 g_main_loop_quit (data->loop);
1539 * g_dbus_connection_close_sync:
1540 * @connection: A #GDBusConnection.
1541 * @cancellable: (allow-none): A #GCancellable or %NULL.
1542 * @error: Return location for error or %NULL.
1544 * Synchronously closees @connection. The calling thread is blocked
1545 * until this is done. See g_dbus_connection_close() for the
1546 * asynchronous version of this method and more details about what it
1549 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1554 g_dbus_connection_close_sync (GDBusConnection *connection,
1555 GCancellable *cancellable,
1560 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1561 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1565 if (check_unclosed (connection, 0, error))
1567 GMainContext *context;
1570 context = g_main_context_new ();
1571 g_main_context_push_thread_default (context);
1572 data.loop = g_main_loop_new (context, TRUE);
1575 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1576 g_main_loop_run (data.loop);
1577 ret = g_dbus_connection_close_finish (connection, data.result, error);
1579 g_object_unref (data.result);
1580 g_main_loop_unref (data.loop);
1581 g_main_context_pop_thread_default (context);
1582 g_main_context_unref (context);
1588 /* ---------------------------------------------------------------------------------------------------- */
1591 * g_dbus_connection_get_last_serial:
1592 * @connection: A #GDBusConnection.
1594 * Retrieves the last serial number assigned to a #GDBusMessage on
1595 * the current thread. This includes messages sent via both low-level
1596 * API such as g_dbus_connection_send_message() as well as
1597 * high-level API such as g_dbus_connection_emit_signal(),
1598 * g_dbus_connection_call() or g_dbus_proxy_call().
1600 * Returns: the last used serial or zero when no message has been sent
1601 * within the current thread.
1606 g_dbus_connection_get_last_serial (GDBusConnection *connection)
1610 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
1612 CONNECTION_LOCK (connection);
1613 ret = GPOINTER_TO_UINT (g_hash_table_lookup (connection->map_thread_to_last_serial,
1615 CONNECTION_UNLOCK (connection);
1620 /* ---------------------------------------------------------------------------------------------------- */
1622 /* Can be called by any thread, with the connection lock held */
1624 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1625 GDBusMessage *message,
1626 GDBusSendMessageFlags flags,
1627 volatile guint32 *out_serial,
1632 guint32 serial_to_use;
1635 CONNECTION_ENSURE_LOCK (connection);
1637 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1638 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1640 /* TODO: check all necessary headers are present */
1645 if (out_serial != NULL)
1648 /* If we're in initable_init(), don't check for being initialized, to avoid
1649 * chicken-and-egg problems. initable_init() is responsible for setting up
1650 * our prerequisites (mainly connection->worker), and only calling us
1651 * from its own thread (so no memory barrier is needed).
1653 if (!check_unclosed (connection,
1654 (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
1658 blob = g_dbus_message_to_blob (message,
1660 connection->capabilities,
1665 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1666 serial_to_use = g_dbus_message_get_serial (message);
1668 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1673 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1676 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1679 g_assert_not_reached ();
1684 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1685 blob_size, serial_to_use, connection);
1686 g_printerr ("----\n");
1687 hexdump (blob, blob_size);
1688 g_printerr ("----\n");
1691 /* TODO: use connection->auth to encode the blob */
1693 if (out_serial != NULL)
1694 *out_serial = serial_to_use;
1696 /* store used serial for the current thread */
1697 /* TODO: watch the thread disposal and remove associated record
1699 * - see https://bugzilla.gnome.org/show_bug.cgi?id=676825#c7
1701 g_hash_table_replace (connection->map_thread_to_last_serial,
1703 GUINT_TO_POINTER (serial_to_use));
1705 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
1706 g_dbus_message_set_serial (message, serial_to_use);
1708 g_dbus_message_lock (message);
1709 _g_dbus_worker_send_message (connection->worker,
1713 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1724 * g_dbus_connection_send_message:
1725 * @connection: A #GDBusConnection.
1726 * @message: A #GDBusMessage
1727 * @flags: Flags affecting how the message is sent.
1728 * @out_serial: (out) (allow-none): Return location for serial number assigned
1729 * to @message when sending it or %NULL.
1730 * @error: Return location for error or %NULL.
1732 * Asynchronously sends @message to the peer represented by @connection.
1734 * Unless @flags contain the
1735 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1736 * will be assigned by @connection and set on @message via
1737 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1738 * serial number used will be written to this location prior to
1739 * submitting the message to the underlying transport.
1741 * If @connection is closed then the operation will fail with
1742 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1743 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1745 * See <xref linkend="gdbus-server"/> and <xref
1746 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1747 * low-level API to send and receive UNIX file descriptors.
1749 * Note that @message must be unlocked, unless @flags contain the
1750 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1752 * Returns: %TRUE if the message was well-formed and queued for
1753 * transmission, %FALSE if @error is set.
1758 g_dbus_connection_send_message (GDBusConnection *connection,
1759 GDBusMessage *message,
1760 GDBusSendMessageFlags flags,
1761 volatile guint32 *out_serial,
1766 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1767 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1768 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1769 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1771 CONNECTION_LOCK (connection);
1772 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1773 CONNECTION_UNLOCK (connection);
1777 /* ---------------------------------------------------------------------------------------------------- */
1781 volatile gint ref_count;
1782 GDBusConnection *connection;
1784 GSimpleAsyncResult *simple;
1786 GMainContext *main_context;
1788 GCancellable *cancellable;
1790 gulong cancellable_handler_id;
1792 GSource *timeout_source;
1797 /* Can be called from any thread with or without lock held */
1798 static SendMessageData *
1799 send_message_data_ref (SendMessageData *data)
1801 g_atomic_int_inc (&data->ref_count);
1805 /* Can be called from any thread with or without lock held */
1807 send_message_data_unref (SendMessageData *data)
1809 if (g_atomic_int_dec_and_test (&data->ref_count))
1811 g_assert (data->timeout_source == NULL);
1812 g_assert (data->simple == NULL);
1813 g_assert (data->cancellable_handler_id == 0);
1814 g_object_unref (data->connection);
1815 if (data->cancellable != NULL)
1816 g_object_unref (data->cancellable);
1817 g_main_context_unref (data->main_context);
1822 /* ---------------------------------------------------------------------------------------------------- */
1824 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1826 send_message_with_reply_deliver (SendMessageData *data, gboolean remove)
1828 CONNECTION_ENSURE_LOCK (data->connection);
1830 g_assert (!data->delivered);
1832 data->delivered = TRUE;
1834 g_simple_async_result_complete_in_idle (data->simple);
1835 g_object_unref (data->simple);
1836 data->simple = NULL;
1838 if (data->timeout_source != NULL)
1840 g_source_destroy (data->timeout_source);
1841 data->timeout_source = NULL;
1843 if (data->cancellable_handler_id > 0)
1845 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1846 data->cancellable_handler_id = 0;
1851 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
1852 GUINT_TO_POINTER (data->serial)));
1855 send_message_data_unref (data);
1858 /* ---------------------------------------------------------------------------------------------------- */
1860 /* Can be called from any thread with lock held */
1862 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1863 GDBusMessage *reply)
1865 if (data->delivered)
1868 g_simple_async_result_set_op_res_gpointer (data->simple,
1869 g_object_ref (reply),
1872 send_message_with_reply_deliver (data, TRUE);
1878 /* ---------------------------------------------------------------------------------------------------- */
1880 /* Called from a user thread, lock is not held */
1882 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1884 SendMessageData *data = user_data;
1886 CONNECTION_LOCK (data->connection);
1887 if (data->delivered)
1890 g_simple_async_result_set_error (data->simple,
1892 G_IO_ERROR_CANCELLED,
1893 _("Operation was cancelled"));
1895 send_message_with_reply_deliver (data, TRUE);
1898 CONNECTION_UNLOCK (data->connection);
1902 /* Can be called from any thread with or without lock held */
1904 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1907 SendMessageData *data = user_data;
1908 GSource *idle_source;
1910 /* postpone cancellation to idle handler since we may be called directly
1911 * via g_cancellable_connect() (e.g. holding lock)
1913 idle_source = g_idle_source_new ();
1914 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1915 g_source_set_callback (idle_source,
1916 send_message_with_reply_cancelled_idle_cb,
1917 send_message_data_ref (data),
1918 (GDestroyNotify) send_message_data_unref);
1919 g_source_attach (idle_source, data->main_context);
1920 g_source_unref (idle_source);
1923 /* ---------------------------------------------------------------------------------------------------- */
1925 /* Called from a user thread, lock is not held */
1927 send_message_with_reply_timeout_cb (gpointer user_data)
1929 SendMessageData *data = user_data;
1931 CONNECTION_LOCK (data->connection);
1932 if (data->delivered)
1935 g_simple_async_result_set_error (data->simple,
1937 G_IO_ERROR_TIMED_OUT,
1938 _("Timeout was reached"));
1940 send_message_with_reply_deliver (data, TRUE);
1943 CONNECTION_UNLOCK (data->connection);
1948 /* ---------------------------------------------------------------------------------------------------- */
1950 /* Called from a user thread, connection's lock is held */
1952 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1953 GDBusMessage *message,
1954 GDBusSendMessageFlags flags,
1956 volatile guint32 *out_serial,
1957 GCancellable *cancellable,
1958 GAsyncReadyCallback callback,
1961 GSimpleAsyncResult *simple;
1962 SendMessageData *data;
1964 volatile guint32 serial;
1968 if (out_serial == NULL)
1969 out_serial = &serial;
1971 if (timeout_msec == -1)
1972 timeout_msec = 25 * 1000;
1974 simple = g_simple_async_result_new (G_OBJECT (connection),
1977 g_dbus_connection_send_message_with_reply);
1978 g_simple_async_result_set_check_cancellable (simple, cancellable);
1980 if (g_cancellable_is_cancelled (cancellable))
1982 g_simple_async_result_set_error (simple,
1984 G_IO_ERROR_CANCELLED,
1985 _("Operation was cancelled"));
1986 g_simple_async_result_complete_in_idle (simple);
1987 g_object_unref (simple);
1992 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1994 g_simple_async_result_take_error (simple, error);
1995 g_simple_async_result_complete_in_idle (simple);
1996 g_object_unref (simple);
2000 data = g_new0 (SendMessageData, 1);
2001 data->ref_count = 1;
2002 data->connection = g_object_ref (connection);
2003 data->simple = simple;
2004 data->serial = *out_serial;
2005 data->main_context = g_main_context_ref_thread_default ();
2007 if (cancellable != NULL)
2009 data->cancellable = g_object_ref (cancellable);
2010 data->cancellable_handler_id = g_cancellable_connect (cancellable,
2011 G_CALLBACK (send_message_with_reply_cancelled_cb),
2012 send_message_data_ref (data),
2013 (GDestroyNotify) send_message_data_unref);
2016 if (timeout_msec != G_MAXINT)
2018 data->timeout_source = g_timeout_source_new (timeout_msec);
2019 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
2020 g_source_set_callback (data->timeout_source,
2021 send_message_with_reply_timeout_cb,
2022 send_message_data_ref (data),
2023 (GDestroyNotify) send_message_data_unref);
2024 g_source_attach (data->timeout_source, data->main_context);
2025 g_source_unref (data->timeout_source);
2028 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
2029 GUINT_TO_POINTER (*out_serial),
2037 * g_dbus_connection_send_message_with_reply:
2038 * @connection: A #GDBusConnection.
2039 * @message: A #GDBusMessage.
2040 * @flags: Flags affecting how the message is sent.
2041 * @timeout_msec: The timeout in milliseconds, -1 to use the default
2042 * timeout or %G_MAXINT for no timeout.
2043 * @out_serial: (out) (allow-none): Return location for serial number assigned
2044 * to @message when sending it or %NULL.
2045 * @cancellable: (allow-none): A #GCancellable or %NULL.
2046 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
2047 * satisfied or %NULL if you don't care about the result.
2048 * @user_data: The data to pass to @callback.
2050 * Asynchronously sends @message to the peer represented by @connection.
2052 * Unless @flags contain the
2053 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2054 * will be assigned by @connection and set on @message via
2055 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2056 * serial number used will be written to this location prior to
2057 * submitting the message to the underlying transport.
2059 * If @connection is closed then the operation will fail with
2060 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2061 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2062 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2064 * This is an asynchronous method. When the operation is finished, @callback will be invoked
2065 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
2066 * of the thread you are calling this method from. You can then call
2067 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
2068 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
2070 * Note that @message must be unlocked, unless @flags contain the
2071 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2073 * See <xref linkend="gdbus-server"/> and <xref
2074 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2075 * low-level API to send and receive UNIX file descriptors.
2080 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
2081 GDBusMessage *message,
2082 GDBusSendMessageFlags flags,
2084 volatile guint32 *out_serial,
2085 GCancellable *cancellable,
2086 GAsyncReadyCallback callback,
2089 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2090 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2091 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2092 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2094 CONNECTION_LOCK (connection);
2095 g_dbus_connection_send_message_with_reply_unlocked (connection,
2103 CONNECTION_UNLOCK (connection);
2107 * g_dbus_connection_send_message_with_reply_finish:
2108 * @connection: a #GDBusConnection
2109 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
2110 * @error: Return location for error or %NULL.
2112 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2114 * Note that @error is only set if a local in-process error
2115 * occurred. That is to say that the returned #GDBusMessage object may
2116 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2117 * g_dbus_message_to_gerror() to transcode this to a #GError.
2119 * See <xref linkend="gdbus-server"/> and <xref
2120 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2121 * low-level API to send and receive UNIX file descriptors.
2123 * Returns: (transfer full): A locked #GDBusMessage or %NULL if @error is set.
2128 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2132 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2133 GDBusMessage *reply;
2135 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2136 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2140 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
2142 if (g_simple_async_result_propagate_error (simple, error))
2145 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
2151 /* ---------------------------------------------------------------------------------------------------- */
2156 GMainContext *context;
2158 } SendMessageSyncData;
2160 /* Called from a user thread, lock is not held */
2162 send_message_with_reply_sync_cb (GDBusConnection *connection,
2166 SendMessageSyncData *data = user_data;
2167 data->res = g_object_ref (res);
2168 g_main_loop_quit (data->loop);
2172 * g_dbus_connection_send_message_with_reply_sync:
2173 * @connection: A #GDBusConnection.
2174 * @message: A #GDBusMessage.
2175 * @flags: Flags affecting how the message is sent.
2176 * @timeout_msec: The timeout in milliseconds, -1 to use the default
2177 * timeout or %G_MAXINT for no timeout.
2178 * @out_serial: (out) (allow-none): Return location for serial number assigned
2179 * to @message when sending it or %NULL.
2180 * @cancellable: (allow-none): A #GCancellable or %NULL.
2181 * @error: Return location for error or %NULL.
2183 * Synchronously sends @message to the peer represented by @connection
2184 * and blocks the calling thread until a reply is received or the
2185 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2186 * for the asynchronous version of this method.
2188 * Unless @flags contain the
2189 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2190 * will be assigned by @connection and set on @message via
2191 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2192 * serial number used will be written to this location prior to
2193 * submitting the message to the underlying transport.
2195 * If @connection is closed then the operation will fail with
2196 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2197 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2198 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2200 * Note that @error is only set if a local in-process error
2201 * occurred. That is to say that the returned #GDBusMessage object may
2202 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2203 * g_dbus_message_to_gerror() to transcode this to a #GError.
2205 * See <xref linkend="gdbus-server"/> and <xref
2206 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2207 * low-level API to send and receive UNIX file descriptors.
2209 * Note that @message must be unlocked, unless @flags contain the
2210 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2212 * Returns: (transfer full): A locked #GDBusMessage that is the reply to @message or %NULL if @error is set.
2217 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2218 GDBusMessage *message,
2219 GDBusSendMessageFlags flags,
2221 volatile guint32 *out_serial,
2222 GCancellable *cancellable,
2225 SendMessageSyncData *data;
2226 GDBusMessage *reply;
2228 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2229 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2230 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2231 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2232 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2234 data = g_new0 (SendMessageSyncData, 1);
2235 data->context = g_main_context_new ();
2236 data->loop = g_main_loop_new (data->context, FALSE);
2238 g_main_context_push_thread_default (data->context);
2240 g_dbus_connection_send_message_with_reply (connection,
2246 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2248 g_main_loop_run (data->loop);
2249 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2253 g_main_context_pop_thread_default (data->context);
2255 g_main_context_unref (data->context);
2256 g_main_loop_unref (data->loop);
2257 g_object_unref (data->res);
2263 /* ---------------------------------------------------------------------------------------------------- */
2267 GDBusMessageFilterFunction func;
2274 GDBusMessageFilterFunction filter_function;
2276 GDestroyNotify user_data_free_func;
2279 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2281 on_worker_message_received (GDBusWorker *worker,
2282 GDBusMessage *message,
2285 GDBusConnection *connection;
2286 FilterCallback *filters;
2291 G_LOCK (message_bus_lock);
2292 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2295 G_UNLOCK (message_bus_lock);
2298 connection = G_DBUS_CONNECTION (user_data);
2299 g_object_ref (connection);
2300 G_UNLOCK (message_bus_lock);
2302 //g_debug ("in on_worker_message_received");
2304 g_object_ref (message);
2305 g_dbus_message_lock (message);
2307 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2309 /* First collect the set of callback functions */
2310 CONNECTION_LOCK (connection);
2311 num_filters = connection->filters->len;
2312 filters = g_new0 (FilterCallback, num_filters);
2313 for (n = 0; n < num_filters; n++)
2315 FilterData *data = connection->filters->pdata[n];
2316 filters[n].func = data->filter_function;
2317 filters[n].user_data = data->user_data;
2319 CONNECTION_UNLOCK (connection);
2321 /* then call the filters in order (without holding the lock) */
2322 for (n = 0; n < num_filters; n++)
2324 message = filters[n].func (connection,
2327 filters[n].user_data);
2328 if (message == NULL)
2330 g_dbus_message_lock (message);
2333 /* Standard dispatch unless the filter ate the message - no need to
2334 * do anything if the message was altered
2336 if (message != NULL)
2338 GDBusMessageType message_type;
2340 message_type = g_dbus_message_get_message_type (message);
2341 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2343 guint32 reply_serial;
2344 SendMessageData *send_message_data;
2346 reply_serial = g_dbus_message_get_reply_serial (message);
2347 CONNECTION_LOCK (connection);
2348 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2349 GUINT_TO_POINTER (reply_serial));
2350 if (send_message_data != NULL)
2352 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2353 send_message_data_deliver_reply_unlocked (send_message_data, message);
2357 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2359 CONNECTION_UNLOCK (connection);
2361 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2363 CONNECTION_LOCK (connection);
2364 distribute_signals (connection, message);
2365 CONNECTION_UNLOCK (connection);
2367 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2369 CONNECTION_LOCK (connection);
2370 distribute_method_call (connection, message);
2371 CONNECTION_UNLOCK (connection);
2375 if (message != NULL)
2376 g_object_unref (message);
2377 g_object_unref (connection);
2381 /* Called in GDBusWorker's thread, lock is not held */
2382 static GDBusMessage *
2383 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2384 GDBusMessage *message,
2387 GDBusConnection *connection;
2388 FilterCallback *filters;
2393 G_LOCK (message_bus_lock);
2394 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2397 G_UNLOCK (message_bus_lock);
2400 connection = G_DBUS_CONNECTION (user_data);
2401 g_object_ref (connection);
2402 G_UNLOCK (message_bus_lock);
2404 //g_debug ("in on_worker_message_about_to_be_sent");
2406 /* First collect the set of callback functions */
2407 CONNECTION_LOCK (connection);
2408 num_filters = connection->filters->len;
2409 filters = g_new0 (FilterCallback, num_filters);
2410 for (n = 0; n < num_filters; n++)
2412 FilterData *data = connection->filters->pdata[n];
2413 filters[n].func = data->filter_function;
2414 filters[n].user_data = data->user_data;
2416 CONNECTION_UNLOCK (connection);
2418 /* then call the filters in order (without holding the lock) */
2419 for (n = 0; n < num_filters; n++)
2421 g_dbus_message_lock (message);
2422 message = filters[n].func (connection,
2425 filters[n].user_data);
2426 if (message == NULL)
2430 g_object_unref (connection);
2436 /* called with connection lock held, in GDBusWorker thread */
2438 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2440 SendMessageData *data = value;
2442 if (data->delivered)
2445 g_simple_async_result_set_error (data->simple,
2448 _("The connection is closed"));
2450 /* Ask send_message_with_reply_deliver not to remove the element from the
2451 * hash table - we're in the middle of a foreach; that would be unsafe.
2452 * Instead, return TRUE from this function so that it gets removed safely.
2454 send_message_with_reply_deliver (data, FALSE);
2458 /* Called in GDBusWorker's thread - we must not block - without lock held */
2460 on_worker_closed (GDBusWorker *worker,
2461 gboolean remote_peer_vanished,
2465 GDBusConnection *connection;
2467 guint old_atomic_flags;
2469 G_LOCK (message_bus_lock);
2470 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2473 G_UNLOCK (message_bus_lock);
2476 connection = G_DBUS_CONNECTION (user_data);
2477 g_object_ref (connection);
2478 G_UNLOCK (message_bus_lock);
2480 //g_debug ("in on_worker_closed: %s", error->message);
2482 CONNECTION_LOCK (connection);
2483 /* Even though this is atomic, we do it inside the lock to avoid breaking
2484 * assumptions in remove_match_rule(). We'd need the lock in a moment
2485 * anyway, so, no loss.
2487 old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
2489 if (!(old_atomic_flags & FLAG_CLOSED))
2491 g_hash_table_foreach_remove (connection->map_method_serial_to_send_message_data, cancel_method_on_close, NULL);
2492 schedule_closed_unlocked (connection, remote_peer_vanished, error);
2494 CONNECTION_UNLOCK (connection);
2496 g_object_unref (connection);
2499 /* ---------------------------------------------------------------------------------------------------- */
2501 /* Determines the biggest set of capabilities we can support on this
2504 * Called with the init_lock held.
2506 static GDBusCapabilityFlags
2507 get_offered_capabilities_max (GDBusConnection *connection)
2509 GDBusCapabilityFlags ret;
2510 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2512 if (G_IS_UNIX_CONNECTION (connection->stream))
2513 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2518 /* Called in a user thread, lock is not held */
2520 initable_init (GInitable *initable,
2521 GCancellable *cancellable,
2524 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2527 /* This method needs to be idempotent to work with the singleton
2528 * pattern. See the docs for g_initable_init(). We implement this by
2531 * Unfortunately we can't use the main lock since the on_worker_*()
2532 * callbacks above needs the lock during initialization (for message
2533 * bus connections we do a synchronous Hello() call on the bus).
2535 g_mutex_lock (&connection->init_lock);
2539 /* Make this a no-op if we're already initialized (successfully or
2542 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
2544 ret = (connection->initialization_error == NULL);
2548 /* Because of init_lock, we can't get here twice in different threads */
2549 g_assert (connection->initialization_error == NULL);
2551 /* The user can pass multiple (but mutally exclusive) construct
2554 * - stream (of type GIOStream)
2555 * - address (of type gchar*)
2557 * At the end of the day we end up with a non-NULL GIOStream
2558 * object in connection->stream.
2560 if (connection->address != NULL)
2562 g_assert (connection->stream == NULL);
2564 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2565 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2567 g_set_error_literal (&connection->initialization_error,
2569 G_IO_ERROR_INVALID_ARGUMENT,
2570 _("Unsupported flags encountered when constructing a client-side connection"));
2574 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2575 NULL, /* TODO: out_guid */
2577 &connection->initialization_error);
2578 if (connection->stream == NULL)
2581 else if (connection->stream != NULL)
2587 g_assert_not_reached ();
2590 /* Authenticate the connection */
2591 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2593 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2594 g_assert (connection->guid != NULL);
2595 connection->auth = _g_dbus_auth_new (connection->stream);
2596 if (!_g_dbus_auth_run_server (connection->auth,
2597 connection->authentication_observer,
2599 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2600 get_offered_capabilities_max (connection),
2601 &connection->capabilities,
2602 &connection->credentials,
2604 &connection->initialization_error))
2607 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2609 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2610 g_assert (connection->guid == NULL);
2611 connection->auth = _g_dbus_auth_new (connection->stream);
2612 connection->guid = _g_dbus_auth_run_client (connection->auth,
2613 connection->authentication_observer,
2614 get_offered_capabilities_max (connection),
2615 &connection->capabilities,
2617 &connection->initialization_error);
2618 if (connection->guid == NULL)
2622 if (connection->authentication_observer != NULL)
2624 g_object_unref (connection->authentication_observer);
2625 connection->authentication_observer = NULL;
2628 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2630 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2633 /* We want all IO operations to be non-blocking since they happen in
2634 * the worker thread which is shared by _all_ connections.
2636 if (G_IS_SOCKET_CONNECTION (connection->stream))
2638 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2642 G_LOCK (message_bus_lock);
2643 if (alive_connections == NULL)
2644 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2645 g_hash_table_insert (alive_connections, connection, connection);
2646 G_UNLOCK (message_bus_lock);
2648 connection->worker = _g_dbus_worker_new (connection->stream,
2649 connection->capabilities,
2650 ((connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) != 0),
2651 on_worker_message_received,
2652 on_worker_message_about_to_be_sent,
2656 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2657 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2659 GVariant *hello_result;
2661 /* we could lift this restriction by adding code in gdbusprivate.c */
2662 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2664 g_set_error_literal (&connection->initialization_error,
2667 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2671 hello_result = g_dbus_connection_call_sync (connection,
2672 "org.freedesktop.DBus", /* name */
2673 "/org/freedesktop/DBus", /* path */
2674 "org.freedesktop.DBus", /* interface */
2676 NULL, /* parameters */
2677 G_VARIANT_TYPE ("(s)"),
2678 CALL_FLAGS_INITIALIZING,
2680 NULL, /* TODO: cancellable */
2681 &connection->initialization_error);
2682 if (hello_result == NULL)
2685 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2686 g_variant_unref (hello_result);
2687 //g_debug ("unique name is '%s'", connection->bus_unique_name);
2694 g_assert (connection->initialization_error != NULL);
2695 g_propagate_error (error, g_error_copy (connection->initialization_error));
2698 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
2699 g_mutex_unlock (&connection->init_lock);
2705 initable_iface_init (GInitableIface *initable_iface)
2707 initable_iface->init = initable_init;
2710 /* ---------------------------------------------------------------------------------------------------- */
2713 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2718 /* ---------------------------------------------------------------------------------------------------- */
2721 * g_dbus_connection_new:
2722 * @stream: A #GIOStream.
2723 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2724 * @flags: Flags describing how to make the connection.
2725 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2726 * @cancellable: (allow-none): A #GCancellable or %NULL.
2727 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2728 * @user_data: The data to pass to @callback.
2730 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2731 * with the end represented by @stream.
2733 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2734 * will be put into non-blocking mode.
2736 * The D-Bus connection will interact with @stream from a worker thread.
2737 * As a result, the caller should not interact with @stream after this
2738 * method has been called, except by calling g_object_unref() on it.
2740 * If @observer is not %NULL it may be used to control the
2741 * authentication process.
2743 * When the operation is finished, @callback will be invoked. You can
2744 * then call g_dbus_connection_new_finish() to get the result of the
2747 * This is a asynchronous failable constructor. See
2748 * g_dbus_connection_new_sync() for the synchronous
2754 g_dbus_connection_new (GIOStream *stream,
2756 GDBusConnectionFlags flags,
2757 GDBusAuthObserver *observer,
2758 GCancellable *cancellable,
2759 GAsyncReadyCallback callback,
2762 g_return_if_fail (G_IS_IO_STREAM (stream));
2763 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2771 "authentication-observer", observer,
2776 * g_dbus_connection_new_finish:
2777 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2778 * @error: Return location for error or %NULL.
2780 * Finishes an operation started with g_dbus_connection_new().
2782 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2787 g_dbus_connection_new_finish (GAsyncResult *res,
2791 GObject *source_object;
2793 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2794 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2796 source_object = g_async_result_get_source_object (res);
2797 g_assert (source_object != NULL);
2798 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2801 g_object_unref (source_object);
2803 return G_DBUS_CONNECTION (object);
2809 * g_dbus_connection_new_sync:
2810 * @stream: A #GIOStream.
2811 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2812 * @flags: Flags describing how to make the connection.
2813 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2814 * @cancellable: (allow-none): A #GCancellable or %NULL.
2815 * @error: Return location for error or %NULL.
2817 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2818 * with the end represented by @stream.
2820 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2821 * will be put into non-blocking mode.
2823 * The D-Bus connection will interact with @stream from a worker thread.
2824 * As a result, the caller should not interact with @stream after this
2825 * method has been called, except by calling g_object_unref() on it.
2827 * If @observer is not %NULL it may be used to control the
2828 * authentication process.
2830 * This is a synchronous failable constructor. See
2831 * g_dbus_connection_new() for the asynchronous version.
2833 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2838 g_dbus_connection_new_sync (GIOStream *stream,
2840 GDBusConnectionFlags flags,
2841 GDBusAuthObserver *observer,
2842 GCancellable *cancellable,
2845 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2846 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2847 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2853 "authentication-observer", observer,
2857 /* ---------------------------------------------------------------------------------------------------- */
2860 * g_dbus_connection_new_for_address:
2861 * @address: A D-Bus address.
2862 * @flags: Flags describing how to make the connection.
2863 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2864 * @cancellable: (allow-none): A #GCancellable or %NULL.
2865 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2866 * @user_data: The data to pass to @callback.
2868 * Asynchronously connects and sets up a D-Bus client connection for
2869 * exchanging D-Bus messages with an endpoint specified by @address
2870 * which must be in the D-Bus address format.
2872 * This constructor can only be used to initiate client-side
2873 * connections - use g_dbus_connection_new() if you need to act as the
2874 * server. In particular, @flags cannot contain the
2875 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2876 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2878 * When the operation is finished, @callback will be invoked. You can
2879 * then call g_dbus_connection_new_finish() to get the result of the
2882 * If @observer is not %NULL it may be used to control the
2883 * authentication process.
2885 * This is a asynchronous failable constructor. See
2886 * g_dbus_connection_new_for_address_sync() for the synchronous
2892 g_dbus_connection_new_for_address (const gchar *address,
2893 GDBusConnectionFlags flags,
2894 GDBusAuthObserver *observer,
2895 GCancellable *cancellable,
2896 GAsyncReadyCallback callback,
2899 g_return_if_fail (address != NULL);
2900 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2907 "authentication-observer", observer,
2912 * g_dbus_connection_new_for_address_finish:
2913 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2914 * @error: Return location for error or %NULL.
2916 * Finishes an operation started with g_dbus_connection_new_for_address().
2918 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2923 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2927 GObject *source_object;
2929 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2930 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2932 source_object = g_async_result_get_source_object (res);
2933 g_assert (source_object != NULL);
2934 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2937 g_object_unref (source_object);
2939 return G_DBUS_CONNECTION (object);
2945 * g_dbus_connection_new_for_address_sync:
2946 * @address: A D-Bus address.
2947 * @flags: Flags describing how to make the connection.
2948 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2949 * @cancellable: (allow-none): A #GCancellable or %NULL.
2950 * @error: Return location for error or %NULL.
2952 * Synchronously connects and sets up a D-Bus client connection for
2953 * exchanging D-Bus messages with an endpoint specified by @address
2954 * which must be in the D-Bus address format.
2956 * This constructor can only be used to initiate client-side
2957 * connections - use g_dbus_connection_new_sync() if you need to act
2958 * as the server. In particular, @flags cannot contain the
2959 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2960 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2962 * This is a synchronous failable constructor. See
2963 * g_dbus_connection_new_for_address() for the asynchronous version.
2965 * If @observer is not %NULL it may be used to control the
2966 * authentication process.
2968 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2973 g_dbus_connection_new_for_address_sync (const gchar *address,
2974 GDBusConnectionFlags flags,
2975 GDBusAuthObserver *observer,
2976 GCancellable *cancellable,
2979 g_return_val_if_fail (address != NULL, NULL);
2980 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2981 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2986 "authentication-observer", observer,
2990 /* ---------------------------------------------------------------------------------------------------- */
2993 * g_dbus_connection_set_exit_on_close:
2994 * @connection: A #GDBusConnection.
2995 * @exit_on_close: Whether the process should be terminated
2996 * when @connection is closed by the remote peer.
2998 * Sets whether the process should be terminated when @connection is
2999 * closed by the remote peer. See #GDBusConnection:exit-on-close for
3002 * Note that this function should be used with care. Most modern UNIX
3003 * desktops tie the notion of a user session the session bus, and expect
3004 * all of a users applications to quit when their bus connection goes away.
3005 * If you are setting @exit_on_close to %FALSE for the shared session
3006 * bus connection, you should make sure that your application exits
3007 * when the user session ends.
3012 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
3013 gboolean exit_on_close)
3015 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3018 g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
3020 g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
3025 * g_dbus_connection_get_exit_on_close:
3026 * @connection: A #GDBusConnection.
3028 * Gets whether the process is terminated when @connection is
3029 * closed by the remote peer. See
3030 * #GDBusConnection:exit-on-close for more details.
3032 * Returns: Whether the process is terminated when @connection is
3033 * closed by the remote peer.
3038 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
3040 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3042 if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
3049 * g_dbus_connection_get_guid:
3050 * @connection: A #GDBusConnection.
3052 * The GUID of the peer performing the role of server when
3053 * authenticating. See #GDBusConnection:guid for more details.
3055 * Returns: The GUID. Do not free this string, it is owned by
3061 g_dbus_connection_get_guid (GDBusConnection *connection)
3063 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3064 return connection->guid;
3068 * g_dbus_connection_get_unique_name:
3069 * @connection: A #GDBusConnection.
3071 * Gets the unique name of @connection as assigned by the message
3072 * bus. This can also be used to figure out if @connection is a
3073 * message bus connection.
3075 * Returns: The unique name or %NULL if @connection is not a message
3076 * bus connection. Do not free this string, it is owned by
3082 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3084 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3086 /* do not use g_return_val_if_fail(), we want the memory barrier */
3087 if (!check_initialized (connection))
3090 return connection->bus_unique_name;
3094 * g_dbus_connection_get_peer_credentials:
3095 * @connection: A #GDBusConnection.
3097 * Gets the credentials of the authenticated peer. This will always
3098 * return %NULL unless @connection acted as a server
3099 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3100 * when set up and the client passed credentials as part of the
3101 * authentication process.
3103 * In a message bus setup, the message bus is always the server and
3104 * each application is a client. So this method will always return
3105 * %NULL for message bus clients.
3107 * Returns: (transfer none): A #GCredentials or %NULL if not available. Do not free
3108 * this object, it is owned by @connection.
3113 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3115 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3117 /* do not use g_return_val_if_fail(), we want the memory barrier */
3118 if (!check_initialized (connection))
3121 return connection->credentials;
3124 /* ---------------------------------------------------------------------------------------------------- */
3126 static guint _global_filter_id = 1;
3129 * g_dbus_connection_add_filter:
3130 * @connection: A #GDBusConnection.
3131 * @filter_function: A filter function.
3132 * @user_data: User data to pass to @filter_function.
3133 * @user_data_free_func: Function to free @user_data with when filter
3134 * is removed or %NULL.
3136 * Adds a message filter. Filters are handlers that are run on all
3137 * incoming and outgoing messages, prior to standard dispatch. Filters
3138 * are run in the order that they were added. The same handler can be
3139 * added as a filter more than once, in which case it will be run more
3140 * than once. Filters added during a filter callback won't be run on
3141 * the message being processed. Filter functions are allowed to modify
3142 * and even drop messages.
3144 * Note that filters are run in a dedicated message handling thread so
3145 * they can't block and, generally, can't do anything but signal a
3146 * worker thread. Also note that filters are rarely needed - use API
3147 * such as g_dbus_connection_send_message_with_reply(),
3148 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3150 * If a filter consumes an incoming message the message is not
3151 * dispatched anywhere else - not even the standard dispatch machinery
3152 * (that API such as g_dbus_connection_signal_subscribe() and
3153 * g_dbus_connection_send_message_with_reply() relies on) will see the
3154 * message. Similary, if a filter consumes an outgoing message, the
3155 * message will not be sent to the other peer.
3157 * Returns: A filter identifier that can be used with
3158 * g_dbus_connection_remove_filter().
3163 g_dbus_connection_add_filter (GDBusConnection *connection,
3164 GDBusMessageFilterFunction filter_function,
3166 GDestroyNotify user_data_free_func)
3170 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3171 g_return_val_if_fail (filter_function != NULL, 0);
3172 g_return_val_if_fail (check_initialized (connection), 0);
3174 CONNECTION_LOCK (connection);
3175 data = g_new0 (FilterData, 1);
3176 data->id = _global_filter_id++; /* TODO: overflow etc. */
3177 data->filter_function = filter_function;
3178 data->user_data = user_data;
3179 data->user_data_free_func = user_data_free_func;
3180 g_ptr_array_add (connection->filters, data);
3181 CONNECTION_UNLOCK (connection);
3186 /* only called from finalize(), removes all filters */
3188 purge_all_filters (GDBusConnection *connection)
3191 for (n = 0; n < connection->filters->len; n++)
3193 FilterData *data = connection->filters->pdata[n];
3194 if (data->user_data_free_func != NULL)
3195 data->user_data_free_func (data->user_data);
3201 * g_dbus_connection_remove_filter:
3202 * @connection: a #GDBusConnection
3203 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3210 g_dbus_connection_remove_filter (GDBusConnection *connection,
3214 FilterData *to_destroy;
3216 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3217 g_return_if_fail (check_initialized (connection));
3219 CONNECTION_LOCK (connection);
3221 for (n = 0; n < connection->filters->len; n++)
3223 FilterData *data = connection->filters->pdata[n];
3224 if (data->id == filter_id)
3226 g_ptr_array_remove_index (connection->filters, n);
3231 CONNECTION_UNLOCK (connection);
3233 /* do free without holding lock */
3234 if (to_destroy != NULL)
3236 if (to_destroy->user_data_free_func != NULL)
3237 to_destroy->user_data_free_func (to_destroy->user_data);
3238 g_free (to_destroy);
3242 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3246 /* ---------------------------------------------------------------------------------------------------- */
3252 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3253 gchar *interface_name;
3257 GDBusSignalFlags flags;
3258 GArray *subscribers;
3263 GDBusSignalCallback callback;
3265 GDestroyNotify user_data_free_func;
3267 GMainContext *context;
3271 signal_data_free (SignalData *signal_data)
3273 g_free (signal_data->rule);
3274 g_free (signal_data->sender);
3275 g_free (signal_data->sender_unique_name);
3276 g_free (signal_data->interface_name);
3277 g_free (signal_data->member);
3278 g_free (signal_data->object_path);
3279 g_free (signal_data->arg0);
3280 g_array_free (signal_data->subscribers, TRUE);
3281 g_free (signal_data);
3285 args_to_rule (const gchar *sender,
3286 const gchar *interface_name,
3287 const gchar *member,
3288 const gchar *object_path,
3290 GDBusSignalFlags flags)
3294 rule = g_string_new ("type='signal'");
3295 if (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE)
3296 g_string_prepend_c (rule, '-');
3298 g_string_append_printf (rule, ",sender='%s'", sender);
3299 if (interface_name != NULL)
3300 g_string_append_printf (rule, ",interface='%s'", interface_name);
3302 g_string_append_printf (rule, ",member='%s'", member);
3303 if (object_path != NULL)
3304 g_string_append_printf (rule, ",path='%s'", object_path);
3308 if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3309 g_string_append_printf (rule, ",arg0path='%s'", arg0);
3310 else if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3311 g_string_append_printf (rule, ",arg0namespace='%s'", arg0);
3313 g_string_append_printf (rule, ",arg0='%s'", arg0);
3316 return g_string_free (rule, FALSE);
3319 static guint _global_subscriber_id = 1;
3320 static guint _global_registration_id = 1;
3321 static guint _global_subtree_registration_id = 1;
3323 /* ---------------------------------------------------------------------------------------------------- */
3325 /* Called in a user thread, lock is held */
3327 add_match_rule (GDBusConnection *connection,
3328 const gchar *match_rule)
3331 GDBusMessage *message;
3333 if (match_rule[0] == '-')
3336 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3337 "/org/freedesktop/DBus", /* path */
3338 "org.freedesktop.DBus", /* interface */
3340 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3342 if (!g_dbus_connection_send_message_unlocked (connection,
3344 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3348 g_critical ("Error while sending AddMatch() message: %s", error->message);
3349 g_error_free (error);
3351 g_object_unref (message);
3354 /* ---------------------------------------------------------------------------------------------------- */
3356 /* Called in a user thread, lock is held */
3358 remove_match_rule (GDBusConnection *connection,
3359 const gchar *match_rule)
3362 GDBusMessage *message;
3364 if (match_rule[0] == '-')
3367 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3368 "/org/freedesktop/DBus", /* path */
3369 "org.freedesktop.DBus", /* interface */
3371 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3374 if (!g_dbus_connection_send_message_unlocked (connection,
3376 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3380 /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
3381 * critical; but we're holding the lock, and our caller checked whether
3382 * we were already closed, so we can't get that error.
3384 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3385 g_error_free (error);
3387 g_object_unref (message);
3390 /* ---------------------------------------------------------------------------------------------------- */
3393 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3395 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3396 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3397 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3398 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3399 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3402 /* ---------------------------------------------------------------------------------------------------- */
3405 * g_dbus_connection_signal_subscribe:
3406 * @connection: A #GDBusConnection.
3407 * @sender: (allow-none): Sender name to match on (unique or well-known name)
3408 * or %NULL to listen from all senders.
3409 * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3410 * match on all interfaces.
3411 * @member: (allow-none): D-Bus signal name to match on or %NULL to match on all signals.
3412 * @object_path: (allow-none): Object path to match on or %NULL to match on all object paths.
3413 * @arg0: (allow-none): Contents of first string argument to match on or %NULL
3414 * to match on all kinds of arguments.
3415 * @flags: Flags describing how to subscribe to the signal (currently unused).
3416 * @callback: Callback to invoke when there is a signal matching the requested data.
3417 * @user_data: User data to pass to @callback.
3418 * @user_data_free_func: (allow-none): Function to free @user_data with when
3419 * subscription is removed or %NULL.
3421 * Subscribes to signals on @connection and invokes @callback with a
3422 * whenever the signal is received. Note that @callback
3423 * will be invoked in the <link
3424 * linkend="g-main-context-push-thread-default">thread-default main
3425 * loop</link> of the thread you are calling this method from.
3427 * If @connection is not a message bus connection, @sender must be
3430 * If @sender is a well-known name note that @callback is invoked with
3431 * the unique name for the owner of @sender, not the well-known name
3432 * as one would expect. This is because the message bus rewrites the
3433 * name. As such, to avoid certain race conditions, users should be
3434 * tracking the name owner of the well-known name and use that when
3435 * processing the received signal.
3437 * If one of %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE or
3438 * %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH are given, @arg0 is
3439 * interpreted as part of a namespace or path. The first argument
3440 * of a signal is matched against that part as specified by D-Bus.
3442 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
3447 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3448 const gchar *sender,
3449 const gchar *interface_name,
3450 const gchar *member,
3451 const gchar *object_path,
3453 GDBusSignalFlags flags,
3454 GDBusSignalCallback callback,
3456 GDestroyNotify user_data_free_func)
3459 SignalData *signal_data;
3460 SignalSubscriber subscriber;
3461 GPtrArray *signal_data_array;
3462 const gchar *sender_unique_name;
3464 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3465 * an OOM condition. We might want to change that but that would involve making
3466 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3467 * handle that. And there's really no sensible way of handling this short of retrying
3468 * to add the match rule... and then there's the little thing that, hey, maybe there's
3469 * a reason the bus in an OOM condition.
3471 * Doable, but not really sure it's worth it...
3474 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3475 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3476 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3477 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3478 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3479 g_return_val_if_fail (callback != NULL, 0);
3480 g_return_val_if_fail (check_initialized (connection), 0);
3481 g_return_val_if_fail (!((flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH) && (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)), 0);
3482 g_return_val_if_fail (!(arg0 == NULL && (flags & (G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH | G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE))), 0);
3484 CONNECTION_LOCK (connection);
3486 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3487 * with a '-' character to prefix the rule (which will otherwise be
3490 * This allows us to hash the rule and do our lifecycle tracking in
3491 * the usual way, but the '-' prevents the match rule from ever
3492 * actually being send to the bus (either for add or remove).
3494 rule = args_to_rule (sender, interface_name, member, object_path, arg0, flags);
3496 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3497 sender_unique_name = sender;
3499 sender_unique_name = "";
3501 subscriber.callback = callback;
3502 subscriber.user_data = user_data;
3503 subscriber.user_data_free_func = user_data_free_func;
3504 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3505 subscriber.context = g_main_context_ref_thread_default ();
3507 /* see if we've already have this rule */
3508 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3509 if (signal_data != NULL)
3511 g_array_append_val (signal_data->subscribers, subscriber);
3516 signal_data = g_new0 (SignalData, 1);
3517 signal_data->rule = rule;
3518 signal_data->sender = g_strdup (sender);
3519 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3520 signal_data->interface_name = g_strdup (interface_name);
3521 signal_data->member = g_strdup (member);
3522 signal_data->object_path = g_strdup (object_path);
3523 signal_data->arg0 = g_strdup (arg0);
3524 signal_data->flags = flags;
3525 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3526 g_array_append_val (signal_data->subscribers, subscriber);
3528 g_hash_table_insert (connection->map_rule_to_signal_data,
3532 /* Add the match rule to the bus...
3534 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3535 * always send such messages to us.
3537 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3539 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3540 add_match_rule (connection, signal_data->rule);
3543 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3544 signal_data->sender_unique_name);
3545 if (signal_data_array == NULL)
3547 signal_data_array = g_ptr_array_new ();
3548 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3549 g_strdup (signal_data->sender_unique_name),
3552 g_ptr_array_add (signal_data_array, signal_data);
3555 g_hash_table_insert (connection->map_id_to_signal_data,
3556 GUINT_TO_POINTER (subscriber.id),
3559 CONNECTION_UNLOCK (connection);
3561 return subscriber.id;
3564 /* ---------------------------------------------------------------------------------------------------- */
3566 /* called in any thread */
3567 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3569 unsubscribe_id_internal (GDBusConnection *connection,
3570 guint subscription_id,
3571 GArray *out_removed_subscribers)
3573 SignalData *signal_data;
3574 GPtrArray *signal_data_array;
3577 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3578 GUINT_TO_POINTER (subscription_id));
3579 if (signal_data == NULL)
3581 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3585 for (n = 0; n < signal_data->subscribers->len; n++)
3587 SignalSubscriber *subscriber;
3589 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3590 if (subscriber->id != subscription_id)
3593 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3594 GUINT_TO_POINTER (subscription_id)));
3595 g_array_append_val (out_removed_subscribers, *subscriber);
3596 g_array_remove_index (signal_data->subscribers, n);
3598 if (signal_data->subscribers->len == 0)
3600 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3602 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3603 signal_data->sender_unique_name);
3604 g_warn_if_fail (signal_data_array != NULL);
3605 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3607 if (signal_data_array->len == 0)
3609 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3610 signal_data->sender_unique_name));
3613 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3614 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
3615 !is_signal_data_for_name_lost_or_acquired (signal_data) &&
3616 !g_dbus_connection_is_closed (connection) &&
3617 !connection->finalizing)
3619 /* The check for g_dbus_connection_is_closed() means that
3620 * sending the RemoveMatch message can't fail with
3621 * G_IO_ERROR_CLOSED, because we're holding the lock,
3622 * so on_worker_closed() can't happen between the check we just
3623 * did, and releasing the lock later.
3625 remove_match_rule (connection, signal_data->rule);
3628 signal_data_free (signal_data);
3634 g_assert_not_reached ();
3641 * g_dbus_connection_signal_unsubscribe:
3642 * @connection: A #GDBusConnection.
3643 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
3645 * Unsubscribes from signals.
3650 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3651 guint subscription_id)
3653 GArray *subscribers;
3656 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3657 g_return_if_fail (check_initialized (connection));
3659 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3661 CONNECTION_LOCK (connection);
3662 unsubscribe_id_internal (connection,
3665 CONNECTION_UNLOCK (connection);
3668 g_assert (subscribers->len == 0 || subscribers->len == 1);
3670 /* call GDestroyNotify without lock held */
3671 for (n = 0; n < subscribers->len; n++)
3673 SignalSubscriber *subscriber;
3674 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3675 call_destroy_notify (subscriber->context,
3676 subscriber->user_data_free_func,
3677 subscriber->user_data);
3678 g_main_context_unref (subscriber->context);
3681 g_array_free (subscribers, TRUE);
3684 /* ---------------------------------------------------------------------------------------------------- */
3688 guint subscription_id;
3689 GDBusSignalCallback callback;
3691 GDBusMessage *message;
3692 GDBusConnection *connection;
3693 const gchar *sender;
3695 const gchar *interface;
3696 const gchar *member;
3699 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3703 emit_signal_instance_in_idle_cb (gpointer data)
3705 SignalInstance *signal_instance = data;
3706 GVariant *parameters;
3707 gboolean has_subscription;
3709 parameters = g_dbus_message_get_body (signal_instance->message);
3710 if (parameters == NULL)
3712 parameters = g_variant_new ("()");
3713 g_variant_ref_sink (parameters);
3717 g_variant_ref_sink (parameters);
3721 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3722 signal_instance->subscription_id,
3723 signal_instance->sender,
3724 signal_instance->path,
3725 signal_instance->interface,
3726 signal_instance->member,
3727 g_variant_print (parameters, TRUE));
3730 /* Careful here, don't do the callback if we no longer has the subscription */
3731 CONNECTION_LOCK (signal_instance->connection);
3732 has_subscription = FALSE;
3733 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3734 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3735 has_subscription = TRUE;
3736 CONNECTION_UNLOCK (signal_instance->connection);
3738 if (has_subscription)
3739 signal_instance->callback (signal_instance->connection,
3740 signal_instance->sender,
3741 signal_instance->path,
3742 signal_instance->interface,
3743 signal_instance->member,
3745 signal_instance->user_data);
3747 g_variant_unref (parameters);
3753 signal_instance_free (SignalInstance *signal_instance)
3755 g_object_unref (signal_instance->message);
3756 g_object_unref (signal_instance->connection);
3757 g_free (signal_instance);
3761 namespace_rule_matches (const gchar *namespace,
3767 len_namespace = strlen (namespace);
3768 len_name = strlen (name);
3770 if (len_name < len_namespace)
3773 if (memcmp (namespace, name, len_namespace) != 0)
3776 return len_namespace == len_name || name[len_namespace] == '.';
3780 path_rule_matches (const gchar *path_a,
3781 const gchar *path_b)
3785 len_a = strlen (path_a);
3786 len_b = strlen (path_b);
3788 if (len_a < len_b && path_a[len_a - 1] != '/')
3791 if (len_b < len_a && path_b[len_b - 1] != '/')
3794 return memcmp (path_a, path_b, MIN (len_a, len_b)) == 0;
3797 /* called in GDBusWorker thread WITH lock held */
3799 schedule_callbacks (GDBusConnection *connection,
3800 GPtrArray *signal_data_array,
3801 GDBusMessage *message,
3802 const gchar *sender)
3805 const gchar *interface;
3806 const gchar *member;
3815 interface = g_dbus_message_get_interface (message);
3816 member = g_dbus_message_get_member (message);
3817 path = g_dbus_message_get_path (message);
3818 arg0 = g_dbus_message_get_arg0 (message);
3821 g_print ("In schedule_callbacks:\n"
3823 " interface = '%s'\n"
3834 /* TODO: if this is slow, then we can change signal_data_array into
3835 * map_object_path_to_signal_data_array or something.
3837 for (n = 0; n < signal_data_array->len; n++)
3839 SignalData *signal_data = signal_data_array->pdata[n];
3841 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3844 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3847 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3850 if (signal_data->arg0 != NULL)
3855 if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3857 if (!namespace_rule_matches (signal_data->arg0, arg0))
3860 else if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3862 if (!path_rule_matches (signal_data->arg0, arg0))
3865 else if (!g_str_equal (signal_data->arg0, arg0))
3869 for (m = 0; m < signal_data->subscribers->len; m++)
3871 SignalSubscriber *subscriber;
3872 GSource *idle_source;
3873 SignalInstance *signal_instance;
3875 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3877 signal_instance = g_new0 (SignalInstance, 1);
3878 signal_instance->subscription_id = subscriber->id;
3879 signal_instance->callback = subscriber->callback;
3880 signal_instance->user_data = subscriber->user_data;
3881 signal_instance->message = g_object_ref (message);
3882 signal_instance->connection = g_object_ref (connection);
3883 signal_instance->sender = sender;
3884 signal_instance->path = path;
3885 signal_instance->interface = interface;
3886 signal_instance->member = member;
3888 idle_source = g_idle_source_new ();
3889 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3890 g_source_set_callback (idle_source,
3891 emit_signal_instance_in_idle_cb,
3893 (GDestroyNotify) signal_instance_free);
3894 g_source_attach (idle_source, subscriber->context);
3895 g_source_unref (idle_source);
3900 /* called in GDBusWorker thread with lock held */
3902 distribute_signals (GDBusConnection *connection,
3903 GDBusMessage *message)
3905 GPtrArray *signal_data_array;
3906 const gchar *sender;
3908 sender = g_dbus_message_get_sender (message);
3910 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3912 _g_dbus_debug_print_lock ();
3913 g_print ("========================================================================\n"
3914 "GDBus-debug:Signal:\n"
3915 " <<<< RECEIVED SIGNAL %s.%s\n"
3917 " sent by name %s\n",
3918 g_dbus_message_get_interface (message),
3919 g_dbus_message_get_member (message),
3920 g_dbus_message_get_path (message),
3921 sender != NULL ? sender : "(none)");
3922 _g_dbus_debug_print_unlock ();
3925 /* collect subscribers that match on sender */
3928 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3929 if (signal_data_array != NULL)
3930 schedule_callbacks (connection, signal_data_array, message, sender);
3933 /* collect subscribers not matching on sender */
3934 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3935 if (signal_data_array != NULL)
3936 schedule_callbacks (connection, signal_data_array, message, sender);
3939 /* ---------------------------------------------------------------------------------------------------- */
3941 /* only called from finalize(), removes all subscriptions */
3943 purge_all_signal_subscriptions (GDBusConnection *connection)
3945 GHashTableIter iter;
3948 GArray *subscribers;
3951 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3952 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3953 while (g_hash_table_iter_next (&iter, &key, NULL))
3955 guint subscription_id = GPOINTER_TO_UINT (key);
3956 g_array_append_val (ids, subscription_id);
3959 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3960 for (n = 0; n < ids->len; n++)
3962 guint subscription_id = g_array_index (ids, guint, n);
3963 unsubscribe_id_internal (connection,
3967 g_array_free (ids, TRUE);
3969 /* call GDestroyNotify without lock held */
3970 for (n = 0; n < subscribers->len; n++)
3972 SignalSubscriber *subscriber;
3973 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3974 call_destroy_notify (subscriber->context,
3975 subscriber->user_data_free_func,
3976 subscriber->user_data);
3977 g_main_context_unref (subscriber->context);
3980 g_array_free (subscribers, TRUE);
3983 /* ---------------------------------------------------------------------------------------------------- */
3985 static GDBusInterfaceVTable *
3986 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3988 /* Don't waste memory by copying padding - remember to update this
3989 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3991 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3995 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
4000 /* ---------------------------------------------------------------------------------------------------- */
4002 static GDBusSubtreeVTable *
4003 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
4005 /* Don't waste memory by copying padding - remember to update this
4006 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
4008 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4012 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
4017 /* ---------------------------------------------------------------------------------------------------- */
4019 struct ExportedObject
4022 GDBusConnection *connection;
4024 /* maps gchar* -> ExportedInterface* */
4025 GHashTable *map_if_name_to_ei;
4028 /* only called with lock held */
4030 exported_object_free (ExportedObject *eo)
4032 g_free (eo->object_path);
4033 g_hash_table_unref (eo->map_if_name_to_ei);
4042 gchar *interface_name;
4043 GDBusInterfaceVTable *vtable;
4044 GDBusInterfaceInfo *interface_info;
4046 GMainContext *context;
4048 GDestroyNotify user_data_free_func;
4049 } ExportedInterface;
4051 /* called with lock held */
4053 exported_interface_free (ExportedInterface *ei)
4055 g_dbus_interface_info_cache_release (ei->interface_info);
4056 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
4058 call_destroy_notify (ei->context,
4059 ei->user_data_free_func,
4062 g_main_context_unref (ei->context);
4064 g_free (ei->interface_name);
4065 _g_dbus_interface_vtable_free (ei->vtable);
4069 /* ---------------------------------------------------------------------------------------------------- */
4071 /* Convenience function to check if @registration_id (if not zero) or
4072 * @subtree_registration_id (if not zero) has been unregistered. If
4073 * so, returns %TRUE.
4075 * May be called by any thread. Caller must *not* hold lock.
4078 has_object_been_unregistered (GDBusConnection *connection,
4079 guint registration_id,
4080 guint subtree_registration_id)
4084 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4088 CONNECTION_LOCK (connection);
4089 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
4090 GUINT_TO_POINTER (registration_id)) == NULL)
4094 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
4095 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
4099 CONNECTION_UNLOCK (connection);
4104 /* ---------------------------------------------------------------------------------------------------- */
4108 GDBusConnection *connection;
4109 GDBusMessage *message;
4111 const gchar *property_name;
4112 const GDBusInterfaceVTable *vtable;
4113 GDBusInterfaceInfo *interface_info;
4114 const GDBusPropertyInfo *property_info;
4115 guint registration_id;
4116 guint subtree_registration_id;
4120 property_data_free (PropertyData *data)
4122 g_object_unref (data->connection);
4123 g_object_unref (data->message);
4127 /* called in thread where object was registered - no locks held */
4129 invoke_get_property_in_idle_cb (gpointer _data)
4131 PropertyData *data = _data;
4134 GDBusMessage *reply;
4136 if (has_object_been_unregistered (data->connection,
4137 data->registration_id,
4138 data->subtree_registration_id))
4140 reply = g_dbus_message_new_method_error (data->message,
4141 "org.freedesktop.DBus.Error.UnknownMethod",
4142 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4143 g_dbus_message_get_path (data->message));
4144 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4145 g_object_unref (reply);
4150 value = data->vtable->get_property (data->connection,
4151 g_dbus_message_get_sender (data->message),
4152 g_dbus_message_get_path (data->message),
4153 data->interface_info->name,
4154 data->property_name,
4161 g_assert_no_error (error);
4163 g_variant_take_ref (value);
4164 reply = g_dbus_message_new_method_reply (data->message);
4165 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4166 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4167 g_variant_unref (value);
4168 g_object_unref (reply);
4172 gchar *dbus_error_name;
4173 g_assert (error != NULL);
4174 dbus_error_name = g_dbus_error_encode_gerror (error);
4175 reply = g_dbus_message_new_method_error_literal (data->message,
4178 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4179 g_free (dbus_error_name);
4180 g_error_free (error);
4181 g_object_unref (reply);
4188 /* called in thread where object was registered - no locks held */
4190 invoke_set_property_in_idle_cb (gpointer _data)
4192 PropertyData *data = _data;
4194 GDBusMessage *reply;
4200 g_variant_get (g_dbus_message_get_body (data->message),
4206 if (!data->vtable->set_property (data->connection,
4207 g_dbus_message_get_sender (data->message),
4208 g_dbus_message_get_path (data->message),
4209 data->interface_info->name,
4210 data->property_name,
4215 gchar *dbus_error_name;
4216 g_assert (error != NULL);
4217 dbus_error_name = g_dbus_error_encode_gerror (error);
4218 reply = g_dbus_message_new_method_error_literal (data->message,
4221 g_free (dbus_error_name);
4222 g_error_free (error);
4226 reply = g_dbus_message_new_method_reply (data->message);
4229 g_assert (reply != NULL);
4230 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4231 g_object_unref (reply);
4232 g_variant_unref (value);
4237 /* called in any thread with connection's lock held */
4239 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4240 GDBusMessage *message,
4241 guint registration_id,
4242 guint subtree_registration_id,
4244 GDBusInterfaceInfo *interface_info,
4245 const GDBusInterfaceVTable *vtable,
4246 GMainContext *main_context,
4250 const char *interface_name;
4251 const char *property_name;
4252 const GDBusPropertyInfo *property_info;
4253 GSource *idle_source;
4254 PropertyData *property_data;
4255 GDBusMessage *reply;
4260 g_variant_get (g_dbus_message_get_body (message),
4265 g_variant_get (g_dbus_message_get_body (message),
4274 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4276 property_info = NULL;
4278 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4279 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4280 if (property_info == NULL)
4282 reply = g_dbus_message_new_method_error (message,
4283 "org.freedesktop.DBus.Error.InvalidArgs",
4284 _("No such property '%s'"),
4286 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4287 g_object_unref (reply);
4292 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4294 reply = g_dbus_message_new_method_error (message,
4295 "org.freedesktop.DBus.Error.InvalidArgs",
4296 _("Property '%s' is not readable"),
4298 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4299 g_object_unref (reply);
4303 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4305 reply = g_dbus_message_new_method_error (message,
4306 "org.freedesktop.DBus.Error.InvalidArgs",
4307 _("Property '%s' is not writable"),
4309 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4310 g_object_unref (reply);
4319 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4320 * of the given value is wrong
4322 g_variant_get_child (g_dbus_message_get_body (message), 2, "v", &value);
4323 if (g_strcmp0 (g_variant_get_type_string (value), property_info->signature) != 0)
4325 reply = g_dbus_message_new_method_error (message,
4326 "org.freedesktop.DBus.Error.InvalidArgs",
4327 _("Error setting property '%s': Expected type '%s' but got '%s'"),
4328 property_name, property_info->signature,
4329 g_variant_get_type_string (value));
4330 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4331 g_variant_unref (value);
4332 g_object_unref (reply);
4337 g_variant_unref (value);
4340 /* If the vtable pointer for get_property() resp. set_property() is
4341 * NULL then dispatch the call via the method_call() handler.
4345 if (vtable->get_property == NULL)
4347 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4348 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4349 vtable, main_context, user_data);
4356 if (vtable->set_property == NULL)
4358 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4359 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4360 vtable, main_context, user_data);
4366 /* ok, got the property info - call user code in an idle handler */
4367 property_data = g_new0 (PropertyData, 1);
4368 property_data->connection = g_object_ref (connection);
4369 property_data->message = g_object_ref (message);
4370 property_data->user_data = user_data;
4371 property_data->property_name = property_name;
4372 property_data->vtable = vtable;
4373 property_data->interface_info = interface_info;
4374 property_data->property_info = property_info;
4375 property_data->registration_id = registration_id;
4376 property_data->subtree_registration_id = subtree_registration_id;
4378 idle_source = g_idle_source_new ();
4379 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4380 g_source_set_callback (idle_source,
4381 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4383 (GDestroyNotify) property_data_free);
4384 g_source_attach (idle_source, main_context);
4385 g_source_unref (idle_source);
4393 /* called in GDBusWorker thread with connection's lock held */
4395 handle_getset_property (GDBusConnection *connection,
4397 GDBusMessage *message,
4400 ExportedInterface *ei;
4402 const char *interface_name;
4403 const char *property_name;
4408 g_variant_get (g_dbus_message_get_body (message),
4413 g_variant_get (g_dbus_message_get_body (message),
4419 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4420 * no such interface registered
4422 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4425 GDBusMessage *reply;
4426 reply = g_dbus_message_new_method_error (message,
4427 "org.freedesktop.DBus.Error.InvalidArgs",
4428 _("No such interface '%s'"),
4430 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4431 g_object_unref (reply);
4436 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4449 /* ---------------------------------------------------------------------------------------------------- */
4453 GDBusConnection *connection;
4454 GDBusMessage *message;
4456 const GDBusInterfaceVTable *vtable;
4457 GDBusInterfaceInfo *interface_info;
4458 guint registration_id;
4459 guint subtree_registration_id;
4460 } PropertyGetAllData;
4463 property_get_all_data_free (PropertyData *data)
4465 g_object_unref (data->connection);
4466 g_object_unref (data->message);
4470 /* called in thread where object was registered - no locks held */
4472 invoke_get_all_properties_in_idle_cb (gpointer _data)
4474 PropertyGetAllData *data = _data;
4475 GVariantBuilder builder;
4476 GDBusMessage *reply;
4479 if (has_object_been_unregistered (data->connection,
4480 data->registration_id,
4481 data->subtree_registration_id))
4483 reply = g_dbus_message_new_method_error (data->message,
4484 "org.freedesktop.DBus.Error.UnknownMethod",
4485 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4486 g_dbus_message_get_path (data->message));
4487 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4488 g_object_unref (reply);
4492 /* TODO: Right now we never fail this call - we just omit values if
4493 * a get_property() call is failing.
4495 * We could fail the whole call if just a single get_property() call
4496 * returns an error. We need clarification in the D-Bus spec about this.
4498 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4499 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4500 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4502 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4505 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4508 value = data->vtable->get_property (data->connection,
4509 g_dbus_message_get_sender (data->message),
4510 g_dbus_message_get_path (data->message),
4511 data->interface_info->name,
4512 property_info->name,
4519 g_variant_take_ref (value);
4520 g_variant_builder_add (&builder,
4522 property_info->name,
4524 g_variant_unref (value);
4526 g_variant_builder_close (&builder);
4528 reply = g_dbus_message_new_method_reply (data->message);
4529 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4530 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4531 g_object_unref (reply);
4538 interface_has_readable_properties (GDBusInterfaceInfo *interface_info)
4542 if (!interface_info->properties)
4545 for (i = 0; interface_info->properties[i]; i++)
4546 if (interface_info->properties[i]->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE)
4552 /* called in any thread with connection's lock held */
4554 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4555 GDBusMessage *message,
4556 guint registration_id,
4557 guint subtree_registration_id,
4558 GDBusInterfaceInfo *interface_info,
4559 const GDBusInterfaceVTable *vtable,
4560 GMainContext *main_context,
4564 GSource *idle_source;
4565 PropertyGetAllData *property_get_all_data;
4572 /* If the vtable pointer for get_property() is NULL but we have a
4573 * non-zero number of readable properties, then dispatch the call via
4574 * the method_call() handler.
4576 if (vtable->get_property == NULL && interface_has_readable_properties (interface_info))
4578 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4579 interface_info, NULL, NULL, g_dbus_message_get_body (message),
4580 vtable, main_context, user_data);
4585 /* ok, got the property info - call user in an idle handler */
4586 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4587 property_get_all_data->connection = g_object_ref (connection);
4588 property_get_all_data->message = g_object_ref (message);
4589 property_get_all_data->user_data = user_data;
4590 property_get_all_data->vtable = vtable;
4591 property_get_all_data->interface_info = interface_info;
4592 property_get_all_data->registration_id = registration_id;
4593 property_get_all_data->subtree_registration_id = subtree_registration_id;
4595 idle_source = g_idle_source_new ();
4596 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4597 g_source_set_callback (idle_source,
4598 invoke_get_all_properties_in_idle_cb,
4599 property_get_all_data,
4600 (GDestroyNotify) property_get_all_data_free);
4601 g_source_attach (idle_source, main_context);
4602 g_source_unref (idle_source);
4610 /* called in GDBusWorker thread with connection's lock held */
4612 handle_get_all_properties (GDBusConnection *connection,
4614 GDBusMessage *message)
4616 ExportedInterface *ei;
4618 const char *interface_name;
4622 g_variant_get (g_dbus_message_get_body (message),
4626 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4627 * no such interface registered
4629 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4632 GDBusMessage *reply;
4633 reply = g_dbus_message_new_method_error (message,
4634 "org.freedesktop.DBus.Error.InvalidArgs",
4635 _("No such interface"),
4637 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4638 g_object_unref (reply);
4643 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4655 /* ---------------------------------------------------------------------------------------------------- */
4657 static const gchar introspect_header[] =
4658 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4659 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4660 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4663 static const gchar introspect_tail[] =
4666 static const gchar introspect_properties_interface[] =
4667 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4668 " <method name=\"Get\">\n"
4669 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4670 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4671 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4673 " <method name=\"GetAll\">\n"
4674 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4675 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4677 " <method name=\"Set\">\n"
4678 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4679 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4680 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4682 " <signal name=\"PropertiesChanged\">\n"
4683 " <arg type=\"s\" name=\"interface_name\"/>\n"
4684 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4685 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4689 static const gchar introspect_introspectable_interface[] =
4690 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4691 " <method name=\"Introspect\">\n"
4692 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4695 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4696 " <method name=\"Ping\"/>\n"
4697 " <method name=\"GetMachineId\">\n"
4698 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4703 introspect_append_header (GString *s)
4705 g_string_append (s, introspect_header);
4709 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4711 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4717 begin = object_path + path_len;
4718 end = strchr (begin, '/');
4720 s = g_strndup (begin, end - begin);
4722 s = g_strdup (begin);
4724 if (g_hash_table_lookup (set, s) == NULL)
4725 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
4731 /* TODO: we want a nicer public interface for this */
4732 /* called in any thread with connection's lock held */
4734 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4739 GHashTableIter hash_iter;
4740 const gchar *object_path;
4746 CONNECTION_ENSURE_LOCK (connection);
4748 path_len = strlen (path);
4752 set = g_hash_table_new (g_str_hash, g_str_equal);
4754 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4755 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4756 maybe_add_path (path, path_len, object_path, set);
4758 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4759 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4760 maybe_add_path (path, path_len, object_path, set);
4762 p = g_ptr_array_new ();
4763 keys = g_hash_table_get_keys (set);
4764 for (l = keys; l != NULL; l = l->next)
4765 g_ptr_array_add (p, l->data);
4766 g_hash_table_unref (set);
4769 g_ptr_array_add (p, NULL);
4770 ret = (gchar **) g_ptr_array_free (p, FALSE);
4774 /* called in any thread with connection's lock not held */
4776 g_dbus_connection_list_registered (GDBusConnection *connection,
4780 CONNECTION_LOCK (connection);
4781 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4782 CONNECTION_UNLOCK (connection);
4786 /* called in GDBusWorker thread with connection's lock held */
4788 handle_introspect (GDBusConnection *connection,
4790 GDBusMessage *message)
4794 GDBusMessage *reply;
4795 GHashTableIter hash_iter;
4796 ExportedInterface *ei;
4799 /* first the header with the standard interfaces */
4800 s = g_string_sized_new (sizeof (introspect_header) +
4801 sizeof (introspect_properties_interface) +
4802 sizeof (introspect_introspectable_interface) +
4803 sizeof (introspect_tail));
4804 introspect_append_header (s);
4805 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4806 "org.freedesktop.DBus.Properties"))
4807 g_string_append (s, introspect_properties_interface);
4809 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4810 "org.freedesktop.DBus.Introspectable"))
4811 g_string_append (s, introspect_introspectable_interface);
4813 /* then include the registered interfaces */
4814 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4815 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4816 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4818 /* finally include nodes registered below us */
4819 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4820 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4821 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4822 g_strfreev (registered);
4823 g_string_append (s, introspect_tail);
4825 reply = g_dbus_message_new_method_reply (message);
4826 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4827 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4828 g_object_unref (reply);
4829 g_string_free (s, TRUE);
4834 /* called in thread where object was registered - no locks held */
4836 call_in_idle_cb (gpointer user_data)
4838 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4839 GDBusInterfaceVTable *vtable;
4840 guint registration_id;
4841 guint subtree_registration_id;
4843 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4844 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4846 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4848 subtree_registration_id))
4850 GDBusMessage *reply;
4851 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4852 "org.freedesktop.DBus.Error.UnknownMethod",
4853 _("No such interface '%s' on object at path %s"),
4854 g_dbus_method_invocation_get_interface_name (invocation),
4855 g_dbus_method_invocation_get_object_path (invocation));
4856 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4857 g_object_unref (reply);
4861 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4862 g_assert (vtable != NULL && vtable->method_call != NULL);
4864 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4865 g_dbus_method_invocation_get_sender (invocation),
4866 g_dbus_method_invocation_get_object_path (invocation),
4867 g_dbus_method_invocation_get_interface_name (invocation),
4868 g_dbus_method_invocation_get_method_name (invocation),
4869 g_dbus_method_invocation_get_parameters (invocation),
4870 g_object_ref (invocation),
4871 g_dbus_method_invocation_get_user_data (invocation));
4877 /* called in GDBusWorker thread with connection's lock held */
4879 schedule_method_call (GDBusConnection *connection,
4880 GDBusMessage *message,
4881 guint registration_id,
4882 guint subtree_registration_id,
4883 const GDBusInterfaceInfo *interface_info,
4884 const GDBusMethodInfo *method_info,
4885 const GDBusPropertyInfo *property_info,
4886 GVariant *parameters,
4887 const GDBusInterfaceVTable *vtable,
4888 GMainContext *main_context,
4891 GDBusMethodInvocation *invocation;
4892 GSource *idle_source;
4894 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4895 g_dbus_message_get_path (message),
4896 g_dbus_message_get_interface (message),
4897 g_dbus_message_get_member (message),
4905 /* TODO: would be nicer with a real MethodData like we already
4906 * have PropertyData and PropertyGetAllData... */
4907 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4908 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4909 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4911 idle_source = g_idle_source_new ();
4912 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4913 g_source_set_callback (idle_source,
4917 g_source_attach (idle_source, main_context);
4918 g_source_unref (idle_source);
4921 /* called in GDBusWorker thread with connection's lock held */
4923 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4924 GDBusMessage *message,
4925 guint registration_id,
4926 guint subtree_registration_id,
4927 GDBusInterfaceInfo *interface_info,
4928 const GDBusInterfaceVTable *vtable,
4929 GMainContext *main_context,
4932 GDBusMethodInfo *method_info;
4933 GDBusMessage *reply;
4934 GVariant *parameters;
4936 GVariantType *in_type;
4940 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4941 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4943 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4944 * error to the caller
4946 if (method_info == NULL)
4948 reply = g_dbus_message_new_method_error (message,
4949 "org.freedesktop.DBus.Error.UnknownMethod",
4950 _("No such method '%s'"),
4951 g_dbus_message_get_member (message));
4952 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4953 g_object_unref (reply);
4958 parameters = g_dbus_message_get_body (message);
4959 if (parameters == NULL)
4961 parameters = g_variant_new ("()");
4962 g_variant_ref_sink (parameters);
4966 g_variant_ref (parameters);
4969 /* Check that the incoming args are of the right type - if they are not, return
4970 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4972 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4973 if (!g_variant_is_of_type (parameters, in_type))
4977 type_string = g_variant_type_dup_string (in_type);
4979 reply = g_dbus_message_new_method_error (message,
4980 "org.freedesktop.DBus.Error.InvalidArgs",
4981 _("Type of message, '%s', does not match expected type '%s'"),
4982 g_variant_get_type_string (parameters),
4984 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4985 g_variant_type_free (in_type);
4986 g_variant_unref (parameters);
4987 g_object_unref (reply);
4988 g_free (type_string);
4992 g_variant_type_free (in_type);
4994 /* schedule the call in idle */
4995 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4996 interface_info, method_info, NULL, parameters,
4997 vtable, main_context, user_data);
4998 g_variant_unref (parameters);
5005 /* ---------------------------------------------------------------------------------------------------- */
5007 /* called in GDBusWorker thread with connection's lock held */
5009 obj_message_func (GDBusConnection *connection,
5011 GDBusMessage *message)
5013 const gchar *interface_name;
5014 const gchar *member;
5015 const gchar *signature;
5020 interface_name = g_dbus_message_get_interface (message);
5021 member = g_dbus_message_get_member (message);
5022 signature = g_dbus_message_get_signature (message);
5024 /* see if we have an interface for handling this call */
5025 if (interface_name != NULL)
5027 ExportedInterface *ei;
5028 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5031 /* we do - invoke the handler in idle in the right thread */
5033 /* handle no vtable or handler being present */
5034 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
5037 handled = validate_and_maybe_schedule_method_call (connection,
5049 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5050 g_strcmp0 (member, "Introspect") == 0 &&
5051 g_strcmp0 (signature, "") == 0)
5053 handled = handle_introspect (connection, eo, message);
5056 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5057 g_strcmp0 (member, "Get") == 0 &&
5058 g_strcmp0 (signature, "ss") == 0)
5060 handled = handle_getset_property (connection, eo, message, TRUE);
5063 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5064 g_strcmp0 (member, "Set") == 0 &&
5065 g_strcmp0 (signature, "ssv") == 0)
5067 handled = handle_getset_property (connection, eo, message, FALSE);
5070 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5071 g_strcmp0 (member, "GetAll") == 0 &&
5072 g_strcmp0 (signature, "s") == 0)
5074 handled = handle_get_all_properties (connection, eo, message);
5083 * g_dbus_connection_register_object:
5084 * @connection: A #GDBusConnection.
5085 * @object_path: The object path to register at.
5086 * @interface_info: Introspection data for the interface.
5087 * @vtable: (allow-none): A #GDBusInterfaceVTable to call into or %NULL.
5088 * @user_data: (allow-none): Data to pass to functions in @vtable.
5089 * @user_data_free_func: Function to call when the object path is unregistered.
5090 * @error: Return location for error or %NULL.
5092 * Registers callbacks for exported objects at @object_path with the
5093 * D-Bus interface that is described in @interface_info.
5095 * Calls to functions in @vtable (and @user_data_free_func) will
5096 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
5097 * loop</link> of the thread you are calling this method from.
5099 * Note that all #GVariant values passed to functions in @vtable will match
5100 * the signature given in @interface_info - if a remote caller passes
5101 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
5102 * is returned to the remote caller.
5104 * Additionally, if the remote caller attempts to invoke methods or
5105 * access properties not mentioned in @interface_info the
5106 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
5107 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
5108 * are returned to the caller.
5110 * It is considered a programming error if the
5111 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
5112 * #GVariant of incorrect type.
5114 * If an existing callback is already registered at @object_path and
5115 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
5117 * GDBus automatically implements the standard D-Bus interfaces
5118 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
5119 * and org.freedesktop.Peer, so you don't have to implement those for
5120 * the objects you export. You <emphasis>can</emphasis> implement
5121 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
5122 * and setting of properties asynchronously.
5124 * Note that the reference count on @interface_info will be
5125 * incremented by 1 (unless allocated statically, e.g. if the
5126 * reference count is -1, see g_dbus_interface_info_ref()) for as long
5127 * as the object is exported. Also note that @vtable will be copied.
5129 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
5131 * Returns: 0 if @error is set, otherwise a registration id (never 0)
5132 * that can be used with g_dbus_connection_unregister_object() .
5137 g_dbus_connection_register_object (GDBusConnection *connection,
5138 const gchar *object_path,
5139 GDBusInterfaceInfo *interface_info,
5140 const GDBusInterfaceVTable *vtable,
5142 GDestroyNotify user_data_free_func,
5146 ExportedInterface *ei;
5149 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5150 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5151 g_return_val_if_fail (interface_info != NULL, 0);
5152 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
5153 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5154 g_return_val_if_fail (check_initialized (connection), 0);
5158 CONNECTION_LOCK (connection);
5160 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5163 eo = g_new0 (ExportedObject, 1);
5164 eo->object_path = g_strdup (object_path);
5165 eo->connection = connection;
5166 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
5169 (GDestroyNotify) exported_interface_free);
5170 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
5173 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
5179 _("An object is already exported for the interface %s at %s"),
5180 interface_info->name,
5185 ei = g_new0 (ExportedInterface, 1);
5186 ei->id = _global_registration_id++; /* TODO: overflow etc. */
5188 ei->user_data = user_data;
5189 ei->user_data_free_func = user_data_free_func;
5190 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
5191 ei->interface_info = g_dbus_interface_info_ref (interface_info);
5192 g_dbus_interface_info_cache_build (ei->interface_info);
5193 ei->interface_name = g_strdup (interface_info->name);
5194 ei->context = g_main_context_ref_thread_default ();
5196 g_hash_table_insert (eo->map_if_name_to_ei,
5197 (gpointer) ei->interface_name,
5199 g_hash_table_insert (connection->map_id_to_ei,
5200 GUINT_TO_POINTER (ei->id),
5206 CONNECTION_UNLOCK (connection);
5212 * g_dbus_connection_unregister_object:
5213 * @connection: A #GDBusConnection.
5214 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
5216 * Unregisters an object.
5218 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
5223 g_dbus_connection_unregister_object (GDBusConnection *connection,
5224 guint registration_id)
5226 ExportedInterface *ei;
5230 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5231 g_return_val_if_fail (check_initialized (connection), FALSE);
5235 CONNECTION_LOCK (connection);
5237 ei = g_hash_table_lookup (connection->map_id_to_ei,
5238 GUINT_TO_POINTER (registration_id));
5244 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5245 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5246 /* unregister object path if we have no more exported interfaces */
5247 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5248 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5254 CONNECTION_UNLOCK (connection);
5259 /* ---------------------------------------------------------------------------------------------------- */
5262 * g_dbus_connection_emit_signal:
5263 * @connection: A #GDBusConnection.
5264 * @destination_bus_name: (allow-none): The unique bus name for the destination
5265 * for the signal or %NULL to emit to all listeners.
5266 * @object_path: Path of remote object.
5267 * @interface_name: D-Bus interface to emit a signal on.
5268 * @signal_name: The name of the signal to emit.
5269 * @parameters: (allow-none): A #GVariant tuple with parameters for the signal
5270 * or %NULL if not passing parameters.
5271 * @error: Return location for error or %NULL.
5275 * If the parameters GVariant is floating, it is consumed.
5277 * This can only fail if @parameters is not compatible with the D-Bus protocol.
5279 * Returns: %TRUE unless @error is set.
5284 g_dbus_connection_emit_signal (GDBusConnection *connection,
5285 const gchar *destination_bus_name,
5286 const gchar *object_path,
5287 const gchar *interface_name,
5288 const gchar *signal_name,
5289 GVariant *parameters,
5292 GDBusMessage *message;
5298 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5299 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5300 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5301 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5302 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5303 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5304 g_return_val_if_fail (check_initialized (connection), FALSE);
5306 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5308 _g_dbus_debug_print_lock ();
5309 g_print ("========================================================================\n"
5310 "GDBus-debug:Emission:\n"
5311 " >>>> SIGNAL EMISSION %s.%s()\n"
5313 " destination %s\n",
5314 interface_name, signal_name,
5316 destination_bus_name != NULL ? destination_bus_name : "(none)");
5317 _g_dbus_debug_print_unlock ();
5320 message = g_dbus_message_new_signal (object_path,
5324 if (destination_bus_name != NULL)
5325 g_dbus_message_set_header (message,
5326 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5327 g_variant_new_string (destination_bus_name));
5329 if (parameters != NULL)
5330 g_dbus_message_set_body (message, parameters);
5332 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5333 g_object_unref (message);
5339 add_call_flags (GDBusMessage *message,
5340 GDBusCallFlags flags)
5342 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5343 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
5347 decode_method_reply (GDBusMessage *reply,
5348 const gchar *method_name,
5349 const GVariantType *reply_type,
5350 GUnixFDList **out_fd_list,
5356 switch (g_dbus_message_get_message_type (reply))
5358 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5359 result = g_dbus_message_get_body (reply);
5362 result = g_variant_new ("()");
5363 g_variant_ref_sink (result);
5367 g_variant_ref (result);
5370 if (!g_variant_is_of_type (result, reply_type))
5372 gchar *type_string = g_variant_type_dup_string (reply_type);
5376 G_IO_ERROR_INVALID_ARGUMENT,
5377 _("Method '%s' returned type '%s', but expected '%s'"),
5378 method_name, g_variant_get_type_string (result), type_string);
5380 g_variant_unref (result);
5381 g_free (type_string);
5388 if (out_fd_list != NULL)
5390 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5391 if (*out_fd_list != NULL)
5392 g_object_ref (*out_fd_list);
5398 case G_DBUS_MESSAGE_TYPE_ERROR:
5399 g_dbus_message_to_gerror (reply, error);
5403 g_assert_not_reached ();
5413 GSimpleAsyncResult *simple;
5414 GVariantType *reply_type;
5415 gchar *method_name; /* for error message */
5419 GUnixFDList *fd_list;
5423 call_state_free (CallState *state)
5425 g_variant_type_free (state->reply_type);
5426 g_free (state->method_name);
5428 if (state->value != NULL)
5429 g_variant_unref (state->value);
5430 if (state->fd_list != NULL)
5431 g_object_unref (state->fd_list);
5432 g_slice_free (CallState, state);
5435 /* called in any thread, with the connection's lock not held */
5437 g_dbus_connection_call_done (GObject *source,
5438 GAsyncResult *result,
5441 GSimpleAsyncResult *simple;
5442 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5443 CallState *state = user_data;
5445 GDBusMessage *reply;
5448 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5452 if (G_UNLIKELY (_g_dbus_debug_call ()))
5454 _g_dbus_debug_print_lock ();
5455 g_print ("========================================================================\n"
5456 "GDBus-debug:Call:\n"
5457 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5463 g_print ("SUCCESS\n");
5467 g_print ("FAILED: %s\n",
5470 _g_dbus_debug_print_unlock ();
5474 state->value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5476 simple = state->simple; /* why? because state is freed before we unref simple.. */
5479 g_simple_async_result_take_error (state->simple, error);
5480 g_simple_async_result_complete (state->simple);
5481 call_state_free (state);
5485 g_simple_async_result_set_op_res_gpointer (state->simple, state, (GDestroyNotify) call_state_free);
5486 g_simple_async_result_complete (state->simple);
5488 g_clear_object (&reply);
5489 g_object_unref (simple);
5492 /* called in any thread, with the connection's lock not held */
5494 g_dbus_connection_call_internal (GDBusConnection *connection,
5495 const gchar *bus_name,
5496 const gchar *object_path,
5497 const gchar *interface_name,
5498 const gchar *method_name,
5499 GVariant *parameters,
5500 const GVariantType *reply_type,
5501 GDBusCallFlags flags,
5503 GUnixFDList *fd_list,
5504 GCancellable *cancellable,
5505 GAsyncReadyCallback callback,
5508 GDBusMessage *message;
5511 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5512 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5513 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5514 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5515 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5516 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5517 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5518 g_return_if_fail (check_initialized (connection));
5520 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5522 g_return_if_fail (fd_list == NULL);
5525 message = g_dbus_message_new_method_call (bus_name,
5529 add_call_flags (message, flags);
5530 if (parameters != NULL)
5531 g_dbus_message_set_body (message, parameters);
5534 if (fd_list != NULL)
5535 g_dbus_message_set_unix_fd_list (message, fd_list);
5538 /* If the user has no callback then we can just send the message with
5539 * the G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set and skip all
5540 * the logic for processing the reply. If the service sends the reply
5541 * anyway then it will just be ignored.
5543 if (callback != NULL)
5547 state = g_slice_new0 (CallState);
5548 state->simple = g_simple_async_result_new (G_OBJECT (connection),
5549 callback, user_data,
5550 g_dbus_connection_call_internal);
5551 g_simple_async_result_set_check_cancellable (state->simple, cancellable);
5552 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5554 if (reply_type == NULL)
5555 reply_type = G_VARIANT_TYPE_ANY;
5557 state->reply_type = g_variant_type_copy (reply_type);
5559 g_dbus_connection_send_message_with_reply (connection,
5561 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5565 g_dbus_connection_call_done,
5567 serial = state->serial;
5571 GDBusMessageFlags flags;
5573 flags = g_dbus_message_get_flags (message);
5574 flags |= G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
5575 g_dbus_message_set_flags (message, flags);
5577 g_dbus_connection_send_message (connection,
5579 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5583 if (G_UNLIKELY (_g_dbus_debug_call ()))
5585 _g_dbus_debug_print_lock ();
5586 g_print ("========================================================================\n"
5587 "GDBus-debug:Call:\n"
5588 " >>>> ASYNC %s.%s()\n"
5590 " owned by name %s (serial %d)\n",
5594 bus_name != NULL ? bus_name : "(none)",
5596 _g_dbus_debug_print_unlock ();
5599 if (message != NULL)
5600 g_object_unref (message);
5603 /* called in any thread, with the connection's lock not held */
5605 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
5606 GUnixFDList **out_fd_list,
5610 GSimpleAsyncResult *simple;
5613 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5614 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
5615 g_dbus_connection_call_internal), NULL);
5616 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5618 simple = G_SIMPLE_ASYNC_RESULT (res);
5620 if (g_simple_async_result_propagate_error (simple, error))
5623 state = g_simple_async_result_get_op_res_gpointer (simple);
5624 if (out_fd_list != NULL)
5625 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
5626 return g_variant_ref (state->value);
5629 /* called in any user thread, with the connection's lock not held */
5631 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
5632 const gchar *bus_name,
5633 const gchar *object_path,
5634 const gchar *interface_name,
5635 const gchar *method_name,
5636 GVariant *parameters,
5637 const GVariantType *reply_type,
5638 GDBusCallFlags flags,
5640 GUnixFDList *fd_list,
5641 GUnixFDList **out_fd_list,
5642 GCancellable *cancellable,
5645 GDBusMessage *message;
5646 GDBusMessage *reply;
5648 GError *local_error;
5649 GDBusSendMessageFlags send_flags;
5655 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5656 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5657 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5658 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5659 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5660 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5661 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5663 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
5665 g_return_val_if_fail (fd_list == NULL, NULL);
5667 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5669 if (!(flags & CALL_FLAGS_INITIALIZING))
5670 g_return_val_if_fail (check_initialized (connection), FALSE);
5672 if (reply_type == NULL)
5673 reply_type = G_VARIANT_TYPE_ANY;
5675 message = g_dbus_message_new_method_call (bus_name,
5679 add_call_flags (message, flags);
5680 if (parameters != NULL)
5681 g_dbus_message_set_body (message, parameters);
5684 if (fd_list != NULL)
5685 g_dbus_message_set_unix_fd_list (message, fd_list);
5688 if (G_UNLIKELY (_g_dbus_debug_call ()))
5690 _g_dbus_debug_print_lock ();
5691 g_print ("========================================================================\n"
5692 "GDBus-debug:Call:\n"
5693 " >>>> SYNC %s.%s()\n"
5695 " owned by name %s\n",
5699 bus_name != NULL ? bus_name : "(none)");
5700 _g_dbus_debug_print_unlock ();
5705 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
5707 /* translate from one flavour of flags to another... */
5708 if (flags & CALL_FLAGS_INITIALIZING)
5709 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
5711 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5715 NULL, /* volatile guint32 *out_serial */
5719 if (G_UNLIKELY (_g_dbus_debug_call ()))
5721 _g_dbus_debug_print_lock ();
5722 g_print ("========================================================================\n"
5723 "GDBus-debug:Call:\n"
5724 " <<<< SYNC COMPLETE %s.%s()\n"
5730 g_print ("SUCCESS\n");
5734 g_print ("FAILED: %s\n",
5735 local_error->message);
5737 _g_dbus_debug_print_unlock ();
5743 *error = local_error;
5745 g_error_free (local_error);
5749 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
5752 if (message != NULL)
5753 g_object_unref (message);
5755 g_object_unref (reply);
5760 /* ---------------------------------------------------------------------------------------------------- */
5763 * g_dbus_connection_call:
5764 * @connection: A #GDBusConnection.
5765 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5766 * @connection is not a message bus connection.
5767 * @object_path: Path of remote object.
5768 * @interface_name: D-Bus interface to invoke method on.
5769 * @method_name: The name of the method to invoke.
5770 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5771 * or %NULL if not passing parameters.
5772 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5773 * @flags: Flags from the #GDBusCallFlags enumeration.
5774 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5775 * timeout or %G_MAXINT for no timeout.
5776 * @cancellable: (allow-none): A #GCancellable or %NULL.
5777 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5778 * satisfied or %NULL if you don't care about the result of the
5779 * method invocation.
5780 * @user_data: The data to pass to @callback.
5782 * Asynchronously invokes the @method_name method on the
5783 * @interface_name D-Bus interface on the remote object at
5784 * @object_path owned by @bus_name.
5786 * If @connection is closed then the operation will fail with
5787 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
5788 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
5789 * not compatible with the D-Bus protocol, the operation fails with
5790 * %G_IO_ERROR_INVALID_ARGUMENT.
5792 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
5793 * error will be raised if it does not match. Said another way, if you give a @reply_type
5794 * then any non-%NULL return value will be of this type.
5796 * If the @parameters #GVariant is floating, it is consumed. This allows
5797 * convenient 'inline' use of g_variant_new(), e.g.:
5799 * g_dbus_connection_call (connection,
5800 * "org.freedesktop.StringThings",
5801 * "/org/freedesktop/StringThings",
5802 * "org.freedesktop.StringThings",
5804 * g_variant_new ("(ss)",
5808 * G_DBUS_CALL_FLAGS_NONE,
5811 * (GAsyncReadyCallback) two_strings_done,
5815 * This is an asynchronous method. When the operation is finished, @callback will be invoked
5816 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
5817 * of the thread you are calling this method from. You can then call
5818 * g_dbus_connection_call_finish() to get the result of the operation.
5819 * See g_dbus_connection_call_sync() for the synchronous version of this
5822 * If @callback is %NULL then the D-Bus method call message will be sent with
5823 * the %G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set.
5828 g_dbus_connection_call (GDBusConnection *connection,
5829 const gchar *bus_name,
5830 const gchar *object_path,
5831 const gchar *interface_name,
5832 const gchar *method_name,
5833 GVariant *parameters,
5834 const GVariantType *reply_type,
5835 GDBusCallFlags flags,
5837 GCancellable *cancellable,
5838 GAsyncReadyCallback callback,
5841 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);
5845 * g_dbus_connection_call_finish:
5846 * @connection: A #GDBusConnection.
5847 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
5848 * @error: Return location for error or %NULL.
5850 * Finishes an operation started with g_dbus_connection_call().
5852 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5853 * return values. Free with g_variant_unref().
5858 g_dbus_connection_call_finish (GDBusConnection *connection,
5862 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
5866 * g_dbus_connection_call_sync:
5867 * @connection: A #GDBusConnection.
5868 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5869 * @connection is not a message bus connection.
5870 * @object_path: Path of remote object.
5871 * @interface_name: D-Bus interface to invoke method on.
5872 * @method_name: The name of the method to invoke.
5873 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5874 * or %NULL if not passing parameters.
5875 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5876 * @flags: Flags from the #GDBusCallFlags enumeration.
5877 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5878 * timeout or %G_MAXINT for no timeout.
5879 * @cancellable: (allow-none): A #GCancellable or %NULL.
5880 * @error: Return location for error or %NULL.
5882 * Synchronously invokes the @method_name method on the
5883 * @interface_name D-Bus interface on the remote object at
5884 * @object_path owned by @bus_name.
5886 * If @connection is closed then the operation will fail with
5887 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
5888 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
5889 * contains a value not compatible with the D-Bus protocol, the operation
5890 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
5892 * If @reply_type is non-%NULL then the reply will be checked for having
5893 * this type and an error will be raised if it does not match. Said
5894 * another way, if you give a @reply_type then any non-%NULL return
5895 * value will be of this type.
5897 * If the @parameters #GVariant is floating, it is consumed.
5898 * This allows convenient 'inline' use of g_variant_new(), e.g.:
5900 * g_dbus_connection_call_sync (connection,
5901 * "org.freedesktop.StringThings",
5902 * "/org/freedesktop/StringThings",
5903 * "org.freedesktop.StringThings",
5905 * g_variant_new ("(ss)",
5909 * G_DBUS_CALL_FLAGS_NONE,
5915 * The calling thread is blocked until a reply is received. See
5916 * g_dbus_connection_call() for the asynchronous version of
5919 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5920 * return values. Free with g_variant_unref().
5925 g_dbus_connection_call_sync (GDBusConnection *connection,
5926 const gchar *bus_name,
5927 const gchar *object_path,
5928 const gchar *interface_name,
5929 const gchar *method_name,
5930 GVariant *parameters,
5931 const GVariantType *reply_type,
5932 GDBusCallFlags flags,
5934 GCancellable *cancellable,
5937 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);
5940 /* ---------------------------------------------------------------------------------------------------- */
5945 * g_dbus_connection_call_with_unix_fd_list:
5946 * @connection: A #GDBusConnection.
5947 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5948 * @connection is not a message bus connection.
5949 * @object_path: Path of remote object.
5950 * @interface_name: D-Bus interface to invoke method on.
5951 * @method_name: The name of the method to invoke.
5952 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5953 * or %NULL if not passing parameters.
5954 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5955 * @flags: Flags from the #GDBusCallFlags enumeration.
5956 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5957 * timeout or %G_MAXINT for no timeout.
5958 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
5959 * @cancellable: (allow-none): A #GCancellable or %NULL.
5960 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5961 * satisfied or %NULL if you don't * care about the result of the
5962 * method invocation.
5963 * @user_data: The data to pass to @callback.
5965 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
5967 * This method is only available on UNIX.
5972 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
5973 const gchar *bus_name,
5974 const gchar *object_path,
5975 const gchar *interface_name,
5976 const gchar *method_name,
5977 GVariant *parameters,
5978 const GVariantType *reply_type,
5979 GDBusCallFlags flags,
5981 GUnixFDList *fd_list,
5982 GCancellable *cancellable,
5983 GAsyncReadyCallback callback,
5986 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);
5990 * g_dbus_connection_call_with_unix_fd_list_finish:
5991 * @connection: A #GDBusConnection.
5992 * @out_fd_list: (out) (allow-none): Return location for a #GUnixFDList or %NULL.
5993 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call_with_unix_fd_list().
5994 * @error: Return location for error or %NULL.
5996 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
5998 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5999 * return values. Free with g_variant_unref().
6004 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
6005 GUnixFDList **out_fd_list,
6009 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
6013 * g_dbus_connection_call_with_unix_fd_list_sync:
6014 * @connection: A #GDBusConnection.
6015 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
6016 * @connection is not a message bus connection.
6017 * @object_path: Path of remote object.
6018 * @interface_name: D-Bus interface to invoke method on.
6019 * @method_name: The name of the method to invoke.
6020 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
6021 * or %NULL if not passing parameters.
6022 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
6023 * @flags: Flags from the #GDBusCallFlags enumeration.
6024 * @timeout_msec: The timeout in milliseconds, -1 to use the default
6025 * timeout or %G_MAXINT for no timeout.
6026 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
6027 * @out_fd_list: (out) (allow-none): Return location for a #GUnixFDList or %NULL.
6028 * @cancellable: (allow-none): A #GCancellable or %NULL.
6029 * @error: Return location for error or %NULL.
6031 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
6033 * This method is only available on UNIX.
6035 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6036 * return values. Free with g_variant_unref().
6041 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
6042 const gchar *bus_name,
6043 const gchar *object_path,
6044 const gchar *interface_name,
6045 const gchar *method_name,
6046 GVariant *parameters,
6047 const GVariantType *reply_type,
6048 GDBusCallFlags flags,
6050 GUnixFDList *fd_list,
6051 GUnixFDList **out_fd_list,
6052 GCancellable *cancellable,
6055 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);
6058 #endif /* G_OS_UNIX */
6060 /* ---------------------------------------------------------------------------------------------------- */
6062 struct ExportedSubtree
6066 GDBusConnection *connection;
6067 GDBusSubtreeVTable *vtable;
6068 GDBusSubtreeFlags flags;
6070 GMainContext *context;
6072 GDestroyNotify user_data_free_func;
6076 exported_subtree_free (ExportedSubtree *es)
6078 call_destroy_notify (es->context,
6079 es->user_data_free_func,
6082 g_main_context_unref (es->context);
6084 _g_dbus_subtree_vtable_free (es->vtable);
6085 g_free (es->object_path);
6089 /* called without lock held in the thread where the caller registered
6093 handle_subtree_introspect (GDBusConnection *connection,
6094 ExportedSubtree *es,
6095 GDBusMessage *message)
6099 GDBusMessage *reply;
6102 const gchar *sender;
6103 const gchar *requested_object_path;
6104 const gchar *requested_node;
6105 GDBusInterfaceInfo **interfaces;
6107 gchar **subnode_paths;
6108 gboolean has_properties_interface;
6109 gboolean has_introspectable_interface;
6113 requested_object_path = g_dbus_message_get_path (message);
6114 sender = g_dbus_message_get_sender (message);
6115 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6117 s = g_string_new (NULL);
6118 introspect_append_header (s);
6120 /* Strictly we don't need the children in dynamic mode, but we avoid the
6121 * conditionals to preserve code clarity
6123 children = es->vtable->enumerate (es->connection,
6130 requested_node = strrchr (requested_object_path, '/') + 1;
6132 /* Assert existence of object if we are not dynamic */
6133 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
6134 !_g_strv_has_string ((const gchar * const *) children, requested_node))
6139 requested_node = NULL;
6142 interfaces = es->vtable->introspect (es->connection,
6147 if (interfaces != NULL)
6149 has_properties_interface = FALSE;
6150 has_introspectable_interface = FALSE;
6152 for (n = 0; interfaces[n] != NULL; n++)
6154 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
6155 has_properties_interface = TRUE;
6156 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
6157 has_introspectable_interface = TRUE;
6159 if (!has_properties_interface)
6160 g_string_append (s, introspect_properties_interface);
6161 if (!has_introspectable_interface)
6162 g_string_append (s, introspect_introspectable_interface);
6164 for (n = 0; interfaces[n] != NULL; n++)
6166 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
6167 g_dbus_interface_info_unref (interfaces[n]);
6169 g_free (interfaces);
6172 /* then include <node> entries from the Subtree for the root */
6175 for (n = 0; children != NULL && children[n] != NULL; n++)
6176 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
6179 /* finally include nodes registered below us */
6180 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
6181 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
6182 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
6183 g_strfreev (subnode_paths);
6185 g_string_append (s, "</node>\n");
6187 reply = g_dbus_message_new_method_reply (message);
6188 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6189 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6190 g_object_unref (reply);
6195 g_string_free (s, TRUE);
6196 g_strfreev (children);
6200 /* called without lock held in the thread where the caller registered
6204 handle_subtree_method_invocation (GDBusConnection *connection,
6205 ExportedSubtree *es,
6206 GDBusMessage *message)
6209 const gchar *sender;
6210 const gchar *interface_name;
6211 const gchar *member;
6212 const gchar *signature;
6213 const gchar *requested_object_path;
6214 const gchar *requested_node;
6216 GDBusInterfaceInfo *interface_info;
6217 const GDBusInterfaceVTable *interface_vtable;
6218 gpointer interface_user_data;
6220 GDBusInterfaceInfo **interfaces;
6221 gboolean is_property_get;
6222 gboolean is_property_set;
6223 gboolean is_property_get_all;
6228 requested_object_path = g_dbus_message_get_path (message);
6229 sender = g_dbus_message_get_sender (message);
6230 interface_name = g_dbus_message_get_interface (message);
6231 member = g_dbus_message_get_member (message);
6232 signature = g_dbus_message_get_signature (message);
6233 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6235 is_property_get = FALSE;
6236 is_property_set = FALSE;
6237 is_property_get_all = FALSE;
6238 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6240 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6241 is_property_get = TRUE;
6242 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6243 is_property_set = TRUE;
6244 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6245 is_property_get_all = TRUE;
6250 requested_node = strrchr (requested_object_path, '/') + 1;
6252 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6254 /* We don't want to dispatch to unenumerated
6255 * nodes, so ensure that the child exists.
6260 children = es->vtable->enumerate (es->connection,
6265 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6266 g_strfreev (children);
6274 requested_node = NULL;
6277 /* get introspection data for the node */
6278 interfaces = es->vtable->introspect (es->connection,
6280 requested_object_path,
6284 if (interfaces == NULL)
6287 interface_info = NULL;
6288 for (n = 0; interfaces[n] != NULL; n++)
6290 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6291 interface_info = interfaces[n];
6294 /* dispatch the call if the user wants to handle it */
6295 if (interface_info != NULL)
6297 /* figure out where to dispatch the method call */
6298 interface_user_data = NULL;
6299 interface_vtable = es->vtable->dispatch (es->connection,
6304 &interface_user_data,
6306 if (interface_vtable == NULL)
6309 CONNECTION_LOCK (connection);
6310 handled = validate_and_maybe_schedule_method_call (es->connection,
6317 interface_user_data);
6318 CONNECTION_UNLOCK (connection);
6320 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6321 else if (is_property_get || is_property_set || is_property_get_all)
6323 if (is_property_get)
6324 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6325 else if (is_property_set)
6326 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6327 else if (is_property_get_all)
6328 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6330 g_assert_not_reached ();
6332 /* see if the object supports this interface at all */
6333 for (n = 0; interfaces[n] != NULL; n++)
6335 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6336 interface_info = interfaces[n];
6339 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6340 * claims it won't support the interface
6342 if (interface_info == NULL)
6344 GDBusMessage *reply;
6345 reply = g_dbus_message_new_method_error (message,
6346 "org.freedesktop.DBus.Error.InvalidArgs",
6347 _("No such interface '%s'"),
6349 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6350 g_object_unref (reply);
6355 /* figure out where to dispatch the property get/set/getall calls */
6356 interface_user_data = NULL;
6357 interface_vtable = es->vtable->dispatch (es->connection,
6362 &interface_user_data,
6364 if (interface_vtable == NULL)
6366 g_warning ("The subtree introspection function indicates that '%s' "
6367 "is a valid interface name, but calling the dispatch "
6368 "function on that interface gave us NULL", interface_name);
6372 if (is_property_get || is_property_set)
6374 CONNECTION_LOCK (connection);
6375 handled = validate_and_maybe_schedule_property_getset (es->connection,
6383 interface_user_data);
6384 CONNECTION_UNLOCK (connection);
6386 else if (is_property_get_all)
6388 CONNECTION_LOCK (connection);
6389 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6396 interface_user_data);
6397 CONNECTION_UNLOCK (connection);
6402 if (interfaces != NULL)
6404 for (n = 0; interfaces[n] != NULL; n++)
6405 g_dbus_interface_info_unref (interfaces[n]);
6406 g_free (interfaces);
6414 GDBusMessage *message;
6415 ExportedSubtree *es;
6416 } SubtreeDeferredData;
6419 subtree_deferred_data_free (SubtreeDeferredData *data)
6421 g_object_unref (data->message);
6425 /* called without lock held in the thread where the caller registered the subtree */
6427 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6429 SubtreeDeferredData *data = _data;
6434 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6435 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6436 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6437 handled = handle_subtree_introspect (data->es->connection,
6441 handled = handle_subtree_method_invocation (data->es->connection,
6447 CONNECTION_LOCK (data->es->connection);
6448 handled = handle_generic_unlocked (data->es->connection, data->message);
6449 CONNECTION_UNLOCK (data->es->connection);
6452 /* if we couldn't handle the request, just bail with the UnknownMethod error */
6455 GDBusMessage *reply;
6456 reply = g_dbus_message_new_method_error (data->message,
6457 "org.freedesktop.DBus.Error.UnknownMethod",
6458 _("Method '%s' on interface '%s' with signature '%s' does not exist"),
6459 g_dbus_message_get_member (data->message),
6460 g_dbus_message_get_interface (data->message),
6461 g_dbus_message_get_signature (data->message));
6462 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6463 g_object_unref (reply);
6469 /* called in GDBusWorker thread with connection's lock held */
6471 subtree_message_func (GDBusConnection *connection,
6472 ExportedSubtree *es,
6473 GDBusMessage *message)
6475 GSource *idle_source;
6476 SubtreeDeferredData *data;
6478 data = g_new0 (SubtreeDeferredData, 1);
6479 data->message = g_object_ref (message);
6482 /* defer this call to an idle handler in the right thread */
6483 idle_source = g_idle_source_new ();
6484 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
6485 g_source_set_callback (idle_source,
6486 process_subtree_vtable_message_in_idle_cb,
6488 (GDestroyNotify) subtree_deferred_data_free);
6489 g_source_attach (idle_source, es->context);
6490 g_source_unref (idle_source);
6492 /* since we own the entire subtree, handlers for objects not in the subtree have been
6493 * tried already by libdbus-1 - so we just need to ensure that we're always going
6494 * to reply to the message
6500 * g_dbus_connection_register_subtree:
6501 * @connection: A #GDBusConnection.
6502 * @object_path: The object path to register the subtree at.
6503 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
6504 * @flags: Flags used to fine tune the behavior of the subtree.
6505 * @user_data: Data to pass to functions in @vtable.
6506 * @user_data_free_func: Function to call when the subtree is unregistered.
6507 * @error: Return location for error or %NULL.
6509 * Registers a whole subtree of <quote>dynamic</quote> objects.
6511 * The @enumerate and @introspection functions in @vtable are used to
6512 * convey, to remote callers, what nodes exist in the subtree rooted
6515 * When handling remote calls into any node in the subtree, first the
6516 * @enumerate function is used to check if the node exists. If the node exists
6517 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6518 * the @introspection function is used to check if the node supports the
6519 * requested method. If so, the @dispatch function is used to determine
6520 * where to dispatch the call. The collected #GDBusInterfaceVTable and
6521 * #gpointer will be used to call into the interface vtable for processing
6524 * All calls into user-provided code will be invoked in the <link
6525 * linkend="g-main-context-push-thread-default">thread-default main
6526 * loop</link> of the thread you are calling this method from.
6528 * If an existing subtree is already registered at @object_path or
6529 * then @error is set to #G_IO_ERROR_EXISTS.
6531 * Note that it is valid to register regular objects (using
6532 * g_dbus_connection_register_object()) in a subtree registered with
6533 * g_dbus_connection_register_subtree() - if so, the subtree handler
6534 * is tried as the last resort. One way to think about a subtree
6535 * handler is to consider it a <quote>fallback handler</quote>
6536 * for object paths not registered via g_dbus_connection_register_object()
6537 * or other bindings.
6539 * Note that @vtable will be copied so you cannot change it after
6542 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
6544 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
6545 * that can be used with g_dbus_connection_unregister_subtree() .
6550 g_dbus_connection_register_subtree (GDBusConnection *connection,
6551 const gchar *object_path,
6552 const GDBusSubtreeVTable *vtable,
6553 GDBusSubtreeFlags flags,
6555 GDestroyNotify user_data_free_func,
6559 ExportedSubtree *es;
6561 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
6562 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
6563 g_return_val_if_fail (vtable != NULL, 0);
6564 g_return_val_if_fail (error == NULL || *error == NULL, 0);
6565 g_return_val_if_fail (check_initialized (connection), 0);
6569 CONNECTION_LOCK (connection);
6571 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6577 _("A subtree is already exported for %s"),
6582 es = g_new0 (ExportedSubtree, 1);
6583 es->object_path = g_strdup (object_path);
6584 es->connection = connection;
6586 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
6588 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
6589 es->user_data = user_data;
6590 es->user_data_free_func = user_data_free_func;
6591 es->context = g_main_context_ref_thread_default ();
6593 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
6594 g_hash_table_insert (connection->map_id_to_es,
6595 GUINT_TO_POINTER (es->id),
6601 CONNECTION_UNLOCK (connection);
6606 /* ---------------------------------------------------------------------------------------------------- */
6609 * g_dbus_connection_unregister_subtree:
6610 * @connection: A #GDBusConnection.
6611 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
6613 * Unregisters a subtree.
6615 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
6620 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
6621 guint registration_id)
6623 ExportedSubtree *es;
6626 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
6627 g_return_val_if_fail (check_initialized (connection), FALSE);
6631 CONNECTION_LOCK (connection);
6633 es = g_hash_table_lookup (connection->map_id_to_es,
6634 GUINT_TO_POINTER (registration_id));
6638 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
6639 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
6644 CONNECTION_UNLOCK (connection);
6649 /* ---------------------------------------------------------------------------------------------------- */
6651 /* may be called in any thread, with connection's lock held */
6653 handle_generic_ping_unlocked (GDBusConnection *connection,
6654 const gchar *object_path,
6655 GDBusMessage *message)
6657 GDBusMessage *reply;
6658 reply = g_dbus_message_new_method_reply (message);
6659 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6660 g_object_unref (reply);
6663 /* may be called in any thread, with connection's lock held */
6665 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
6666 const gchar *object_path,
6667 GDBusMessage *message)
6669 GDBusMessage *reply;
6672 if (connection->machine_id == NULL)
6677 connection->machine_id = _g_dbus_get_machine_id (&error);
6678 if (connection->machine_id == NULL)
6680 reply = g_dbus_message_new_method_error_literal (message,
6681 "org.freedesktop.DBus.Error.Failed",
6683 g_error_free (error);
6689 reply = g_dbus_message_new_method_reply (message);
6690 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
6692 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6693 g_object_unref (reply);
6696 /* may be called in any thread, with connection's lock held */
6698 handle_generic_introspect_unlocked (GDBusConnection *connection,
6699 const gchar *object_path,
6700 GDBusMessage *message)
6705 GDBusMessage *reply;
6707 /* first the header */
6708 s = g_string_new (NULL);
6709 introspect_append_header (s);
6711 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
6712 for (n = 0; registered != NULL && registered[n] != NULL; n++)
6713 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
6714 g_strfreev (registered);
6715 g_string_append (s, "</node>\n");
6717 reply = g_dbus_message_new_method_reply (message);
6718 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6719 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6720 g_object_unref (reply);
6721 g_string_free (s, TRUE);
6724 /* may be called in any thread, with connection's lock held */
6726 handle_generic_unlocked (GDBusConnection *connection,
6727 GDBusMessage *message)
6730 const gchar *interface_name;
6731 const gchar *member;
6732 const gchar *signature;
6735 CONNECTION_ENSURE_LOCK (connection);
6739 interface_name = g_dbus_message_get_interface (message);
6740 member = g_dbus_message_get_member (message);
6741 signature = g_dbus_message_get_signature (message);
6742 path = g_dbus_message_get_path (message);
6744 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
6745 g_strcmp0 (member, "Introspect") == 0 &&
6746 g_strcmp0 (signature, "") == 0)
6748 handle_generic_introspect_unlocked (connection, path, message);
6751 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6752 g_strcmp0 (member, "Ping") == 0 &&
6753 g_strcmp0 (signature, "") == 0)
6755 handle_generic_ping_unlocked (connection, path, message);
6758 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6759 g_strcmp0 (member, "GetMachineId") == 0 &&
6760 g_strcmp0 (signature, "") == 0)
6762 handle_generic_get_machine_id_unlocked (connection, path, message);
6769 /* ---------------------------------------------------------------------------------------------------- */
6771 /* called in GDBusWorker thread with connection's lock held */
6773 distribute_method_call (GDBusConnection *connection,
6774 GDBusMessage *message)
6776 GDBusMessage *reply;
6778 ExportedSubtree *es;
6779 const gchar *object_path;
6780 const gchar *interface_name;
6781 const gchar *member;
6783 gchar *subtree_path;
6786 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
6788 interface_name = g_dbus_message_get_interface (message);
6789 member = g_dbus_message_get_member (message);
6790 path = g_dbus_message_get_path (message);
6791 subtree_path = g_strdup (path);
6792 needle = strrchr (subtree_path, '/');
6793 if (needle != NULL && needle != subtree_path)
6799 g_free (subtree_path);
6800 subtree_path = NULL;
6804 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
6806 _g_dbus_debug_print_lock ();
6807 g_print ("========================================================================\n"
6808 "GDBus-debug:Incoming:\n"
6809 " <<<< METHOD INVOCATION %s.%s()\n"
6811 " invoked by name %s\n"
6813 interface_name, member,
6815 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
6816 g_dbus_message_get_serial (message));
6817 _g_dbus_debug_print_unlock ();
6820 object_path = g_dbus_message_get_path (message);
6821 g_assert (object_path != NULL);
6823 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
6826 if (obj_message_func (connection, eo, message))
6830 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6833 if (subtree_message_func (connection, es, message))
6837 if (subtree_path != NULL)
6839 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
6842 if (subtree_message_func (connection, es, message))
6847 if (handle_generic_unlocked (connection, message))
6850 /* if we end up here, the message has not been not handled - so return an error saying this */
6851 reply = g_dbus_message_new_method_error (message,
6852 "org.freedesktop.DBus.Error.UnknownMethod",
6853 _("No such interface '%s' on object at path %s"),
6856 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6857 g_object_unref (reply);
6860 g_free (subtree_path);
6863 /* ---------------------------------------------------------------------------------------------------- */
6865 /* Called in any user thread, with the message_bus_lock held. */
6867 message_bus_get_singleton (GBusType bus_type,
6871 const gchar *starter_bus;
6877 case G_BUS_TYPE_SESSION:
6878 ret = &the_session_bus;
6881 case G_BUS_TYPE_SYSTEM:
6882 ret = &the_system_bus;
6885 case G_BUS_TYPE_STARTER:
6886 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
6887 if (g_strcmp0 (starter_bus, "session") == 0)
6889 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
6892 else if (g_strcmp0 (starter_bus, "system") == 0)
6894 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
6899 if (starter_bus != NULL)
6903 G_IO_ERROR_INVALID_ARGUMENT,
6904 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
6905 " - unknown value '%s'"),
6910 g_set_error_literal (error,
6912 G_IO_ERROR_INVALID_ARGUMENT,
6913 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
6914 "variable is not set"));
6920 g_assert_not_reached ();
6928 /* Called in any user thread, without holding locks. */
6929 static GDBusConnection *
6930 get_uninitialized_connection (GBusType bus_type,
6931 GCancellable *cancellable,
6934 GWeakRef *singleton;
6935 GDBusConnection *ret;
6939 G_LOCK (message_bus_lock);
6940 singleton = message_bus_get_singleton (bus_type, error);
6941 if (singleton == NULL)
6944 ret = g_weak_ref_get (singleton);
6949 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
6950 if (address == NULL)
6952 ret = g_object_new (G_TYPE_DBUS_CONNECTION,
6954 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
6955 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
6956 "exit-on-close", TRUE,
6959 g_weak_ref_set (singleton, ret);
6963 g_assert (ret != NULL);
6966 G_UNLOCK (message_bus_lock);
6970 /* May be called from any thread. Must not hold message_bus_lock. */
6972 _g_bus_get_singleton_if_exists (GBusType bus_type)
6974 GWeakRef *singleton;
6975 GDBusConnection *ret = NULL;
6977 G_LOCK (message_bus_lock);
6978 singleton = message_bus_get_singleton (bus_type, NULL);
6979 if (singleton == NULL)
6982 ret = g_weak_ref_get (singleton);
6985 G_UNLOCK (message_bus_lock);
6991 * @bus_type: A #GBusType.
6992 * @cancellable: (allow-none): A #GCancellable or %NULL.
6993 * @error: Return location for error or %NULL.
6995 * Synchronously connects to the message bus specified by @bus_type.
6996 * Note that the returned object may shared with other callers,
6997 * e.g. if two separate parts of a process calls this function with
6998 * the same @bus_type, they will share the same object.
7000 * This is a synchronous failable function. See g_bus_get() and
7001 * g_bus_get_finish() for the asynchronous version.
7003 * The returned object is a singleton, that is, shared with other
7004 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7005 * event that you need a private message bus connection, use
7006 * g_dbus_address_get_for_bus_sync() and
7007 * g_dbus_connection_new_for_address().
7009 * Note that the returned #GDBusConnection object will (usually) have
7010 * the #GDBusConnection:exit-on-close property set to %TRUE.
7012 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
7017 g_bus_get_sync (GBusType bus_type,
7018 GCancellable *cancellable,
7021 GDBusConnection *connection;
7023 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7025 connection = get_uninitialized_connection (bus_type, cancellable, error);
7026 if (connection == NULL)
7029 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
7031 g_object_unref (connection);
7040 bus_get_async_initable_cb (GObject *source_object,
7044 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
7048 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
7052 g_assert (error != NULL);
7053 g_simple_async_result_take_error (simple, error);
7054 g_object_unref (source_object);
7058 g_simple_async_result_set_op_res_gpointer (simple,
7062 g_simple_async_result_complete_in_idle (simple);
7063 g_object_unref (simple);
7068 * @bus_type: A #GBusType.
7069 * @cancellable: (allow-none): A #GCancellable or %NULL.
7070 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
7071 * @user_data: The data to pass to @callback.
7073 * Asynchronously connects to the message bus specified by @bus_type.
7075 * When the operation is finished, @callback will be invoked. You can
7076 * then call g_bus_get_finish() to get the result of the operation.
7078 * This is a asynchronous failable function. See g_bus_get_sync() for
7079 * the synchronous version.
7084 g_bus_get (GBusType bus_type,
7085 GCancellable *cancellable,
7086 GAsyncReadyCallback callback,
7089 GDBusConnection *connection;
7090 GSimpleAsyncResult *simple;
7093 simple = g_simple_async_result_new (NULL,
7097 g_simple_async_result_set_check_cancellable (simple, cancellable);
7100 connection = get_uninitialized_connection (bus_type, cancellable, &error);
7101 if (connection == NULL)
7103 g_assert (error != NULL);
7104 g_simple_async_result_take_error (simple, error);
7105 g_simple_async_result_complete_in_idle (simple);
7106 g_object_unref (simple);
7110 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
7113 bus_get_async_initable_cb,
7120 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
7121 * @error: Return location for error or %NULL.
7123 * Finishes an operation started with g_bus_get().
7125 * The returned object is a singleton, that is, shared with other
7126 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7127 * event that you need a private message bus connection, use
7128 * g_dbus_address_get_for_bus_sync() and
7129 * g_dbus_connection_new_for_address().
7131 * Note that the returned #GDBusConnection object will (usually) have
7132 * the #GDBusConnection:exit-on-close property set to %TRUE.
7134 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
7139 g_bus_get_finish (GAsyncResult *res,
7142 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
7144 GDBusConnection *ret;
7146 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7148 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
7152 if (g_simple_async_result_propagate_error (simple, error))
7155 object = g_simple_async_result_get_op_res_gpointer (simple);
7156 g_assert (object != NULL);
7157 ret = g_object_ref (G_DBUS_CONNECTION (object));
7163 /* ---------------------------------------------------------------------------------------------------- */