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
108 #include <sys/types.h>
113 #include "gdbusauth.h"
114 #include "gdbusutils.h"
115 #include "gdbusaddress.h"
116 #include "gdbusmessage.h"
117 #include "gdbusconnection.h"
118 #include "gdbuserror.h"
119 #include "gioenumtypes.h"
120 #include "gdbusintrospection.h"
121 #include "gdbusmethodinvocation.h"
122 #include "gdbusprivate.h"
123 #include "gdbusauthobserver.h"
124 #include "ginitable.h"
125 #include "gasyncinitable.h"
126 #include "giostream.h"
127 #include "gasyncresult.h"
128 #include "gsimpleasyncresult.h"
131 #include "gunixconnection.h"
132 #include "gunixfdmessage.h"
135 #include "glibintl.h"
138 * SECTION:gdbusconnection
139 * @short_description: D-Bus Connections
140 * @include: gio/gio.h
142 * The #GDBusConnection type is used for D-Bus connections to remote
143 * peers such as a message buses. It is a low-level API that offers a
144 * lot of flexibility. For instance, it lets you establish a connection
145 * over any transport that can by represented as an #GIOStream.
147 * This class is rarely used directly in D-Bus clients. If you are writing
148 * an D-Bus client, it is often easier to use the g_bus_own_name(),
149 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
151 * As an exception to the usual GLib rule that a particular object must not be
152 * used by two threads at the same time, #GDBusConnection's methods may be
153 * called from any thread<footnote>
155 * This is so that g_bus_get() and g_bus_get_sync() can safely return the
156 * same #GDBusConnection when called from any thread.
160 * Most of the ways to obtain a #GDBusConnection automatically initialize it
161 * (i.e. connect to D-Bus): for instance, g_dbus_connection_new() and
162 * g_bus_get(), and the synchronous versions of those methods, give you an
163 * initialized connection. Language bindings for GIO should use
164 * g_initable_new() or g_async_initable_new(), which also initialize the
167 * If you construct an uninitialized #GDBusConnection, such as via
168 * g_object_new(), you must initialize it via g_initable_init() or
169 * g_async_initable_init() before using its methods or properties. Calling
170 * methods or accessing properties on a #GDBusConnection that has not completed
171 * initialization successfully is considered to be invalid, and leads to
172 * undefined behaviour. In particular, if initialization fails with a #GError,
173 * the only valid thing you can do with that #GDBusConnection is to free it
174 * with g_object_unref().
176 * <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>
178 * <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>
180 * <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>
182 * <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>
185 /* ---------------------------------------------------------------------------------------------------- */
187 typedef struct _GDBusConnectionClass GDBusConnectionClass;
190 * GDBusConnectionClass:
191 * @closed: Signal class handler for the #GDBusConnection::closed signal.
193 * Class structure for #GDBusConnection.
197 struct _GDBusConnectionClass
200 GObjectClass parent_class;
204 void (*closed) (GDBusConnection *connection,
205 gboolean remote_peer_vanished,
209 G_LOCK_DEFINE_STATIC (message_bus_lock);
211 static GWeakRef the_session_bus;
212 static GWeakRef the_system_bus;
214 /* Extra pseudo-member of GDBusSendMessageFlags.
215 * Set by initable_init() to indicate that despite not being initialized yet,
216 * enough of the only-valid-after-init members are set that we can send a
217 * message, and we're being called from its thread, so no memory barrier is
218 * required before accessing them.
220 #define SEND_MESSAGE_FLAGS_INITIALIZING (1<<31)
222 /* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
223 #define CALL_FLAGS_INITIALIZING (1<<31)
225 /* ---------------------------------------------------------------------------------------------------- */
229 GDestroyNotify callback;
231 GMainContext *context;
232 } CallDestroyNotifyData;
235 call_destroy_notify_data_in_idle (gpointer user_data)
237 CallDestroyNotifyData *data = user_data;
238 data->callback (data->user_data);
243 call_destroy_notify_data_free (CallDestroyNotifyData *data)
245 if (data->context != NULL)
246 g_main_context_unref (data->context);
251 * call_destroy_notify: <internal>
252 * @context: A #GMainContext or %NULL.
253 * @callback: A #GDestroyNotify or %NULL.
254 * @user_data: Data to pass to @callback.
256 * Schedules @callback to run in @context.
259 call_destroy_notify (GMainContext *context,
260 GDestroyNotify callback,
263 GSource *idle_source;
264 CallDestroyNotifyData *data;
266 if (callback == NULL)
269 data = g_new0 (CallDestroyNotifyData, 1);
270 data->callback = callback;
271 data->user_data = user_data;
272 data->context = context;
273 if (data->context != NULL)
274 g_main_context_ref (data->context);
276 idle_source = g_idle_source_new ();
277 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
278 g_source_set_callback (idle_source,
279 call_destroy_notify_data_in_idle,
281 (GDestroyNotify) call_destroy_notify_data_free);
282 g_source_attach (idle_source, data->context);
283 g_source_unref (idle_source);
289 /* ---------------------------------------------------------------------------------------------------- */
292 _g_strv_has_string (const gchar* const *haystack,
297 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
299 if (g_strcmp0 (haystack[n], needle) == 0)
305 /* ---------------------------------------------------------------------------------------------------- */
308 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
310 // TODO: for some reason this doesn't work on Windows
311 #define CONNECTION_ENSURE_LOCK(obj) do { \
312 if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock))) \
314 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
315 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
320 #define CONNECTION_LOCK(obj) do { \
321 g_mutex_lock (&(obj)->lock); \
324 #define CONNECTION_UNLOCK(obj) do { \
325 g_mutex_unlock (&(obj)->lock); \
328 /* Flags in connection->atomic_flags */
330 FLAG_INITIALIZED = 1 << 0,
331 FLAG_EXIT_ON_CLOSE = 1 << 1,
338 * The #GDBusConnection structure contains only private data and
339 * should only be accessed using the provided API.
343 struct _GDBusConnection
346 GObject parent_instance;
348 /* ------------------------------------------------------------------------ */
349 /* -- General object state ------------------------------------------------ */
350 /* ------------------------------------------------------------------------ */
352 /* General-purpose lock for most fields */
355 /* A lock used in the init() method of the GInitable interface - see comments
356 * in initable_init() for why a separate lock is needed.
358 * If you need both @lock and @init_lock, you must take @init_lock first.
362 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
363 * someone calls org.freedesktop.DBus.GetMachineId(). Protected by @lock.
367 /* The underlying stream used for communication
368 * Read-only after initable_init(), so it may be read if you either
369 * hold @init_lock or check for initialization first.
373 /* The object used for authentication (if any).
374 * Read-only after initable_init(), so it may be read if you either
375 * hold @init_lock or check for initialization first.
379 /* Last serial used. Protected by @lock. */
382 /* The object used to send/receive messages.
383 * Read-only after initable_init(), so it may be read if you either
384 * hold @init_lock or check for initialization first.
388 /* If connected to a message bus, this contains the unique name assigned to
389 * us by the bus (e.g. ":1.42").
390 * Read-only after initable_init(), so it may be read if you either
391 * hold @init_lock or check for initialization first.
393 gchar *bus_unique_name;
395 /* The GUID returned by the other side if we authenticed as a client or
396 * the GUID to use if authenticating as a server.
397 * Read-only after initable_init(), so it may be read if you either
398 * hold @init_lock or check for initialization first.
402 /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
403 * Inspect @initialization_error to see whether it succeeded or failed.
405 * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
407 * FLAG_CLOSED is the closed property. It may be read at any time, but
408 * may only be written while holding @lock.
410 volatile gint atomic_flags;
412 /* If the connection could not be established during initable_init(),
413 * this GError will be set.
414 * Read-only after initable_init(), so it may be read if you either
415 * hold @init_lock or check for initialization first.
417 GError *initialization_error;
419 /* The result of g_main_context_ref_thread_default() when the object
420 * was created (the GObject _init() function) - this is used for delivery
421 * of the :closed GObject signal.
423 * Only set in the GObject init function, so no locks are needed.
425 GMainContext *main_context_at_construction;
427 /* Read-only construct properties, no locks needed */
429 GDBusConnectionFlags flags;
431 /* Map used for managing method replies, protected by @lock */
432 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
434 /* Maps used for managing signal subscription, protected by @lock */
435 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
436 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
437 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
439 /* Maps used for managing exported objects and subtrees,
442 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
443 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
444 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
445 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
447 /* Structure used for message filters, protected by @lock */
450 /* Capabilities negotiated during authentication
451 * Read-only after initable_init(), so it may be read without holding a
452 * lock, if you check for initialization first.
454 GDBusCapabilityFlags capabilities;
456 /* Protected by @init_lock */
457 GDBusAuthObserver *authentication_observer;
459 /* Read-only after initable_init(), so it may be read if you either
460 * hold @init_lock or check for initialization first.
462 GCredentials *credentials;
464 /* set to TRUE when finalizing */
468 typedef struct ExportedObject ExportedObject;
469 static void exported_object_free (ExportedObject *eo);
471 typedef struct ExportedSubtree ExportedSubtree;
472 static void exported_subtree_free (ExportedSubtree *es);
490 PROP_CAPABILITY_FLAGS,
491 PROP_AUTHENTICATION_OBSERVER,
494 static void distribute_signals (GDBusConnection *connection,
495 GDBusMessage *message);
497 static void distribute_method_call (GDBusConnection *connection,
498 GDBusMessage *message);
500 static gboolean handle_generic_unlocked (GDBusConnection *connection,
501 GDBusMessage *message);
504 static void purge_all_signal_subscriptions (GDBusConnection *connection);
505 static void purge_all_filters (GDBusConnection *connection);
507 #define _G_ENSURE_LOCK(name) do { \
508 if (G_UNLIKELY (G_TRYLOCK(name))) \
510 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
511 "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
515 static guint signals[LAST_SIGNAL] = { 0 };
517 static void initable_iface_init (GInitableIface *initable_iface);
518 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
520 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
521 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
522 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
526 * Check that all members of @connection that can only be accessed after
527 * the connection is initialized can safely be accessed. If not,
528 * log a critical warning. This function is a memory barrier.
530 * Returns: %TRUE if initialized
533 check_initialized (GDBusConnection *connection)
535 /* The access to @atomic_flags isn't conditional, so that this function
536 * provides a memory barrier for thread-safety even if checks are disabled.
537 * (If you don't want this stricter guarantee, you can call
538 * g_return_if_fail (check_initialized (c)).)
540 * This isn't strictly necessary now that we've decided use of an
541 * uninitialized GDBusConnection is undefined behaviour, but it seems
542 * better to be as deterministic as is feasible.
544 * (Anything that could suffer a crash from seeing undefined values
545 * must have a race condition - thread A initializes the connection while
546 * thread B calls a method without initialization, hoping that thread A will
547 * win the race - so its behaviour is undefined anyway.)
549 gint flags = g_atomic_int_get (&connection->atomic_flags);
551 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
553 /* We can safely access this, due to the memory barrier above */
554 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
560 MAY_BE_UNINITIALIZED = (1<<1)
561 } CheckUnclosedFlags;
564 * Check the same thing as check_initialized(), and also that the
565 * connection is not closed. If the connection is uninitialized,
566 * raise a critical warning (it's programmer error); if it's closed,
567 * raise a recoverable GError (it's a runtime error).
569 * This function is a memory barrier.
571 * Returns: %TRUE if initialized and not closed
574 check_unclosed (GDBusConnection *connection,
575 CheckUnclosedFlags check,
578 /* check_initialized() is effectively inlined, so we don't waste time
579 * doing two memory barriers
581 gint flags = g_atomic_int_get (&connection->atomic_flags);
583 if (!(check & MAY_BE_UNINITIALIZED))
585 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
586 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
589 if (flags & FLAG_CLOSED)
591 g_set_error_literal (error,
594 _("The connection is closed"));
601 static GHashTable *alive_connections = NULL;
604 g_dbus_connection_dispose (GObject *object)
606 GDBusConnection *connection = G_DBUS_CONNECTION (object);
608 G_LOCK (message_bus_lock);
609 CONNECTION_LOCK (connection);
610 if (connection->worker != NULL)
612 _g_dbus_worker_stop (connection->worker);
613 connection->worker = NULL;
614 if (alive_connections != NULL)
615 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
619 if (alive_connections != NULL)
620 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
622 CONNECTION_UNLOCK (connection);
623 G_UNLOCK (message_bus_lock);
625 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
626 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
630 g_dbus_connection_finalize (GObject *object)
632 GDBusConnection *connection = G_DBUS_CONNECTION (object);
634 connection->finalizing = TRUE;
636 purge_all_signal_subscriptions (connection);
638 purge_all_filters (connection);
639 g_ptr_array_unref (connection->filters);
641 if (connection->authentication_observer != NULL)
642 g_object_unref (connection->authentication_observer);
644 if (connection->auth != NULL)
645 g_object_unref (connection->auth);
647 if (connection->credentials)
648 g_object_unref (connection->credentials);
650 if (connection->stream != NULL)
652 g_object_unref (connection->stream);
653 connection->stream = NULL;
656 g_free (connection->address);
658 g_free (connection->guid);
659 g_free (connection->bus_unique_name);
661 if (connection->initialization_error != NULL)
662 g_error_free (connection->initialization_error);
664 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
666 g_hash_table_unref (connection->map_rule_to_signal_data);
667 g_hash_table_unref (connection->map_id_to_signal_data);
668 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
670 g_hash_table_unref (connection->map_id_to_ei);
671 g_hash_table_unref (connection->map_object_path_to_eo);
672 g_hash_table_unref (connection->map_id_to_es);
673 g_hash_table_unref (connection->map_object_path_to_es);
675 g_main_context_unref (connection->main_context_at_construction);
677 g_free (connection->machine_id);
679 g_mutex_clear (&connection->init_lock);
680 g_mutex_clear (&connection->lock);
682 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
685 /* called in any user thread, with the connection's lock not held */
687 g_dbus_connection_get_property (GObject *object,
692 GDBusConnection *connection = G_DBUS_CONNECTION (object);
697 g_value_set_object (value, g_dbus_connection_get_stream (connection));
701 g_value_set_string (value, g_dbus_connection_get_guid (connection));
704 case PROP_UNIQUE_NAME:
705 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
709 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
712 case PROP_EXIT_ON_CLOSE:
713 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
716 case PROP_CAPABILITY_FLAGS:
717 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
721 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
726 /* called in any user thread, with the connection's lock not held */
728 g_dbus_connection_set_property (GObject *object,
733 GDBusConnection *connection = G_DBUS_CONNECTION (object);
738 connection->stream = g_value_dup_object (value);
742 connection->guid = g_value_dup_string (value);
746 connection->address = g_value_dup_string (value);
750 connection->flags = g_value_get_flags (value);
753 case PROP_EXIT_ON_CLOSE:
754 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
757 case PROP_AUTHENTICATION_OBSERVER:
758 connection->authentication_observer = g_value_dup_object (value);
762 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
767 /* Base-class implementation of GDBusConnection::closed.
769 * Called in a user thread, by the main context that was thread-default when
770 * the object was constructed.
773 g_dbus_connection_real_closed (GDBusConnection *connection,
774 gboolean remote_peer_vanished,
777 gint flags = g_atomic_int_get (&connection->atomic_flags);
779 /* Because atomic int access is a memory barrier, we can safely read
780 * initialization_error without a lock, as long as we do it afterwards.
782 if (remote_peer_vanished &&
783 (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
784 (flags & FLAG_INITIALIZED) != 0 &&
785 connection->initialization_error == NULL)
789 g_print ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
792 g_quark_to_string (error->domain), error->code);
796 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
803 g_dbus_connection_class_init (GDBusConnectionClass *klass)
805 GObjectClass *gobject_class;
807 gobject_class = G_OBJECT_CLASS (klass);
809 gobject_class->finalize = g_dbus_connection_finalize;
810 gobject_class->dispose = g_dbus_connection_dispose;
811 gobject_class->set_property = g_dbus_connection_set_property;
812 gobject_class->get_property = g_dbus_connection_get_property;
814 klass->closed = g_dbus_connection_real_closed;
817 * GDBusConnection:stream:
819 * The underlying #GIOStream used for I/O.
821 * If this is passed on construction and is a #GSocketConnection,
822 * then the corresponding #GSocket will be put into non-blocking mode.
824 * While the #GDBusConnection is active, it will interact with this
825 * stream from a worker thread, so it is not safe to interact with
826 * the stream directly.
830 g_object_class_install_property (gobject_class,
832 g_param_spec_object ("stream",
834 P_("The underlying streams used for I/O"),
838 G_PARAM_CONSTRUCT_ONLY |
839 G_PARAM_STATIC_NAME |
840 G_PARAM_STATIC_BLURB |
841 G_PARAM_STATIC_NICK));
844 * GDBusConnection:address:
846 * A D-Bus address specifying potential endpoints that can be used
847 * when establishing the connection.
851 g_object_class_install_property (gobject_class,
853 g_param_spec_string ("address",
855 P_("D-Bus address specifying potential socket endpoints"),
858 G_PARAM_CONSTRUCT_ONLY |
859 G_PARAM_STATIC_NAME |
860 G_PARAM_STATIC_BLURB |
861 G_PARAM_STATIC_NICK));
864 * GDBusConnection:flags:
866 * Flags from the #GDBusConnectionFlags enumeration.
870 g_object_class_install_property (gobject_class,
872 g_param_spec_flags ("flags",
875 G_TYPE_DBUS_CONNECTION_FLAGS,
876 G_DBUS_CONNECTION_FLAGS_NONE,
878 G_PARAM_CONSTRUCT_ONLY |
879 G_PARAM_STATIC_NAME |
880 G_PARAM_STATIC_BLURB |
881 G_PARAM_STATIC_NICK));
884 * GDBusConnection:guid:
886 * The GUID of the peer performing the role of server when
889 * If you are constructing a #GDBusConnection and pass
890 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
891 * #GDBusConnection:flags property then you MUST also set this
892 * property to a valid guid.
894 * If you are constructing a #GDBusConnection and pass
895 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
896 * #GDBusConnection:flags property you will be able to read the GUID
897 * of the other peer here after the connection has been successfully
902 g_object_class_install_property (gobject_class,
904 g_param_spec_string ("guid",
906 P_("GUID of the server peer"),
910 G_PARAM_CONSTRUCT_ONLY |
911 G_PARAM_STATIC_NAME |
912 G_PARAM_STATIC_BLURB |
913 G_PARAM_STATIC_NICK));
916 * GDBusConnection:unique-name:
918 * The unique name as assigned by the message bus or %NULL if the
919 * connection is not open or not a message bus connection.
923 g_object_class_install_property (gobject_class,
925 g_param_spec_string ("unique-name",
927 P_("Unique name of bus connection"),
930 G_PARAM_STATIC_NAME |
931 G_PARAM_STATIC_BLURB |
932 G_PARAM_STATIC_NICK));
935 * GDBusConnection:closed:
937 * A boolean specifying whether the connection has been closed.
941 g_object_class_install_property (gobject_class,
943 g_param_spec_boolean ("closed",
945 P_("Whether the connection is closed"),
948 G_PARAM_STATIC_NAME |
949 G_PARAM_STATIC_BLURB |
950 G_PARAM_STATIC_NICK));
953 * GDBusConnection:exit-on-close:
955 * A boolean specifying whether the process will be terminated (by
956 * calling <literal>raise(SIGTERM)</literal>) if the connection
957 * is closed by the remote peer.
961 g_object_class_install_property (gobject_class,
963 g_param_spec_boolean ("exit-on-close",
965 P_("Whether the process is terminated when the connection is closed"),
969 G_PARAM_STATIC_NAME |
970 G_PARAM_STATIC_BLURB |
971 G_PARAM_STATIC_NICK));
974 * GDBusConnection:capabilities:
976 * Flags from the #GDBusCapabilityFlags enumeration
977 * representing connection features negotiated with the other peer.
981 g_object_class_install_property (gobject_class,
982 PROP_CAPABILITY_FLAGS,
983 g_param_spec_flags ("capabilities",
986 G_TYPE_DBUS_CAPABILITY_FLAGS,
987 G_DBUS_CAPABILITY_FLAGS_NONE,
989 G_PARAM_STATIC_NAME |
990 G_PARAM_STATIC_BLURB |
991 G_PARAM_STATIC_NICK));
994 * GDBusConnection:authentication-observer:
996 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
1000 g_object_class_install_property (gobject_class,
1001 PROP_AUTHENTICATION_OBSERVER,
1002 g_param_spec_object ("authentication-observer",
1003 P_("Authentication Observer"),
1004 P_("Object used to assist in the authentication process"),
1005 G_TYPE_DBUS_AUTH_OBSERVER,
1007 G_PARAM_CONSTRUCT_ONLY |
1008 G_PARAM_STATIC_NAME |
1009 G_PARAM_STATIC_BLURB |
1010 G_PARAM_STATIC_NICK));
1013 * GDBusConnection::closed:
1014 * @connection: The #GDBusConnection emitting the signal.
1015 * @remote_peer_vanished: %TRUE if @connection is closed because the
1016 * remote peer closed its end of the connection.
1017 * @error: A #GError with more details about the event or %NULL.
1019 * Emitted when the connection is closed.
1021 * The cause of this event can be
1024 * If g_dbus_connection_close() is called. In this case
1025 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
1026 * </para></listitem>
1028 * If the remote peer closes the connection. In this case
1029 * @remote_peer_vanished is set to %TRUE and @error is set.
1030 * </para></listitem>
1032 * If the remote peer sends invalid or malformed data. In this
1033 * case @remote_peer_vanished is set to %FALSE and @error
1035 * </para></listitem>
1038 * Upon receiving this signal, you should give up your reference to
1039 * @connection. You are guaranteed that this signal is emitted only
1044 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
1045 G_TYPE_DBUS_CONNECTION,
1047 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1058 g_dbus_connection_init (GDBusConnection *connection)
1060 g_mutex_init (&connection->lock);
1061 g_mutex_init (&connection->init_lock);
1063 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
1065 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1067 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1069 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1072 (GDestroyNotify) g_ptr_array_unref);
1074 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1077 (GDestroyNotify) exported_object_free);
1079 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1082 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1085 (GDestroyNotify) exported_subtree_free);
1087 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1090 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1092 connection->filters = g_ptr_array_new ();
1096 * g_dbus_connection_get_stream:
1097 * @connection: a #GDBusConnection
1099 * Gets the underlying stream used for IO.
1101 * While the #GDBusConnection is active, it will interact with this
1102 * stream from a worker thread, so it is not safe to interact with
1103 * the stream directly.
1105 * Returns: (transfer none): the stream used for IO
1110 g_dbus_connection_get_stream (GDBusConnection *connection)
1112 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1114 /* do not use g_return_val_if_fail(), we want the memory barrier */
1115 if (!check_initialized (connection))
1118 return connection->stream;
1122 * g_dbus_connection_start_message_processing:
1123 * @connection: A #GDBusConnection.
1125 * If @connection was created with
1126 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1127 * starts processing messages. Does nothing on if @connection wasn't
1128 * created with this flag or if the method has already been called.
1133 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1135 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1137 /* do not use g_return_val_if_fail(), we want the memory barrier */
1138 if (!check_initialized (connection))
1141 g_assert (connection->worker != NULL);
1142 _g_dbus_worker_unfreeze (connection->worker);
1146 * g_dbus_connection_is_closed:
1147 * @connection: A #GDBusConnection.
1149 * Gets whether @connection is closed.
1151 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
1156 g_dbus_connection_is_closed (GDBusConnection *connection)
1160 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1162 flags = g_atomic_int_get (&connection->atomic_flags);
1164 return (flags & FLAG_CLOSED) ? TRUE : FALSE;
1168 * g_dbus_connection_get_capabilities:
1169 * @connection: A #GDBusConnection.
1171 * Gets the capabilities negotiated with the remote peer
1173 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
1177 GDBusCapabilityFlags
1178 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1180 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1182 /* do not use g_return_val_if_fail(), we want the memory barrier */
1183 if (!check_initialized (connection))
1184 return G_DBUS_CAPABILITY_FLAGS_NONE;
1186 return connection->capabilities;
1189 /* ---------------------------------------------------------------------------------------------------- */
1191 /* Called in a temporary thread without holding locks. */
1193 flush_in_thread_func (GSimpleAsyncResult *res,
1195 GCancellable *cancellable)
1200 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1203 g_simple_async_result_take_error (res, error);
1207 * g_dbus_connection_flush:
1208 * @connection: A #GDBusConnection.
1209 * @cancellable: A #GCancellable or %NULL.
1210 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1211 * satisfied or %NULL if you don't care about the result.
1212 * @user_data: The data to pass to @callback.
1214 * Asynchronously flushes @connection, that is, writes all queued
1215 * outgoing message to the transport and then flushes the transport
1216 * (using g_output_stream_flush_async()). This is useful in programs
1217 * that wants to emit a D-Bus signal and then exit
1218 * immediately. Without flushing the connection, there is no guarantee
1219 * that the message has been sent to the networking buffers in the OS
1222 * This is an asynchronous method. When the operation is finished,
1223 * @callback will be invoked in the <link
1224 * linkend="g-main-context-push-thread-default">thread-default main
1225 * loop</link> of the thread you are calling this method from. You can
1226 * then call g_dbus_connection_flush_finish() to get the result of the
1227 * operation. See g_dbus_connection_flush_sync() for the synchronous
1233 g_dbus_connection_flush (GDBusConnection *connection,
1234 GCancellable *cancellable,
1235 GAsyncReadyCallback callback,
1238 GSimpleAsyncResult *simple;
1240 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1242 simple = g_simple_async_result_new (G_OBJECT (connection),
1245 g_dbus_connection_flush);
1246 g_simple_async_result_run_in_thread (simple,
1247 flush_in_thread_func,
1250 g_object_unref (simple);
1254 * g_dbus_connection_flush_finish:
1255 * @connection: A #GDBusConnection.
1256 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_flush().
1257 * @error: Return location for error or %NULL.
1259 * Finishes an operation started with g_dbus_connection_flush().
1261 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1266 g_dbus_connection_flush_finish (GDBusConnection *connection,
1270 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1275 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1276 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1277 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1279 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1281 if (g_simple_async_result_propagate_error (simple, error))
1291 * g_dbus_connection_flush_sync:
1292 * @connection: A #GDBusConnection.
1293 * @cancellable: A #GCancellable or %NULL.
1294 * @error: Return location for error or %NULL.
1296 * Synchronously flushes @connection. The calling thread is blocked
1297 * until this is done. See g_dbus_connection_flush() for the
1298 * asynchronous version of this method and more details about what it
1301 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1306 g_dbus_connection_flush_sync (GDBusConnection *connection,
1307 GCancellable *cancellable,
1312 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1313 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1317 /* This is only a best-effort attempt to see whether the connection is
1318 * closed, so it doesn't need the lock. If the connection closes just
1319 * after this check, but before scheduling the flush operation, the
1320 * result will be more or less the same as if the connection closed while
1321 * the flush operation was pending - it'll fail with either CLOSED or
1324 if (!check_unclosed (connection, 0, error))
1327 g_assert (connection->worker != NULL);
1329 ret = _g_dbus_worker_flush_sync (connection->worker,
1337 /* ---------------------------------------------------------------------------------------------------- */
1341 GDBusConnection *connection;
1343 gboolean remote_peer_vanished;
1347 emit_closed_data_free (EmitClosedData *data)
1349 g_object_unref (data->connection);
1350 if (data->error != NULL)
1351 g_error_free (data->error);
1355 /* Called in a user thread that has acquired the main context that was
1356 * thread-default when the object was constructed
1359 emit_closed_in_idle (gpointer user_data)
1361 EmitClosedData *data = user_data;
1364 g_object_notify (G_OBJECT (data->connection), "closed");
1365 g_signal_emit (data->connection,
1366 signals[CLOSED_SIGNAL],
1368 data->remote_peer_vanished,
1374 /* Can be called from any thread, must hold lock.
1375 * FLAG_CLOSED must already have been set.
1378 schedule_closed_unlocked (GDBusConnection *connection,
1379 gboolean remote_peer_vanished,
1382 GSource *idle_source;
1383 EmitClosedData *data;
1385 CONNECTION_ENSURE_LOCK (connection);
1387 data = g_new0 (EmitClosedData, 1);
1388 data->connection = g_object_ref (connection);
1389 data->remote_peer_vanished = remote_peer_vanished;
1390 data->error = error != NULL ? g_error_copy (error) : NULL;
1392 idle_source = g_idle_source_new ();
1393 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1394 g_source_set_callback (idle_source,
1395 emit_closed_in_idle,
1397 (GDestroyNotify) emit_closed_data_free);
1398 g_source_attach (idle_source, connection->main_context_at_construction);
1399 g_source_unref (idle_source);
1402 /* ---------------------------------------------------------------------------------------------------- */
1405 * g_dbus_connection_close:
1406 * @connection: A #GDBusConnection.
1407 * @cancellable: A #GCancellable or %NULL.
1408 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1409 * satisfied or %NULL if you don't care about the result.
1410 * @user_data: The data to pass to @callback.
1412 * Closes @connection. Note that this never causes the process to
1413 * exit (this might only happen if the other end of a shared message
1414 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1416 * Once the connection is closed, operations such as sending a message
1417 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1418 * will not automatically flush the connection so queued messages may
1419 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1421 * If @connection is already closed, this method fails with
1422 * %G_IO_ERROR_CLOSED.
1424 * When @connection has been closed, the #GDBusConnection::closed
1425 * signal is emitted in the <link
1426 * linkend="g-main-context-push-thread-default">thread-default main
1427 * loop</link> of the thread that @connection was constructed in.
1429 * This is an asynchronous method. When the operation is finished,
1430 * @callback will be invoked in the <link
1431 * linkend="g-main-context-push-thread-default">thread-default main
1432 * loop</link> of the thread you are calling this method from. You can
1433 * then call g_dbus_connection_close_finish() to get the result of the
1434 * operation. See g_dbus_connection_close_sync() for the synchronous
1440 g_dbus_connection_close (GDBusConnection *connection,
1441 GCancellable *cancellable,
1442 GAsyncReadyCallback callback,
1445 GSimpleAsyncResult *simple;
1447 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1449 /* do not use g_return_val_if_fail(), we want the memory barrier */
1450 if (!check_initialized (connection))
1453 g_assert (connection->worker != NULL);
1455 simple = g_simple_async_result_new (G_OBJECT (connection),
1458 g_dbus_connection_close);
1459 _g_dbus_worker_close (connection->worker, cancellable, simple);
1460 g_object_unref (simple);
1464 * g_dbus_connection_close_finish:
1465 * @connection: A #GDBusConnection.
1466 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_close().
1467 * @error: Return location for error or %NULL.
1469 * Finishes an operation started with g_dbus_connection_close().
1471 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1476 g_dbus_connection_close_finish (GDBusConnection *connection,
1480 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1485 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1486 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1487 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1489 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1491 if (g_simple_async_result_propagate_error (simple, error))
1502 GAsyncResult *result;
1505 /* Can be called by any thread, without the connection lock */
1507 sync_close_cb (GObject *source_object,
1511 SyncCloseData *data = user_data;
1513 data->result = g_object_ref (res);
1514 g_main_loop_quit (data->loop);
1518 * g_dbus_connection_close_sync:
1519 * @connection: A #GDBusConnection.
1520 * @cancellable: A #GCancellable or %NULL.
1521 * @error: Return location for error or %NULL.
1523 * Synchronously closees @connection. The calling thread is blocked
1524 * until this is done. See g_dbus_connection_close() for the
1525 * asynchronous version of this method and more details about what it
1528 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1533 g_dbus_connection_close_sync (GDBusConnection *connection,
1534 GCancellable *cancellable,
1539 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1540 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1544 if (check_unclosed (connection, 0, error))
1546 GMainContext *context;
1549 context = g_main_context_new ();
1550 g_main_context_push_thread_default (context);
1551 data.loop = g_main_loop_new (context, TRUE);
1554 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1555 g_main_loop_run (data.loop);
1556 ret = g_dbus_connection_close_finish (connection, data.result, error);
1558 g_object_unref (data.result);
1559 g_main_loop_unref (data.loop);
1560 g_main_context_pop_thread_default (context);
1561 g_main_context_unref (context);
1567 /* ---------------------------------------------------------------------------------------------------- */
1569 /* Can be called by any thread, with the connection lock held */
1571 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1572 GDBusMessage *message,
1573 GDBusSendMessageFlags flags,
1574 volatile guint32 *out_serial,
1579 guint32 serial_to_use;
1582 CONNECTION_ENSURE_LOCK (connection);
1584 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1585 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1587 /* TODO: check all necessary headers are present */
1592 if (out_serial != NULL)
1595 /* If we're in initable_init(), don't check for being initialized, to avoid
1596 * chicken-and-egg problems. initable_init() is responsible for setting up
1597 * our prerequisites (mainly connection->worker), and only calling us
1598 * from its own thread (so no memory barrier is needed).
1600 if (!check_unclosed (connection,
1601 (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
1605 blob = g_dbus_message_to_blob (message,
1607 connection->capabilities,
1612 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1613 serial_to_use = g_dbus_message_get_serial (message);
1615 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1620 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1623 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1626 g_assert_not_reached ();
1631 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1632 blob_size, serial_to_use, connection);
1633 g_printerr ("----\n");
1634 hexdump (blob, blob_size);
1635 g_printerr ("----\n");
1638 /* TODO: use connection->auth to encode the blob */
1640 if (out_serial != NULL)
1641 *out_serial = serial_to_use;
1643 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
1644 g_dbus_message_set_serial (message, serial_to_use);
1646 g_dbus_message_lock (message);
1647 _g_dbus_worker_send_message (connection->worker,
1651 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1662 * g_dbus_connection_send_message:
1663 * @connection: A #GDBusConnection.
1664 * @message: A #GDBusMessage
1665 * @flags: Flags affecting how the message is sent.
1666 * @out_serial: (out) (allow-none): Return location for serial number assigned
1667 * to @message when sending it or %NULL.
1668 * @error: Return location for error or %NULL.
1670 * Asynchronously sends @message to the peer represented by @connection.
1672 * Unless @flags contain the
1673 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1674 * will be assigned by @connection and set on @message via
1675 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1676 * serial number used will be written to this location prior to
1677 * submitting the message to the underlying transport.
1679 * If @connection is closed then the operation will fail with
1680 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1681 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1683 * See <xref linkend="gdbus-server"/> and <xref
1684 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1685 * low-level API to send and receive UNIX file descriptors.
1687 * Note that @message must be unlocked, unless @flags contain the
1688 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1690 * Returns: %TRUE if the message was well-formed and queued for
1691 * transmission, %FALSE if @error is set.
1696 g_dbus_connection_send_message (GDBusConnection *connection,
1697 GDBusMessage *message,
1698 GDBusSendMessageFlags flags,
1699 volatile guint32 *out_serial,
1704 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1705 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1706 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1707 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1709 CONNECTION_LOCK (connection);
1710 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1711 CONNECTION_UNLOCK (connection);
1715 /* ---------------------------------------------------------------------------------------------------- */
1719 volatile gint ref_count;
1720 GDBusConnection *connection;
1722 GSimpleAsyncResult *simple;
1724 GMainContext *main_context;
1726 GCancellable *cancellable;
1728 gulong cancellable_handler_id;
1730 GSource *timeout_source;
1735 /* Can be called from any thread with or without lock held */
1736 static SendMessageData *
1737 send_message_data_ref (SendMessageData *data)
1739 g_atomic_int_inc (&data->ref_count);
1743 /* Can be called from any thread with or without lock held */
1745 send_message_data_unref (SendMessageData *data)
1747 if (g_atomic_int_dec_and_test (&data->ref_count))
1749 g_assert (data->timeout_source == NULL);
1750 g_assert (data->simple == NULL);
1751 g_assert (data->cancellable_handler_id == 0);
1752 g_object_unref (data->connection);
1753 if (data->cancellable != NULL)
1754 g_object_unref (data->cancellable);
1755 g_main_context_unref (data->main_context);
1760 /* ---------------------------------------------------------------------------------------------------- */
1762 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1764 send_message_with_reply_deliver (SendMessageData *data, gboolean remove)
1766 CONNECTION_ENSURE_LOCK (data->connection);
1768 g_assert (!data->delivered);
1770 data->delivered = TRUE;
1772 g_simple_async_result_complete_in_idle (data->simple);
1773 g_object_unref (data->simple);
1774 data->simple = NULL;
1776 if (data->timeout_source != NULL)
1778 g_source_destroy (data->timeout_source);
1779 data->timeout_source = NULL;
1781 if (data->cancellable_handler_id > 0)
1783 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1784 data->cancellable_handler_id = 0;
1789 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
1790 GUINT_TO_POINTER (data->serial)));
1793 send_message_data_unref (data);
1796 /* ---------------------------------------------------------------------------------------------------- */
1798 /* Can be called from any thread with lock held */
1800 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1801 GDBusMessage *reply)
1803 if (data->delivered)
1806 g_simple_async_result_set_op_res_gpointer (data->simple,
1807 g_object_ref (reply),
1810 send_message_with_reply_deliver (data, TRUE);
1816 /* ---------------------------------------------------------------------------------------------------- */
1818 /* Called from a user thread, lock is not held */
1820 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1822 SendMessageData *data = user_data;
1824 CONNECTION_LOCK (data->connection);
1825 if (data->delivered)
1828 g_simple_async_result_set_error (data->simple,
1830 G_IO_ERROR_CANCELLED,
1831 _("Operation was cancelled"));
1833 send_message_with_reply_deliver (data, TRUE);
1836 CONNECTION_UNLOCK (data->connection);
1840 /* Can be called from any thread with or without lock held */
1842 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1845 SendMessageData *data = user_data;
1846 GSource *idle_source;
1848 /* postpone cancellation to idle handler since we may be called directly
1849 * via g_cancellable_connect() (e.g. holding lock)
1851 idle_source = g_idle_source_new ();
1852 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1853 g_source_set_callback (idle_source,
1854 send_message_with_reply_cancelled_idle_cb,
1855 send_message_data_ref (data),
1856 (GDestroyNotify) send_message_data_unref);
1857 g_source_attach (idle_source, data->main_context);
1858 g_source_unref (idle_source);
1861 /* ---------------------------------------------------------------------------------------------------- */
1863 /* Called from a user thread, lock is not held */
1865 send_message_with_reply_timeout_cb (gpointer user_data)
1867 SendMessageData *data = user_data;
1869 CONNECTION_LOCK (data->connection);
1870 if (data->delivered)
1873 g_simple_async_result_set_error (data->simple,
1875 G_IO_ERROR_TIMED_OUT,
1876 _("Timeout was reached"));
1878 send_message_with_reply_deliver (data, TRUE);
1881 CONNECTION_UNLOCK (data->connection);
1886 /* ---------------------------------------------------------------------------------------------------- */
1888 /* Called from a user thread, connection's lock is held */
1890 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1891 GDBusMessage *message,
1892 GDBusSendMessageFlags flags,
1894 volatile guint32 *out_serial,
1895 GCancellable *cancellable,
1896 GAsyncReadyCallback callback,
1899 GSimpleAsyncResult *simple;
1900 SendMessageData *data;
1902 volatile guint32 serial;
1906 if (out_serial == NULL)
1907 out_serial = &serial;
1909 if (timeout_msec == -1)
1910 timeout_msec = 25 * 1000;
1912 simple = g_simple_async_result_new (G_OBJECT (connection),
1915 g_dbus_connection_send_message_with_reply);
1917 if (g_cancellable_is_cancelled (cancellable))
1919 g_simple_async_result_set_error (simple,
1921 G_IO_ERROR_CANCELLED,
1922 _("Operation was cancelled"));
1923 g_simple_async_result_complete_in_idle (simple);
1924 g_object_unref (simple);
1929 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1931 g_simple_async_result_take_error (simple, error);
1932 g_simple_async_result_complete_in_idle (simple);
1933 g_object_unref (simple);
1937 data = g_new0 (SendMessageData, 1);
1938 data->ref_count = 1;
1939 data->connection = g_object_ref (connection);
1940 data->simple = simple;
1941 data->serial = *out_serial;
1942 data->main_context = g_main_context_ref_thread_default ();
1944 if (cancellable != NULL)
1946 data->cancellable = g_object_ref (cancellable);
1947 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1948 G_CALLBACK (send_message_with_reply_cancelled_cb),
1949 send_message_data_ref (data),
1950 (GDestroyNotify) send_message_data_unref);
1951 g_object_set_data_full (G_OBJECT (simple),
1953 g_object_ref (cancellable),
1954 (GDestroyNotify) g_object_unref);
1957 if (timeout_msec != G_MAXINT)
1959 data->timeout_source = g_timeout_source_new (timeout_msec);
1960 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1961 g_source_set_callback (data->timeout_source,
1962 send_message_with_reply_timeout_cb,
1963 send_message_data_ref (data),
1964 (GDestroyNotify) send_message_data_unref);
1965 g_source_attach (data->timeout_source, data->main_context);
1966 g_source_unref (data->timeout_source);
1969 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
1970 GUINT_TO_POINTER (*out_serial),
1978 * g_dbus_connection_send_message_with_reply:
1979 * @connection: A #GDBusConnection.
1980 * @message: A #GDBusMessage.
1981 * @flags: Flags affecting how the message is sent.
1982 * @timeout_msec: The timeout in milliseconds, -1 to use the default
1983 * timeout or %G_MAXINT for no timeout.
1984 * @out_serial: (out) (allow-none): Return location for serial number assigned
1985 * to @message when sending it or %NULL.
1986 * @cancellable: A #GCancellable or %NULL.
1987 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1988 * satisfied or %NULL if you don't care about the result.
1989 * @user_data: The data to pass to @callback.
1991 * Asynchronously sends @message to the peer represented by @connection.
1993 * Unless @flags contain the
1994 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1995 * will be assigned by @connection and set on @message via
1996 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1997 * serial number used will be written to this location prior to
1998 * submitting the message to the underlying transport.
2000 * If @connection is closed then the operation will fail with
2001 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2002 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2003 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2005 * This is an asynchronous method. When the operation is finished, @callback will be invoked
2006 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
2007 * of the thread you are calling this method from. You can then call
2008 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
2009 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
2011 * Note that @message must be unlocked, unless @flags contain the
2012 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2014 * See <xref linkend="gdbus-server"/> and <xref
2015 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2016 * low-level API to send and receive UNIX file descriptors.
2021 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
2022 GDBusMessage *message,
2023 GDBusSendMessageFlags flags,
2025 volatile guint32 *out_serial,
2026 GCancellable *cancellable,
2027 GAsyncReadyCallback callback,
2030 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2031 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2032 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2033 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2035 CONNECTION_LOCK (connection);
2036 g_dbus_connection_send_message_with_reply_unlocked (connection,
2044 CONNECTION_UNLOCK (connection);
2048 * g_dbus_connection_send_message_with_reply_finish:
2049 * @connection: a #GDBusConnection
2050 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
2051 * @error: Return location for error or %NULL.
2053 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2055 * Note that @error is only set if a local in-process error
2056 * occurred. That is to say that the returned #GDBusMessage object may
2057 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2058 * g_dbus_message_to_gerror() to transcode this to a #GError.
2060 * See <xref linkend="gdbus-server"/> and <xref
2061 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2062 * low-level API to send and receive UNIX file descriptors.
2064 * Returns: (transfer full): A locked #GDBusMessage or %NULL if @error is set.
2069 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2073 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2074 GDBusMessage *reply;
2075 GCancellable *cancellable;
2077 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2078 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2082 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
2084 if (g_simple_async_result_propagate_error (simple, error))
2087 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
2088 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
2089 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
2091 g_object_unref (reply);
2093 g_set_error_literal (error,
2095 G_IO_ERROR_CANCELLED,
2096 _("Operation was cancelled"));
2102 /* ---------------------------------------------------------------------------------------------------- */
2107 GMainContext *context;
2109 } SendMessageSyncData;
2111 /* Called from a user thread, lock is not held */
2113 send_message_with_reply_sync_cb (GDBusConnection *connection,
2117 SendMessageSyncData *data = user_data;
2118 data->res = g_object_ref (res);
2119 g_main_loop_quit (data->loop);
2123 * g_dbus_connection_send_message_with_reply_sync:
2124 * @connection: A #GDBusConnection.
2125 * @message: A #GDBusMessage.
2126 * @flags: Flags affecting how the message is sent.
2127 * @timeout_msec: The timeout in milliseconds, -1 to use the default
2128 * timeout or %G_MAXINT for no timeout.
2129 * @out_serial: (out) (allow-none): Return location for serial number assigned
2130 * to @message when sending it or %NULL.
2131 * @cancellable: A #GCancellable or %NULL.
2132 * @error: Return location for error or %NULL.
2134 * Synchronously sends @message to the peer represented by @connection
2135 * and blocks the calling thread until a reply is received or the
2136 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2137 * for the asynchronous version of this method.
2139 * Unless @flags contain the
2140 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2141 * will be assigned by @connection and set on @message via
2142 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2143 * serial number used will be written to this location prior to
2144 * submitting the message to the underlying transport.
2146 * If @connection is closed then the operation will fail with
2147 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2148 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2149 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2151 * Note that @error is only set if a local in-process error
2152 * occurred. That is to say that the returned #GDBusMessage object may
2153 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2154 * g_dbus_message_to_gerror() to transcode this to a #GError.
2156 * See <xref linkend="gdbus-server"/> and <xref
2157 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2158 * low-level API to send and receive UNIX file descriptors.
2160 * Note that @message must be unlocked, unless @flags contain the
2161 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2163 * Returns: (transfer full): A locked #GDBusMessage that is the reply to @message or %NULL if @error is set.
2168 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2169 GDBusMessage *message,
2170 GDBusSendMessageFlags flags,
2172 volatile guint32 *out_serial,
2173 GCancellable *cancellable,
2176 SendMessageSyncData *data;
2177 GDBusMessage *reply;
2179 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2180 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2181 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2182 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2183 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2185 data = g_new0 (SendMessageSyncData, 1);
2186 data->context = g_main_context_new ();
2187 data->loop = g_main_loop_new (data->context, FALSE);
2189 g_main_context_push_thread_default (data->context);
2191 g_dbus_connection_send_message_with_reply (connection,
2197 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2199 g_main_loop_run (data->loop);
2200 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2204 g_main_context_pop_thread_default (data->context);
2206 g_main_context_unref (data->context);
2207 g_main_loop_unref (data->loop);
2208 g_object_unref (data->res);
2214 /* ---------------------------------------------------------------------------------------------------- */
2218 GDBusMessageFilterFunction func;
2225 GDBusMessageFilterFunction filter_function;
2227 GDestroyNotify user_data_free_func;
2230 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2232 on_worker_message_received (GDBusWorker *worker,
2233 GDBusMessage *message,
2236 GDBusConnection *connection;
2237 FilterCallback *filters;
2242 G_LOCK (message_bus_lock);
2243 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2246 G_UNLOCK (message_bus_lock);
2249 connection = G_DBUS_CONNECTION (user_data);
2250 g_object_ref (connection);
2251 G_UNLOCK (message_bus_lock);
2253 //g_debug ("in on_worker_message_received");
2255 g_object_ref (message);
2256 g_dbus_message_lock (message);
2258 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2260 /* First collect the set of callback functions */
2261 CONNECTION_LOCK (connection);
2262 num_filters = connection->filters->len;
2263 filters = g_new0 (FilterCallback, num_filters);
2264 for (n = 0; n < num_filters; n++)
2266 FilterData *data = connection->filters->pdata[n];
2267 filters[n].func = data->filter_function;
2268 filters[n].user_data = data->user_data;
2270 CONNECTION_UNLOCK (connection);
2272 /* then call the filters in order (without holding the lock) */
2273 for (n = 0; n < num_filters; n++)
2275 message = filters[n].func (connection,
2278 filters[n].user_data);
2279 if (message == NULL)
2281 g_dbus_message_lock (message);
2284 /* Standard dispatch unless the filter ate the message - no need to
2285 * do anything if the message was altered
2287 if (message != NULL)
2289 GDBusMessageType message_type;
2291 message_type = g_dbus_message_get_message_type (message);
2292 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2294 guint32 reply_serial;
2295 SendMessageData *send_message_data;
2297 reply_serial = g_dbus_message_get_reply_serial (message);
2298 CONNECTION_LOCK (connection);
2299 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2300 GUINT_TO_POINTER (reply_serial));
2301 if (send_message_data != NULL)
2303 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2304 send_message_data_deliver_reply_unlocked (send_message_data, message);
2308 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2310 CONNECTION_UNLOCK (connection);
2312 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2314 CONNECTION_LOCK (connection);
2315 distribute_signals (connection, message);
2316 CONNECTION_UNLOCK (connection);
2318 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2320 CONNECTION_LOCK (connection);
2321 distribute_method_call (connection, message);
2322 CONNECTION_UNLOCK (connection);
2326 if (message != NULL)
2327 g_object_unref (message);
2328 g_object_unref (connection);
2332 /* Called in GDBusWorker's thread, lock is not held */
2333 static GDBusMessage *
2334 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2335 GDBusMessage *message,
2338 GDBusConnection *connection;
2339 FilterCallback *filters;
2344 G_LOCK (message_bus_lock);
2345 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2348 G_UNLOCK (message_bus_lock);
2351 connection = G_DBUS_CONNECTION (user_data);
2352 g_object_ref (connection);
2353 G_UNLOCK (message_bus_lock);
2355 //g_debug ("in on_worker_message_about_to_be_sent");
2357 /* First collect the set of callback functions */
2358 CONNECTION_LOCK (connection);
2359 num_filters = connection->filters->len;
2360 filters = g_new0 (FilterCallback, num_filters);
2361 for (n = 0; n < num_filters; n++)
2363 FilterData *data = connection->filters->pdata[n];
2364 filters[n].func = data->filter_function;
2365 filters[n].user_data = data->user_data;
2367 CONNECTION_UNLOCK (connection);
2369 /* then call the filters in order (without holding the lock) */
2370 for (n = 0; n < num_filters; n++)
2372 g_dbus_message_lock (message);
2373 message = filters[n].func (connection,
2376 filters[n].user_data);
2377 if (message == NULL)
2381 g_object_unref (connection);
2387 /* called with connection lock held, in GDBusWorker thread */
2389 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2391 SendMessageData *data = value;
2393 if (data->delivered)
2396 g_simple_async_result_set_error (data->simple,
2399 _("The connection is closed"));
2401 /* Ask send_message_with_reply_deliver not to remove the element from the
2402 * hash table - we're in the middle of a foreach; that would be unsafe.
2403 * Instead, return TRUE from this function so that it gets removed safely.
2405 send_message_with_reply_deliver (data, FALSE);
2409 /* Called in GDBusWorker's thread - we must not block - without lock held */
2411 on_worker_closed (GDBusWorker *worker,
2412 gboolean remote_peer_vanished,
2416 GDBusConnection *connection;
2418 guint old_atomic_flags;
2420 G_LOCK (message_bus_lock);
2421 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2424 G_UNLOCK (message_bus_lock);
2427 connection = G_DBUS_CONNECTION (user_data);
2428 g_object_ref (connection);
2429 G_UNLOCK (message_bus_lock);
2431 //g_debug ("in on_worker_closed: %s", error->message);
2433 CONNECTION_LOCK (connection);
2434 /* Even though this is atomic, we do it inside the lock to avoid breaking
2435 * assumptions in remove_match_rule(). We'd need the lock in a moment
2436 * anyway, so, no loss.
2438 old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
2440 if (!(old_atomic_flags & FLAG_CLOSED))
2442 g_hash_table_foreach_remove (connection->map_method_serial_to_send_message_data, cancel_method_on_close, NULL);
2443 schedule_closed_unlocked (connection, remote_peer_vanished, error);
2445 CONNECTION_UNLOCK (connection);
2447 g_object_unref (connection);
2450 /* ---------------------------------------------------------------------------------------------------- */
2452 /* Determines the biggest set of capabilities we can support on this
2455 * Called with the init_lock held.
2457 static GDBusCapabilityFlags
2458 get_offered_capabilities_max (GDBusConnection *connection)
2460 GDBusCapabilityFlags ret;
2461 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2463 if (G_IS_UNIX_CONNECTION (connection->stream))
2464 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2469 /* Called in a user thread, lock is not held */
2471 initable_init (GInitable *initable,
2472 GCancellable *cancellable,
2475 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2478 /* This method needs to be idempotent to work with the singleton
2479 * pattern. See the docs for g_initable_init(). We implement this by
2482 * Unfortunately we can't use the main lock since the on_worker_*()
2483 * callbacks above needs the lock during initialization (for message
2484 * bus connections we do a synchronous Hello() call on the bus).
2486 g_mutex_lock (&connection->init_lock);
2490 /* Make this a no-op if we're already initialized (successfully or
2493 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
2495 ret = (connection->initialization_error == NULL);
2499 /* Because of init_lock, we can't get here twice in different threads */
2500 g_assert (connection->initialization_error == NULL);
2502 /* The user can pass multiple (but mutally exclusive) construct
2505 * - stream (of type GIOStream)
2506 * - address (of type gchar*)
2508 * At the end of the day we end up with a non-NULL GIOStream
2509 * object in connection->stream.
2511 if (connection->address != NULL)
2513 g_assert (connection->stream == NULL);
2515 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2516 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2518 g_set_error_literal (&connection->initialization_error,
2520 G_IO_ERROR_INVALID_ARGUMENT,
2521 _("Unsupported flags encountered when constructing a client-side connection"));
2525 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2526 NULL, /* TODO: out_guid */
2528 &connection->initialization_error);
2529 if (connection->stream == NULL)
2532 else if (connection->stream != NULL)
2538 g_assert_not_reached ();
2541 /* Authenticate the connection */
2542 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2544 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2545 g_assert (connection->guid != NULL);
2546 connection->auth = _g_dbus_auth_new (connection->stream);
2547 if (!_g_dbus_auth_run_server (connection->auth,
2548 connection->authentication_observer,
2550 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2551 get_offered_capabilities_max (connection),
2552 &connection->capabilities,
2553 &connection->credentials,
2555 &connection->initialization_error))
2558 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2560 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2561 g_assert (connection->guid == NULL);
2562 connection->auth = _g_dbus_auth_new (connection->stream);
2563 connection->guid = _g_dbus_auth_run_client (connection->auth,
2564 get_offered_capabilities_max (connection),
2565 &connection->capabilities,
2567 &connection->initialization_error);
2568 if (connection->guid == NULL)
2572 if (connection->authentication_observer != NULL)
2574 g_object_unref (connection->authentication_observer);
2575 connection->authentication_observer = NULL;
2578 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2580 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2583 /* We want all IO operations to be non-blocking since they happen in
2584 * the worker thread which is shared by _all_ connections.
2586 if (G_IS_SOCKET_CONNECTION (connection->stream))
2588 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2592 G_LOCK (message_bus_lock);
2593 if (alive_connections == NULL)
2594 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2595 g_hash_table_insert (alive_connections, connection, connection);
2596 G_UNLOCK (message_bus_lock);
2598 connection->worker = _g_dbus_worker_new (connection->stream,
2599 connection->capabilities,
2600 ((connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) != 0),
2601 on_worker_message_received,
2602 on_worker_message_about_to_be_sent,
2606 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2607 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2609 GVariant *hello_result;
2611 /* we could lift this restriction by adding code in gdbusprivate.c */
2612 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2614 g_set_error_literal (&connection->initialization_error,
2617 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2621 hello_result = g_dbus_connection_call_sync (connection,
2622 "org.freedesktop.DBus", /* name */
2623 "/org/freedesktop/DBus", /* path */
2624 "org.freedesktop.DBus", /* interface */
2626 NULL, /* parameters */
2627 G_VARIANT_TYPE ("(s)"),
2628 CALL_FLAGS_INITIALIZING,
2630 NULL, /* TODO: cancellable */
2631 &connection->initialization_error);
2632 if (hello_result == NULL)
2635 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2636 g_variant_unref (hello_result);
2637 //g_debug ("unique name is `%s'", connection->bus_unique_name);
2644 g_assert (connection->initialization_error != NULL);
2645 g_propagate_error (error, g_error_copy (connection->initialization_error));
2648 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
2649 g_mutex_unlock (&connection->init_lock);
2655 initable_iface_init (GInitableIface *initable_iface)
2657 initable_iface->init = initable_init;
2660 /* ---------------------------------------------------------------------------------------------------- */
2663 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2668 /* ---------------------------------------------------------------------------------------------------- */
2671 * g_dbus_connection_new:
2672 * @stream: A #GIOStream.
2673 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2674 * @flags: Flags describing how to make the connection.
2675 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2676 * @cancellable: A #GCancellable or %NULL.
2677 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2678 * @user_data: The data to pass to @callback.
2680 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2681 * with the end represented by @stream.
2683 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2684 * will be put into non-blocking mode.
2686 * The D-Bus connection will interact with @stream from a worker thread.
2687 * As a result, the caller should not interact with @stream after this
2688 * method has been called, except by calling g_object_unref() on it.
2690 * If @observer is not %NULL it may be used to control the
2691 * authentication process.
2693 * When the operation is finished, @callback will be invoked. You can
2694 * then call g_dbus_connection_new_finish() to get the result of the
2697 * This is a asynchronous failable constructor. See
2698 * g_dbus_connection_new_sync() for the synchronous
2704 g_dbus_connection_new (GIOStream *stream,
2706 GDBusConnectionFlags flags,
2707 GDBusAuthObserver *observer,
2708 GCancellable *cancellable,
2709 GAsyncReadyCallback callback,
2712 g_return_if_fail (G_IS_IO_STREAM (stream));
2713 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2721 "authentication-observer", observer,
2726 * g_dbus_connection_new_finish:
2727 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2728 * @error: Return location for error or %NULL.
2730 * Finishes an operation started with g_dbus_connection_new().
2732 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2737 g_dbus_connection_new_finish (GAsyncResult *res,
2741 GObject *source_object;
2743 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2744 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2746 source_object = g_async_result_get_source_object (res);
2747 g_assert (source_object != NULL);
2748 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2751 g_object_unref (source_object);
2753 return G_DBUS_CONNECTION (object);
2759 * g_dbus_connection_new_sync:
2760 * @stream: A #GIOStream.
2761 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2762 * @flags: Flags describing how to make the connection.
2763 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2764 * @cancellable: A #GCancellable or %NULL.
2765 * @error: Return location for error or %NULL.
2767 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2768 * with the end represented by @stream.
2770 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2771 * will be put into non-blocking mode.
2773 * The D-Bus connection will interact with @stream from a worker thread.
2774 * As a result, the caller should not interact with @stream after this
2775 * method has been called, except by calling g_object_unref() on it.
2777 * If @observer is not %NULL it may be used to control the
2778 * authentication process.
2780 * This is a synchronous failable constructor. See
2781 * g_dbus_connection_new() for the asynchronous version.
2783 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2788 g_dbus_connection_new_sync (GIOStream *stream,
2790 GDBusConnectionFlags flags,
2791 GDBusAuthObserver *observer,
2792 GCancellable *cancellable,
2795 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2796 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2797 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2803 "authentication-observer", observer,
2807 /* ---------------------------------------------------------------------------------------------------- */
2810 * g_dbus_connection_new_for_address:
2811 * @address: A D-Bus address.
2812 * @flags: Flags describing how to make the connection.
2813 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2814 * @cancellable: A #GCancellable or %NULL.
2815 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2816 * @user_data: The data to pass to @callback.
2818 * Asynchronously connects and sets up a D-Bus client connection for
2819 * exchanging D-Bus messages with an endpoint specified by @address
2820 * which must be in the D-Bus address format.
2822 * This constructor can only be used to initiate client-side
2823 * connections - use g_dbus_connection_new() if you need to act as the
2824 * server. In particular, @flags cannot contain the
2825 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2826 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2828 * When the operation is finished, @callback will be invoked. You can
2829 * then call g_dbus_connection_new_finish() to get the result of the
2832 * If @observer is not %NULL it may be used to control the
2833 * authentication process.
2835 * This is a asynchronous failable constructor. See
2836 * g_dbus_connection_new_for_address_sync() for the synchronous
2842 g_dbus_connection_new_for_address (const gchar *address,
2843 GDBusConnectionFlags flags,
2844 GDBusAuthObserver *observer,
2845 GCancellable *cancellable,
2846 GAsyncReadyCallback callback,
2849 g_return_if_fail (address != NULL);
2850 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2857 "authentication-observer", observer,
2862 * g_dbus_connection_new_for_address_finish:
2863 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2864 * @error: Return location for error or %NULL.
2866 * Finishes an operation started with g_dbus_connection_new_for_address().
2868 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2873 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2877 GObject *source_object;
2879 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2880 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2882 source_object = g_async_result_get_source_object (res);
2883 g_assert (source_object != NULL);
2884 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2887 g_object_unref (source_object);
2889 return G_DBUS_CONNECTION (object);
2895 * g_dbus_connection_new_for_address_sync:
2896 * @address: A D-Bus address.
2897 * @flags: Flags describing how to make the connection.
2898 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2899 * @cancellable: A #GCancellable or %NULL.
2900 * @error: Return location for error or %NULL.
2902 * Synchronously connects and sets up a D-Bus client connection for
2903 * exchanging D-Bus messages with an endpoint specified by @address
2904 * which must be in the D-Bus address format.
2906 * This constructor can only be used to initiate client-side
2907 * connections - use g_dbus_connection_new_sync() if you need to act
2908 * as the server. In particular, @flags cannot contain the
2909 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2910 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2912 * This is a synchronous failable constructor. See
2913 * g_dbus_connection_new_for_address() for the asynchronous version.
2915 * If @observer is not %NULL it may be used to control the
2916 * authentication process.
2918 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2923 g_dbus_connection_new_for_address_sync (const gchar *address,
2924 GDBusConnectionFlags flags,
2925 GDBusAuthObserver *observer,
2926 GCancellable *cancellable,
2929 g_return_val_if_fail (address != NULL, NULL);
2930 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2931 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2936 "authentication-observer", observer,
2940 /* ---------------------------------------------------------------------------------------------------- */
2943 * g_dbus_connection_set_exit_on_close:
2944 * @connection: A #GDBusConnection.
2945 * @exit_on_close: Whether the process should be terminated
2946 * when @connection is closed by the remote peer.
2948 * Sets whether the process should be terminated when @connection is
2949 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2952 * Note that this function should be used with care. Most modern UNIX
2953 * desktops tie the notion of a user session the session bus, and expect
2954 * all of a users applications to quit when their bus connection goes away.
2955 * If you are setting @exit_on_close to %FALSE for the shared session
2956 * bus connection, you should make sure that your application exits
2957 * when the user session ends.
2962 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2963 gboolean exit_on_close)
2965 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2968 g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
2970 g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
2975 * g_dbus_connection_get_exit_on_close:
2976 * @connection: A #GDBusConnection.
2978 * Gets whether the process is terminated when @connection is
2979 * closed by the remote peer. See
2980 * #GDBusConnection:exit-on-close for more details.
2982 * Returns: Whether the process is terminated when @connection is
2983 * closed by the remote peer.
2988 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2990 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2992 if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
2999 * g_dbus_connection_get_guid:
3000 * @connection: A #GDBusConnection.
3002 * The GUID of the peer performing the role of server when
3003 * authenticating. See #GDBusConnection:guid for more details.
3005 * Returns: The GUID. Do not free this string, it is owned by
3011 g_dbus_connection_get_guid (GDBusConnection *connection)
3013 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3014 return connection->guid;
3018 * g_dbus_connection_get_unique_name:
3019 * @connection: A #GDBusConnection.
3021 * Gets the unique name of @connection as assigned by the message
3022 * bus. This can also be used to figure out if @connection is a
3023 * message bus connection.
3025 * Returns: The unique name or %NULL if @connection is not a message
3026 * bus connection. Do not free this string, it is owned by
3032 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3034 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3036 /* do not use g_return_val_if_fail(), we want the memory barrier */
3037 if (!check_initialized (connection))
3040 return connection->bus_unique_name;
3044 * g_dbus_connection_get_peer_credentials:
3045 * @connection: A #GDBusConnection.
3047 * Gets the credentials of the authenticated peer. This will always
3048 * return %NULL unless @connection acted as a server
3049 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3050 * when set up and the client passed credentials as part of the
3051 * authentication process.
3053 * In a message bus setup, the message bus is always the server and
3054 * each application is a client. So this method will always return
3055 * %NULL for message bus clients.
3057 * Returns: (transfer none): A #GCredentials or %NULL if not available. Do not free
3058 * this object, it is owned by @connection.
3063 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3065 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3067 /* do not use g_return_val_if_fail(), we want the memory barrier */
3068 if (!check_initialized (connection))
3071 return connection->credentials;
3074 /* ---------------------------------------------------------------------------------------------------- */
3076 static guint _global_filter_id = 1;
3079 * g_dbus_connection_add_filter:
3080 * @connection: A #GDBusConnection.
3081 * @filter_function: A filter function.
3082 * @user_data: User data to pass to @filter_function.
3083 * @user_data_free_func: Function to free @user_data with when filter
3084 * is removed or %NULL.
3086 * Adds a message filter. Filters are handlers that are run on all
3087 * incoming and outgoing messages, prior to standard dispatch. Filters
3088 * are run in the order that they were added. The same handler can be
3089 * added as a filter more than once, in which case it will be run more
3090 * than once. Filters added during a filter callback won't be run on
3091 * the message being processed. Filter functions are allowed to modify
3092 * and even drop messages.
3094 * Note that filters are run in a dedicated message handling thread so
3095 * they can't block and, generally, can't do anything but signal a
3096 * worker thread. Also note that filters are rarely needed - use API
3097 * such as g_dbus_connection_send_message_with_reply(),
3098 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3100 * If a filter consumes an incoming message the message is not
3101 * dispatched anywhere else - not even the standard dispatch machinery
3102 * (that API such as g_dbus_connection_signal_subscribe() and
3103 * g_dbus_connection_send_message_with_reply() relies on) will see the
3104 * message. Similary, if a filter consumes an outgoing message, the
3105 * message will not be sent to the other peer.
3107 * Returns: A filter identifier that can be used with
3108 * g_dbus_connection_remove_filter().
3113 g_dbus_connection_add_filter (GDBusConnection *connection,
3114 GDBusMessageFilterFunction filter_function,
3116 GDestroyNotify user_data_free_func)
3120 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3121 g_return_val_if_fail (filter_function != NULL, 0);
3122 g_return_val_if_fail (check_initialized (connection), 0);
3124 CONNECTION_LOCK (connection);
3125 data = g_new0 (FilterData, 1);
3126 data->id = _global_filter_id++; /* TODO: overflow etc. */
3127 data->filter_function = filter_function;
3128 data->user_data = user_data;
3129 data->user_data_free_func = user_data_free_func;
3130 g_ptr_array_add (connection->filters, data);
3131 CONNECTION_UNLOCK (connection);
3136 /* only called from finalize(), removes all filters */
3138 purge_all_filters (GDBusConnection *connection)
3141 for (n = 0; n < connection->filters->len; n++)
3143 FilterData *data = connection->filters->pdata[n];
3144 if (data->user_data_free_func != NULL)
3145 data->user_data_free_func (data->user_data);
3151 * g_dbus_connection_remove_filter:
3152 * @connection: a #GDBusConnection
3153 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3160 g_dbus_connection_remove_filter (GDBusConnection *connection,
3164 FilterData *to_destroy;
3166 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3167 g_return_if_fail (check_initialized (connection));
3169 CONNECTION_LOCK (connection);
3171 for (n = 0; n < connection->filters->len; n++)
3173 FilterData *data = connection->filters->pdata[n];
3174 if (data->id == filter_id)
3176 g_ptr_array_remove_index (connection->filters, n);
3181 CONNECTION_UNLOCK (connection);
3183 /* do free without holding lock */
3184 if (to_destroy != NULL)
3186 if (to_destroy->user_data_free_func != NULL)
3187 to_destroy->user_data_free_func (to_destroy->user_data);
3188 g_free (to_destroy);
3192 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3196 /* ---------------------------------------------------------------------------------------------------- */
3202 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3203 gchar *interface_name;
3207 GArray *subscribers;
3212 GDBusSignalCallback callback;
3214 GDestroyNotify user_data_free_func;
3216 GMainContext *context;
3220 signal_data_free (SignalData *signal_data)
3222 g_free (signal_data->rule);
3223 g_free (signal_data->sender);
3224 g_free (signal_data->sender_unique_name);
3225 g_free (signal_data->interface_name);
3226 g_free (signal_data->member);
3227 g_free (signal_data->object_path);
3228 g_free (signal_data->arg0);
3229 g_array_free (signal_data->subscribers, TRUE);
3230 g_free (signal_data);
3234 args_to_rule (const gchar *sender,
3235 const gchar *interface_name,
3236 const gchar *member,
3237 const gchar *object_path,
3243 rule = g_string_new ("type='signal'");
3245 g_string_prepend_c (rule, '-');
3247 g_string_append_printf (rule, ",sender='%s'", sender);
3248 if (interface_name != NULL)
3249 g_string_append_printf (rule, ",interface='%s'", interface_name);
3251 g_string_append_printf (rule, ",member='%s'", member);
3252 if (object_path != NULL)
3253 g_string_append_printf (rule, ",path='%s'", object_path);
3255 g_string_append_printf (rule, ",arg0='%s'", arg0);
3257 return g_string_free (rule, FALSE);
3260 static guint _global_subscriber_id = 1;
3261 static guint _global_registration_id = 1;
3262 static guint _global_subtree_registration_id = 1;
3264 /* ---------------------------------------------------------------------------------------------------- */
3266 /* Called in a user thread, lock is held */
3268 add_match_rule (GDBusConnection *connection,
3269 const gchar *match_rule)
3272 GDBusMessage *message;
3274 if (match_rule[0] == '-')
3277 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3278 "/org/freedesktop/DBus", /* path */
3279 "org.freedesktop.DBus", /* interface */
3281 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3283 if (!g_dbus_connection_send_message_unlocked (connection,
3285 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3289 g_critical ("Error while sending AddMatch() message: %s", error->message);
3290 g_error_free (error);
3292 g_object_unref (message);
3295 /* ---------------------------------------------------------------------------------------------------- */
3297 /* Called in a user thread, lock is held */
3299 remove_match_rule (GDBusConnection *connection,
3300 const gchar *match_rule)
3303 GDBusMessage *message;
3305 if (match_rule[0] == '-')
3308 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3309 "/org/freedesktop/DBus", /* path */
3310 "org.freedesktop.DBus", /* interface */
3312 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3315 if (!g_dbus_connection_send_message_unlocked (connection,
3317 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3321 /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
3322 * critical; but we're holding the lock, and our caller checked whether
3323 * we were already closed, so we can't get that error.
3325 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3326 g_error_free (error);
3328 g_object_unref (message);
3331 /* ---------------------------------------------------------------------------------------------------- */
3334 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3336 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3337 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3338 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3339 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3340 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3343 /* ---------------------------------------------------------------------------------------------------- */
3346 * g_dbus_connection_signal_subscribe:
3347 * @connection: A #GDBusConnection.
3348 * @sender: (allow-none): Sender name to match on (unique or well-known name)
3349 * or %NULL to listen from all senders.
3350 * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3351 * match on all interfaces.
3352 * @member: (allow-none): D-Bus signal name to match on or %NULL to match on all signals.
3353 * @object_path: (allow-none): Object path to match on or %NULL to match on all object paths.
3354 * @arg0: (allow-none): Contents of first string argument to match on or %NULL
3355 * to match on all kinds of arguments.
3356 * @flags: Flags describing how to subscribe to the signal (currently unused).
3357 * @callback: Callback to invoke when there is a signal matching the requested data.
3358 * @user_data: User data to pass to @callback.
3359 * @user_data_free_func: (allow-none): Function to free @user_data with when
3360 * subscription is removed or %NULL.
3362 * Subscribes to signals on @connection and invokes @callback with a
3363 * whenever the signal is received. Note that @callback
3364 * will be invoked in the <link
3365 * linkend="g-main-context-push-thread-default">thread-default main
3366 * loop</link> of the thread you are calling this method from.
3368 * If @connection is not a message bus connection, @sender must be
3371 * If @sender is a well-known name note that @callback is invoked with
3372 * the unique name for the owner of @sender, not the well-known name
3373 * as one would expect. This is because the message bus rewrites the
3374 * name. As such, to avoid certain race conditions, users should be
3375 * tracking the name owner of the well-known name and use that when
3376 * processing the received signal.
3378 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
3383 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3384 const gchar *sender,
3385 const gchar *interface_name,
3386 const gchar *member,
3387 const gchar *object_path,
3389 GDBusSignalFlags flags,
3390 GDBusSignalCallback callback,
3392 GDestroyNotify user_data_free_func)
3395 SignalData *signal_data;
3396 SignalSubscriber subscriber;
3397 GPtrArray *signal_data_array;
3398 const gchar *sender_unique_name;
3400 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3401 * an OOM condition. We might want to change that but that would involve making
3402 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3403 * handle that. And there's really no sensible way of handling this short of retrying
3404 * to add the match rule... and then there's the little thing that, hey, maybe there's
3405 * a reason the bus in an OOM condition.
3407 * Doable, but not really sure it's worth it...
3410 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3411 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3412 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3413 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3414 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3415 g_return_val_if_fail (callback != NULL, 0);
3416 g_return_val_if_fail (check_initialized (connection), 0);
3418 CONNECTION_LOCK (connection);
3420 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3421 * with a '-' character to prefix the rule (which will otherwise be
3424 * This allows us to hash the rule and do our lifecycle tracking in
3425 * the usual way, but the '-' prevents the match rule from ever
3426 * actually being send to the bus (either for add or remove).
3428 rule = args_to_rule (sender, interface_name, member, object_path, arg0,
3429 (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE) != 0);
3431 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3432 sender_unique_name = sender;
3434 sender_unique_name = "";
3436 subscriber.callback = callback;
3437 subscriber.user_data = user_data;
3438 subscriber.user_data_free_func = user_data_free_func;
3439 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3440 subscriber.context = g_main_context_ref_thread_default ();
3442 /* see if we've already have this rule */
3443 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3444 if (signal_data != NULL)
3446 g_array_append_val (signal_data->subscribers, subscriber);
3451 signal_data = g_new0 (SignalData, 1);
3452 signal_data->rule = rule;
3453 signal_data->sender = g_strdup (sender);
3454 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3455 signal_data->interface_name = g_strdup (interface_name);
3456 signal_data->member = g_strdup (member);
3457 signal_data->object_path = g_strdup (object_path);
3458 signal_data->arg0 = g_strdup (arg0);
3459 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3460 g_array_append_val (signal_data->subscribers, subscriber);
3462 g_hash_table_insert (connection->map_rule_to_signal_data,
3466 /* Add the match rule to the bus...
3468 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3469 * always send such messages to us.
3471 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3473 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3474 add_match_rule (connection, signal_data->rule);
3477 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3478 signal_data->sender_unique_name);
3479 if (signal_data_array == NULL)
3481 signal_data_array = g_ptr_array_new ();
3482 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3483 g_strdup (signal_data->sender_unique_name),
3486 g_ptr_array_add (signal_data_array, signal_data);
3489 g_hash_table_insert (connection->map_id_to_signal_data,
3490 GUINT_TO_POINTER (subscriber.id),
3493 CONNECTION_UNLOCK (connection);
3495 return subscriber.id;
3498 /* ---------------------------------------------------------------------------------------------------- */
3500 /* called in any thread */
3501 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3503 unsubscribe_id_internal (GDBusConnection *connection,
3504 guint subscription_id,
3505 GArray *out_removed_subscribers)
3507 SignalData *signal_data;
3508 GPtrArray *signal_data_array;
3511 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3512 GUINT_TO_POINTER (subscription_id));
3513 if (signal_data == NULL)
3515 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3519 for (n = 0; n < signal_data->subscribers->len; n++)
3521 SignalSubscriber *subscriber;
3523 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3524 if (subscriber->id != subscription_id)
3527 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3528 GUINT_TO_POINTER (subscription_id)));
3529 g_array_append_val (out_removed_subscribers, *subscriber);
3530 g_array_remove_index (signal_data->subscribers, n);
3532 if (signal_data->subscribers->len == 0)
3534 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3536 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3537 signal_data->sender_unique_name);
3538 g_warn_if_fail (signal_data_array != NULL);
3539 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3541 if (signal_data_array->len == 0)
3543 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3544 signal_data->sender_unique_name));
3547 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3548 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
3549 !is_signal_data_for_name_lost_or_acquired (signal_data) &&
3550 !g_dbus_connection_is_closed (connection) &&
3551 !connection->finalizing)
3553 /* The check for g_dbus_connection_is_closed() means that
3554 * sending the RemoveMatch message can't fail with
3555 * G_IO_ERROR_CLOSED, because we're holding the lock,
3556 * so on_worker_closed() can't happen between the check we just
3557 * did, and releasing the lock later.
3559 remove_match_rule (connection, signal_data->rule);
3562 signal_data_free (signal_data);
3568 g_assert_not_reached ();
3575 * g_dbus_connection_signal_unsubscribe:
3576 * @connection: A #GDBusConnection.
3577 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
3579 * Unsubscribes from signals.
3584 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3585 guint subscription_id)
3587 GArray *subscribers;
3590 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3591 g_return_if_fail (check_initialized (connection));
3593 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3595 CONNECTION_LOCK (connection);
3596 unsubscribe_id_internal (connection,
3599 CONNECTION_UNLOCK (connection);
3602 g_assert (subscribers->len == 0 || subscribers->len == 1);
3604 /* call GDestroyNotify without lock held */
3605 for (n = 0; n < subscribers->len; n++)
3607 SignalSubscriber *subscriber;
3608 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3609 call_destroy_notify (subscriber->context,
3610 subscriber->user_data_free_func,
3611 subscriber->user_data);
3612 g_main_context_unref (subscriber->context);
3615 g_array_free (subscribers, TRUE);
3618 /* ---------------------------------------------------------------------------------------------------- */
3622 guint subscription_id;
3623 GDBusSignalCallback callback;
3625 GDBusMessage *message;
3626 GDBusConnection *connection;
3627 const gchar *sender;
3629 const gchar *interface;
3630 const gchar *member;
3633 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3637 emit_signal_instance_in_idle_cb (gpointer data)
3639 SignalInstance *signal_instance = data;
3640 GVariant *parameters;
3641 gboolean has_subscription;
3643 parameters = g_dbus_message_get_body (signal_instance->message);
3644 if (parameters == NULL)
3646 parameters = g_variant_new ("()");
3647 g_variant_ref_sink (parameters);
3651 g_variant_ref_sink (parameters);
3655 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3656 signal_instance->subscription_id,
3657 signal_instance->sender,
3658 signal_instance->path,
3659 signal_instance->interface,
3660 signal_instance->member,
3661 g_variant_print (parameters, TRUE));
3664 /* Careful here, don't do the callback if we no longer has the subscription */
3665 CONNECTION_LOCK (signal_instance->connection);
3666 has_subscription = FALSE;
3667 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3668 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3669 has_subscription = TRUE;
3670 CONNECTION_UNLOCK (signal_instance->connection);
3672 if (has_subscription)
3673 signal_instance->callback (signal_instance->connection,
3674 signal_instance->sender,
3675 signal_instance->path,
3676 signal_instance->interface,
3677 signal_instance->member,
3679 signal_instance->user_data);
3681 g_variant_unref (parameters);
3687 signal_instance_free (SignalInstance *signal_instance)
3689 g_object_unref (signal_instance->message);
3690 g_object_unref (signal_instance->connection);
3691 g_free (signal_instance);
3694 /* called in GDBusWorker thread WITH lock held */
3696 schedule_callbacks (GDBusConnection *connection,
3697 GPtrArray *signal_data_array,
3698 GDBusMessage *message,
3699 const gchar *sender)
3702 const gchar *interface;
3703 const gchar *member;
3712 interface = g_dbus_message_get_interface (message);
3713 member = g_dbus_message_get_member (message);
3714 path = g_dbus_message_get_path (message);
3715 arg0 = g_dbus_message_get_arg0 (message);
3718 g_print ("In schedule_callbacks:\n"
3720 " interface = `%s'\n"
3731 /* TODO: if this is slow, then we can change signal_data_array into
3732 * map_object_path_to_signal_data_array or something.
3734 for (n = 0; n < signal_data_array->len; n++)
3736 SignalData *signal_data = signal_data_array->pdata[n];
3738 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3741 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3744 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3747 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
3750 for (m = 0; m < signal_data->subscribers->len; m++)
3752 SignalSubscriber *subscriber;
3753 GSource *idle_source;
3754 SignalInstance *signal_instance;
3756 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3758 signal_instance = g_new0 (SignalInstance, 1);
3759 signal_instance->subscription_id = subscriber->id;
3760 signal_instance->callback = subscriber->callback;
3761 signal_instance->user_data = subscriber->user_data;
3762 signal_instance->message = g_object_ref (message);
3763 signal_instance->connection = g_object_ref (connection);
3764 signal_instance->sender = sender;
3765 signal_instance->path = path;
3766 signal_instance->interface = interface;
3767 signal_instance->member = member;
3769 idle_source = g_idle_source_new ();
3770 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3771 g_source_set_callback (idle_source,
3772 emit_signal_instance_in_idle_cb,
3774 (GDestroyNotify) signal_instance_free);
3775 g_source_attach (idle_source, subscriber->context);
3776 g_source_unref (idle_source);
3781 /* called in GDBusWorker thread with lock held */
3783 distribute_signals (GDBusConnection *connection,
3784 GDBusMessage *message)
3786 GPtrArray *signal_data_array;
3787 const gchar *sender;
3789 sender = g_dbus_message_get_sender (message);
3791 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3793 _g_dbus_debug_print_lock ();
3794 g_print ("========================================================================\n"
3795 "GDBus-debug:Signal:\n"
3796 " <<<< RECEIVED SIGNAL %s.%s\n"
3798 " sent by name %s\n",
3799 g_dbus_message_get_interface (message),
3800 g_dbus_message_get_member (message),
3801 g_dbus_message_get_path (message),
3802 sender != NULL ? sender : "(none)");
3803 _g_dbus_debug_print_unlock ();
3806 /* collect subscribers that match on sender */
3809 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3810 if (signal_data_array != NULL)
3811 schedule_callbacks (connection, signal_data_array, message, sender);
3814 /* collect subscribers not matching on sender */
3815 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3816 if (signal_data_array != NULL)
3817 schedule_callbacks (connection, signal_data_array, message, sender);
3820 /* ---------------------------------------------------------------------------------------------------- */
3822 /* only called from finalize(), removes all subscriptions */
3824 purge_all_signal_subscriptions (GDBusConnection *connection)
3826 GHashTableIter iter;
3829 GArray *subscribers;
3832 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3833 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3834 while (g_hash_table_iter_next (&iter, &key, NULL))
3836 guint subscription_id = GPOINTER_TO_UINT (key);
3837 g_array_append_val (ids, subscription_id);
3840 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3841 for (n = 0; n < ids->len; n++)
3843 guint subscription_id = g_array_index (ids, guint, n);
3844 unsubscribe_id_internal (connection,
3848 g_array_free (ids, TRUE);
3850 /* call GDestroyNotify without lock held */
3851 for (n = 0; n < subscribers->len; n++)
3853 SignalSubscriber *subscriber;
3854 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3855 call_destroy_notify (subscriber->context,
3856 subscriber->user_data_free_func,
3857 subscriber->user_data);
3858 g_main_context_unref (subscriber->context);
3861 g_array_free (subscribers, TRUE);
3864 /* ---------------------------------------------------------------------------------------------------- */
3866 static GDBusInterfaceVTable *
3867 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3869 /* Don't waste memory by copying padding - remember to update this
3870 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3872 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3876 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
3881 /* ---------------------------------------------------------------------------------------------------- */
3883 static GDBusSubtreeVTable *
3884 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
3886 /* Don't waste memory by copying padding - remember to update this
3887 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
3889 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3893 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
3898 /* ---------------------------------------------------------------------------------------------------- */
3900 struct ExportedObject
3903 GDBusConnection *connection;
3905 /* maps gchar* -> ExportedInterface* */
3906 GHashTable *map_if_name_to_ei;
3909 /* only called with lock held */
3911 exported_object_free (ExportedObject *eo)
3913 g_free (eo->object_path);
3914 g_hash_table_unref (eo->map_if_name_to_ei);
3923 gchar *interface_name;
3924 GDBusInterfaceVTable *vtable;
3925 GDBusInterfaceInfo *interface_info;
3927 GMainContext *context;
3929 GDestroyNotify user_data_free_func;
3930 } ExportedInterface;
3932 /* called with lock held */
3934 exported_interface_free (ExportedInterface *ei)
3936 g_dbus_interface_info_cache_release (ei->interface_info);
3937 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
3939 call_destroy_notify (ei->context,
3940 ei->user_data_free_func,
3943 g_main_context_unref (ei->context);
3945 g_free (ei->interface_name);
3946 _g_dbus_interface_vtable_free (ei->vtable);
3950 /* ---------------------------------------------------------------------------------------------------- */
3952 /* Convenience function to check if @registration_id (if not zero) or
3953 * @subtree_registration_id (if not zero) has been unregistered. If
3954 * so, returns %TRUE.
3956 * May be called by any thread. Caller must *not* hold lock.
3959 has_object_been_unregistered (GDBusConnection *connection,
3960 guint registration_id,
3961 guint subtree_registration_id)
3965 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3969 CONNECTION_LOCK (connection);
3970 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
3971 GUINT_TO_POINTER (registration_id)) == NULL)
3975 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
3976 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
3980 CONNECTION_UNLOCK (connection);
3985 /* ---------------------------------------------------------------------------------------------------- */
3989 GDBusConnection *connection;
3990 GDBusMessage *message;
3992 const gchar *property_name;
3993 const GDBusInterfaceVTable *vtable;
3994 GDBusInterfaceInfo *interface_info;
3995 const GDBusPropertyInfo *property_info;
3996 guint registration_id;
3997 guint subtree_registration_id;
4001 property_data_free (PropertyData *data)
4003 g_object_unref (data->connection);
4004 g_object_unref (data->message);
4008 /* called in thread where object was registered - no locks held */
4010 invoke_get_property_in_idle_cb (gpointer _data)
4012 PropertyData *data = _data;
4015 GDBusMessage *reply;
4017 if (has_object_been_unregistered (data->connection,
4018 data->registration_id,
4019 data->subtree_registration_id))
4021 reply = g_dbus_message_new_method_error (data->message,
4022 "org.freedesktop.DBus.Error.UnknownMethod",
4023 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
4024 g_dbus_message_get_path (data->message));
4025 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4026 g_object_unref (reply);
4031 value = data->vtable->get_property (data->connection,
4032 g_dbus_message_get_sender (data->message),
4033 g_dbus_message_get_path (data->message),
4034 data->interface_info->name,
4035 data->property_name,
4042 g_assert_no_error (error);
4044 g_variant_take_ref (value);
4045 reply = g_dbus_message_new_method_reply (data->message);
4046 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4047 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4048 g_variant_unref (value);
4049 g_object_unref (reply);
4053 gchar *dbus_error_name;
4054 g_assert (error != NULL);
4055 dbus_error_name = g_dbus_error_encode_gerror (error);
4056 reply = g_dbus_message_new_method_error_literal (data->message,
4059 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4060 g_free (dbus_error_name);
4061 g_error_free (error);
4062 g_object_unref (reply);
4069 /* called in thread where object was registered - no locks held */
4071 invoke_set_property_in_idle_cb (gpointer _data)
4073 PropertyData *data = _data;
4075 GDBusMessage *reply;
4081 g_variant_get (g_dbus_message_get_body (data->message),
4087 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4088 * of the given value is wrong
4090 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
4092 reply = g_dbus_message_new_method_error (data->message,
4093 "org.freedesktop.DBus.Error.InvalidArgs",
4094 _("Error setting property `%s': Expected type `%s' but got `%s'"),
4095 data->property_info->name,
4096 data->property_info->signature,
4097 g_variant_get_type_string (value));
4101 if (!data->vtable->set_property (data->connection,
4102 g_dbus_message_get_sender (data->message),
4103 g_dbus_message_get_path (data->message),
4104 data->interface_info->name,
4105 data->property_name,
4110 gchar *dbus_error_name;
4111 g_assert (error != NULL);
4112 dbus_error_name = g_dbus_error_encode_gerror (error);
4113 reply = g_dbus_message_new_method_error_literal (data->message,
4116 g_free (dbus_error_name);
4117 g_error_free (error);
4121 reply = g_dbus_message_new_method_reply (data->message);
4125 g_assert (reply != NULL);
4126 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4127 g_object_unref (reply);
4128 g_variant_unref (value);
4133 /* called in any thread with connection's lock held */
4135 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4136 GDBusMessage *message,
4137 guint registration_id,
4138 guint subtree_registration_id,
4140 GDBusInterfaceInfo *interface_info,
4141 const GDBusInterfaceVTable *vtable,
4142 GMainContext *main_context,
4146 const char *interface_name;
4147 const char *property_name;
4148 const GDBusPropertyInfo *property_info;
4149 GSource *idle_source;
4150 PropertyData *property_data;
4151 GDBusMessage *reply;
4156 g_variant_get (g_dbus_message_get_body (message),
4161 g_variant_get (g_dbus_message_get_body (message),
4170 if (vtable == NULL || vtable->get_property == NULL)
4175 if (vtable == NULL || vtable->set_property == NULL)
4179 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4181 property_info = NULL;
4183 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4184 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4185 if (property_info == NULL)
4187 reply = g_dbus_message_new_method_error (message,
4188 "org.freedesktop.DBus.Error.InvalidArgs",
4189 _("No such property `%s'"),
4191 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4192 g_object_unref (reply);
4197 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4199 reply = g_dbus_message_new_method_error (message,
4200 "org.freedesktop.DBus.Error.InvalidArgs",
4201 _("Property `%s' is not readable"),
4203 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4204 g_object_unref (reply);
4208 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4210 reply = g_dbus_message_new_method_error (message,
4211 "org.freedesktop.DBus.Error.InvalidArgs",
4212 _("Property `%s' is not writable"),
4214 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4215 g_object_unref (reply);
4220 /* ok, got the property info - call user code in an idle handler */
4221 property_data = g_new0 (PropertyData, 1);
4222 property_data->connection = g_object_ref (connection);
4223 property_data->message = g_object_ref (message);
4224 property_data->user_data = user_data;
4225 property_data->property_name = property_name;
4226 property_data->vtable = vtable;
4227 property_data->interface_info = interface_info;
4228 property_data->property_info = property_info;
4229 property_data->registration_id = registration_id;
4230 property_data->subtree_registration_id = subtree_registration_id;
4232 idle_source = g_idle_source_new ();
4233 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4234 g_source_set_callback (idle_source,
4235 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4237 (GDestroyNotify) property_data_free);
4238 g_source_attach (idle_source, main_context);
4239 g_source_unref (idle_source);
4247 /* called in GDBusWorker thread with connection's lock held */
4249 handle_getset_property (GDBusConnection *connection,
4251 GDBusMessage *message,
4254 ExportedInterface *ei;
4256 const char *interface_name;
4257 const char *property_name;
4262 g_variant_get (g_dbus_message_get_body (message),
4267 g_variant_get (g_dbus_message_get_body (message),
4273 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4274 * no such interface registered
4276 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4279 GDBusMessage *reply;
4280 reply = g_dbus_message_new_method_error (message,
4281 "org.freedesktop.DBus.Error.InvalidArgs",
4282 _("No such interface `%s'"),
4284 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4285 g_object_unref (reply);
4290 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4303 /* ---------------------------------------------------------------------------------------------------- */
4307 GDBusConnection *connection;
4308 GDBusMessage *message;
4310 const GDBusInterfaceVTable *vtable;
4311 GDBusInterfaceInfo *interface_info;
4312 guint registration_id;
4313 guint subtree_registration_id;
4314 } PropertyGetAllData;
4317 property_get_all_data_free (PropertyData *data)
4319 g_object_unref (data->connection);
4320 g_object_unref (data->message);
4324 /* called in thread where object was registered - no locks held */
4326 invoke_get_all_properties_in_idle_cb (gpointer _data)
4328 PropertyGetAllData *data = _data;
4329 GVariantBuilder builder;
4330 GDBusMessage *reply;
4333 if (has_object_been_unregistered (data->connection,
4334 data->registration_id,
4335 data->subtree_registration_id))
4337 reply = g_dbus_message_new_method_error (data->message,
4338 "org.freedesktop.DBus.Error.UnknownMethod",
4339 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
4340 g_dbus_message_get_path (data->message));
4341 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4342 g_object_unref (reply);
4346 /* TODO: Right now we never fail this call - we just omit values if
4347 * a get_property() call is failing.
4349 * We could fail the whole call if just a single get_property() call
4350 * returns an error. We need clarification in the D-Bus spec about this.
4352 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4353 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4354 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4356 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4359 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4362 value = data->vtable->get_property (data->connection,
4363 g_dbus_message_get_sender (data->message),
4364 g_dbus_message_get_path (data->message),
4365 data->interface_info->name,
4366 property_info->name,
4373 g_variant_take_ref (value);
4374 g_variant_builder_add (&builder,
4376 property_info->name,
4378 g_variant_unref (value);
4380 g_variant_builder_close (&builder);
4382 reply = g_dbus_message_new_method_reply (data->message);
4383 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4384 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4385 g_object_unref (reply);
4391 /* called in any thread with connection's lock held */
4393 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4394 GDBusMessage *message,
4395 guint registration_id,
4396 guint subtree_registration_id,
4397 GDBusInterfaceInfo *interface_info,
4398 const GDBusInterfaceVTable *vtable,
4399 GMainContext *main_context,
4403 const char *interface_name;
4404 GSource *idle_source;
4405 PropertyGetAllData *property_get_all_data;
4409 g_variant_get (g_dbus_message_get_body (message),
4413 if (vtable == NULL || vtable->get_property == NULL)
4416 /* ok, got the property info - call user in an idle handler */
4417 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4418 property_get_all_data->connection = g_object_ref (connection);
4419 property_get_all_data->message = g_object_ref (message);
4420 property_get_all_data->user_data = user_data;
4421 property_get_all_data->vtable = vtable;
4422 property_get_all_data->interface_info = interface_info;
4423 property_get_all_data->registration_id = registration_id;
4424 property_get_all_data->subtree_registration_id = subtree_registration_id;
4426 idle_source = g_idle_source_new ();
4427 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4428 g_source_set_callback (idle_source,
4429 invoke_get_all_properties_in_idle_cb,
4430 property_get_all_data,
4431 (GDestroyNotify) property_get_all_data_free);
4432 g_source_attach (idle_source, main_context);
4433 g_source_unref (idle_source);
4441 /* called in GDBusWorker thread with connection's lock held */
4443 handle_get_all_properties (GDBusConnection *connection,
4445 GDBusMessage *message)
4447 ExportedInterface *ei;
4449 const char *interface_name;
4453 g_variant_get (g_dbus_message_get_body (message),
4457 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4458 * no such interface registered
4460 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4463 GDBusMessage *reply;
4464 reply = g_dbus_message_new_method_error (message,
4465 "org.freedesktop.DBus.Error.InvalidArgs",
4466 _("No such interface"),
4468 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4469 g_object_unref (reply);
4474 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4486 /* ---------------------------------------------------------------------------------------------------- */
4488 static const gchar introspect_header[] =
4489 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4490 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4491 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4494 static const gchar introspect_tail[] =
4497 static const gchar introspect_properties_interface[] =
4498 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4499 " <method name=\"Get\">\n"
4500 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4501 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4502 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4504 " <method name=\"GetAll\">\n"
4505 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4506 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4508 " <method name=\"Set\">\n"
4509 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4510 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4511 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4513 " <signal name=\"PropertiesChanged\">\n"
4514 " <arg type=\"s\" name=\"interface_name\"/>\n"
4515 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4516 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4520 static const gchar introspect_introspectable_interface[] =
4521 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4522 " <method name=\"Introspect\">\n"
4523 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4526 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4527 " <method name=\"Ping\"/>\n"
4528 " <method name=\"GetMachineId\">\n"
4529 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4534 introspect_append_header (GString *s)
4536 g_string_append (s, introspect_header);
4540 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4542 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4548 begin = object_path + path_len;
4549 end = strchr (begin, '/');
4551 s = g_strndup (begin, end - begin);
4553 s = g_strdup (begin);
4555 if (g_hash_table_lookup (set, s) == NULL)
4556 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
4562 /* TODO: we want a nicer public interface for this */
4563 /* called in any thread with connection's lock held */
4565 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4570 GHashTableIter hash_iter;
4571 const gchar *object_path;
4577 CONNECTION_ENSURE_LOCK (connection);
4579 path_len = strlen (path);
4583 set = g_hash_table_new (g_str_hash, g_str_equal);
4585 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4586 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4587 maybe_add_path (path, path_len, object_path, set);
4589 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4590 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4591 maybe_add_path (path, path_len, object_path, set);
4593 p = g_ptr_array_new ();
4594 keys = g_hash_table_get_keys (set);
4595 for (l = keys; l != NULL; l = l->next)
4596 g_ptr_array_add (p, l->data);
4597 g_hash_table_unref (set);
4600 g_ptr_array_add (p, NULL);
4601 ret = (gchar **) g_ptr_array_free (p, FALSE);
4605 /* called in any thread with connection's lock not held */
4607 g_dbus_connection_list_registered (GDBusConnection *connection,
4611 CONNECTION_LOCK (connection);
4612 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4613 CONNECTION_UNLOCK (connection);
4617 /* called in GDBusWorker thread with connection's lock held */
4619 handle_introspect (GDBusConnection *connection,
4621 GDBusMessage *message)
4625 GDBusMessage *reply;
4626 GHashTableIter hash_iter;
4627 ExportedInterface *ei;
4630 /* first the header with the standard interfaces */
4631 s = g_string_sized_new (sizeof (introspect_header) +
4632 sizeof (introspect_properties_interface) +
4633 sizeof (introspect_introspectable_interface) +
4634 sizeof (introspect_tail));
4635 introspect_append_header (s);
4636 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4637 "org.freedesktop.DBus.Properties"))
4638 g_string_append (s, introspect_properties_interface);
4640 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4641 "org.freedesktop.DBus.Introspectable"))
4642 g_string_append (s, introspect_introspectable_interface);
4644 /* then include the registered interfaces */
4645 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4646 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4647 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4649 /* finally include nodes registered below us */
4650 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4651 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4652 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4653 g_strfreev (registered);
4654 g_string_append (s, introspect_tail);
4656 reply = g_dbus_message_new_method_reply (message);
4657 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4658 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4659 g_object_unref (reply);
4660 g_string_free (s, TRUE);
4665 /* called in thread where object was registered - no locks held */
4667 call_in_idle_cb (gpointer user_data)
4669 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4670 GDBusInterfaceVTable *vtable;
4671 guint registration_id;
4672 guint subtree_registration_id;
4674 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4675 g_assert (vtable != NULL && vtable->method_call != NULL);
4677 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4678 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4680 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4682 subtree_registration_id))
4684 GDBusMessage *reply;
4685 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4686 "org.freedesktop.DBus.Error.UnknownMethod",
4687 _("No such interface `%s' on object at path %s"),
4688 g_dbus_method_invocation_get_interface_name (invocation),
4689 g_dbus_method_invocation_get_object_path (invocation));
4690 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4691 g_object_unref (reply);
4695 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4696 g_dbus_method_invocation_get_sender (invocation),
4697 g_dbus_method_invocation_get_object_path (invocation),
4698 g_dbus_method_invocation_get_interface_name (invocation),
4699 g_dbus_method_invocation_get_method_name (invocation),
4700 g_dbus_method_invocation_get_parameters (invocation),
4701 g_object_ref (invocation),
4702 g_dbus_method_invocation_get_user_data (invocation));
4708 /* called in GDBusWorker thread with connection's lock held */
4710 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4711 GDBusMessage *message,
4712 guint registration_id,
4713 guint subtree_registration_id,
4714 GDBusInterfaceInfo *interface_info,
4715 const GDBusInterfaceVTable *vtable,
4716 GMainContext *main_context,
4719 GDBusMethodInvocation *invocation;
4720 const GDBusMethodInfo *method_info;
4721 GDBusMessage *reply;
4722 GVariant *parameters;
4723 GSource *idle_source;
4725 GVariantType *in_type;
4729 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4730 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4732 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4733 * error to the caller
4735 if (method_info == NULL)
4737 reply = g_dbus_message_new_method_error (message,
4738 "org.freedesktop.DBus.Error.UnknownMethod",
4739 _("No such method `%s'"),
4740 g_dbus_message_get_member (message));
4741 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4742 g_object_unref (reply);
4747 parameters = g_dbus_message_get_body (message);
4748 if (parameters == NULL)
4750 parameters = g_variant_new ("()");
4751 g_variant_ref_sink (parameters);
4755 g_variant_ref (parameters);
4758 /* Check that the incoming args are of the right type - if they are not, return
4759 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4761 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4762 if (!g_variant_is_of_type (parameters, in_type))
4766 type_string = g_variant_type_dup_string (in_type);
4768 reply = g_dbus_message_new_method_error (message,
4769 "org.freedesktop.DBus.Error.InvalidArgs",
4770 _("Type of message, `%s', does not match expected type `%s'"),
4771 g_variant_get_type_string (parameters),
4773 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4774 g_variant_type_free (in_type);
4775 g_variant_unref (parameters);
4776 g_object_unref (reply);
4777 g_free (type_string);
4781 g_variant_type_free (in_type);
4783 /* schedule the call in idle */
4784 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4785 g_dbus_message_get_path (message),
4786 g_dbus_message_get_interface (message),
4787 g_dbus_message_get_member (message),
4793 g_variant_unref (parameters);
4795 /* TODO: would be nicer with a real MethodData like we already
4796 * have PropertyData and PropertyGetAllData... */
4797 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4798 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4799 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4801 idle_source = g_idle_source_new ();
4802 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4803 g_source_set_callback (idle_source,
4807 g_source_attach (idle_source, main_context);
4808 g_source_unref (idle_source);
4816 /* ---------------------------------------------------------------------------------------------------- */
4818 /* called in GDBusWorker thread with connection's lock held */
4820 obj_message_func (GDBusConnection *connection,
4822 GDBusMessage *message)
4824 const gchar *interface_name;
4825 const gchar *member;
4826 const gchar *signature;
4831 interface_name = g_dbus_message_get_interface (message);
4832 member = g_dbus_message_get_member (message);
4833 signature = g_dbus_message_get_signature (message);
4835 /* see if we have an interface for handling this call */
4836 if (interface_name != NULL)
4838 ExportedInterface *ei;
4839 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4842 /* we do - invoke the handler in idle in the right thread */
4844 /* handle no vtable or handler being present */
4845 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
4848 handled = validate_and_maybe_schedule_method_call (connection,
4860 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4861 g_strcmp0 (member, "Introspect") == 0 &&
4862 g_strcmp0 (signature, "") == 0)
4864 handled = handle_introspect (connection, eo, message);
4867 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4868 g_strcmp0 (member, "Get") == 0 &&
4869 g_strcmp0 (signature, "ss") == 0)
4871 handled = handle_getset_property (connection, eo, message, TRUE);
4874 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4875 g_strcmp0 (member, "Set") == 0 &&
4876 g_strcmp0 (signature, "ssv") == 0)
4878 handled = handle_getset_property (connection, eo, message, FALSE);
4881 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4882 g_strcmp0 (member, "GetAll") == 0 &&
4883 g_strcmp0 (signature, "s") == 0)
4885 handled = handle_get_all_properties (connection, eo, message);
4894 * g_dbus_connection_register_object:
4895 * @connection: A #GDBusConnection.
4896 * @object_path: The object path to register at.
4897 * @interface_info: Introspection data for the interface.
4898 * @vtable: (allow-none): A #GDBusInterfaceVTable to call into or %NULL.
4899 * @user_data: (allow-none): Data to pass to functions in @vtable.
4900 * @user_data_free_func: Function to call when the object path is unregistered.
4901 * @error: Return location for error or %NULL.
4903 * Registers callbacks for exported objects at @object_path with the
4904 * D-Bus interface that is described in @interface_info.
4906 * Calls to functions in @vtable (and @user_data_free_func) will
4907 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
4908 * loop</link> of the thread you are calling this method from.
4910 * Note that all #GVariant values passed to functions in @vtable will match
4911 * the signature given in @interface_info - if a remote caller passes
4912 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
4913 * is returned to the remote caller.
4915 * Additionally, if the remote caller attempts to invoke methods or
4916 * access properties not mentioned in @interface_info the
4917 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
4918 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
4919 * are returned to the caller.
4921 * It is considered a programming error if the
4922 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
4923 * #GVariant of incorrect type.
4925 * If an existing callback is already registered at @object_path and
4926 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
4928 * GDBus automatically implements the standard D-Bus interfaces
4929 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
4930 * and org.freedesktop.Peer, so you don't have to implement those for
4931 * the objects you export. You <emphasis>can</emphasis> implement
4932 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
4933 * and setting of properties asynchronously.
4935 * Note that the reference count on @interface_info will be
4936 * incremented by 1 (unless allocated statically, e.g. if the
4937 * reference count is -1, see g_dbus_interface_info_ref()) for as long
4938 * as the object is exported. Also note that @vtable will be copied.
4940 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
4942 * Returns: 0 if @error is set, otherwise a registration id (never 0)
4943 * that can be used with g_dbus_connection_unregister_object() .
4948 g_dbus_connection_register_object (GDBusConnection *connection,
4949 const gchar *object_path,
4950 GDBusInterfaceInfo *interface_info,
4951 const GDBusInterfaceVTable *vtable,
4953 GDestroyNotify user_data_free_func,
4957 ExportedInterface *ei;
4960 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4961 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4962 g_return_val_if_fail (interface_info != NULL, 0);
4963 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
4964 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4965 g_return_val_if_fail (check_initialized (connection), 0);
4969 CONNECTION_LOCK (connection);
4971 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
4974 eo = g_new0 (ExportedObject, 1);
4975 eo->object_path = g_strdup (object_path);
4976 eo->connection = connection;
4977 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
4980 (GDestroyNotify) exported_interface_free);
4981 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
4984 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
4990 _("An object is already exported for the interface %s at %s"),
4991 interface_info->name,
4996 ei = g_new0 (ExportedInterface, 1);
4997 ei->id = _global_registration_id++; /* TODO: overflow etc. */
4999 ei->user_data = user_data;
5000 ei->user_data_free_func = user_data_free_func;
5001 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
5002 ei->interface_info = g_dbus_interface_info_ref (interface_info);
5003 g_dbus_interface_info_cache_build (ei->interface_info);
5004 ei->interface_name = g_strdup (interface_info->name);
5005 ei->context = g_main_context_ref_thread_default ();
5007 g_hash_table_insert (eo->map_if_name_to_ei,
5008 (gpointer) ei->interface_name,
5010 g_hash_table_insert (connection->map_id_to_ei,
5011 GUINT_TO_POINTER (ei->id),
5017 CONNECTION_UNLOCK (connection);
5023 * g_dbus_connection_unregister_object:
5024 * @connection: A #GDBusConnection.
5025 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
5027 * Unregisters an object.
5029 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
5034 g_dbus_connection_unregister_object (GDBusConnection *connection,
5035 guint registration_id)
5037 ExportedInterface *ei;
5041 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5042 g_return_val_if_fail (check_initialized (connection), FALSE);
5046 CONNECTION_LOCK (connection);
5048 ei = g_hash_table_lookup (connection->map_id_to_ei,
5049 GUINT_TO_POINTER (registration_id));
5055 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5056 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5057 /* unregister object path if we have no more exported interfaces */
5058 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5059 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5065 CONNECTION_UNLOCK (connection);
5070 /* ---------------------------------------------------------------------------------------------------- */
5073 * g_dbus_connection_emit_signal:
5074 * @connection: A #GDBusConnection.
5075 * @destination_bus_name: (allow-none): The unique bus name for the destination
5076 * for the signal or %NULL to emit to all listeners.
5077 * @object_path: Path of remote object.
5078 * @interface_name: D-Bus interface to emit a signal on.
5079 * @signal_name: The name of the signal to emit.
5080 * @parameters: (allow-none): A #GVariant tuple with parameters for the signal
5081 * or %NULL if not passing parameters.
5082 * @error: Return location for error or %NULL.
5086 * If the parameters GVariant is floating, it is consumed.
5088 * This can only fail if @parameters is not compatible with the D-Bus protocol.
5090 * Returns: %TRUE unless @error is set.
5095 g_dbus_connection_emit_signal (GDBusConnection *connection,
5096 const gchar *destination_bus_name,
5097 const gchar *object_path,
5098 const gchar *interface_name,
5099 const gchar *signal_name,
5100 GVariant *parameters,
5103 GDBusMessage *message;
5109 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5110 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5111 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5112 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5113 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5114 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5115 g_return_val_if_fail (check_initialized (connection), FALSE);
5117 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5119 _g_dbus_debug_print_lock ();
5120 g_print ("========================================================================\n"
5121 "GDBus-debug:Emission:\n"
5122 " >>>> SIGNAL EMISSION %s.%s()\n"
5124 " destination %s\n",
5125 interface_name, signal_name,
5127 destination_bus_name != NULL ? destination_bus_name : "(none)");
5128 _g_dbus_debug_print_unlock ();
5131 message = g_dbus_message_new_signal (object_path,
5135 if (destination_bus_name != NULL)
5136 g_dbus_message_set_header (message,
5137 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5138 g_variant_new_string (destination_bus_name));
5140 if (parameters != NULL)
5141 g_dbus_message_set_body (message, parameters);
5143 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5144 g_object_unref (message);
5150 add_call_flags (GDBusMessage *message,
5151 GDBusCallFlags flags)
5153 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5154 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
5158 decode_method_reply (GDBusMessage *reply,
5159 const gchar *method_name,
5160 const GVariantType *reply_type,
5161 GUnixFDList **out_fd_list,
5167 switch (g_dbus_message_get_message_type (reply))
5169 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5170 result = g_dbus_message_get_body (reply);
5173 result = g_variant_new ("()");
5174 g_variant_ref_sink (result);
5178 g_variant_ref (result);
5181 if (!g_variant_is_of_type (result, reply_type))
5183 gchar *type_string = g_variant_type_dup_string (reply_type);
5187 G_IO_ERROR_INVALID_ARGUMENT,
5188 _("Method `%s' returned type `%s', but expected `%s'"),
5189 method_name, g_variant_get_type_string (result), type_string);
5191 g_variant_unref (result);
5192 g_free (type_string);
5199 if (out_fd_list != NULL)
5201 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5202 if (*out_fd_list != NULL)
5203 g_object_ref (*out_fd_list);
5209 case G_DBUS_MESSAGE_TYPE_ERROR:
5210 g_dbus_message_to_gerror (reply, error);
5214 g_assert_not_reached ();
5224 GSimpleAsyncResult *simple;
5225 GVariantType *reply_type;
5226 gchar *method_name; /* for error message */
5230 GUnixFDList *fd_list;
5234 call_state_free (CallState *state)
5236 g_variant_type_free (state->reply_type);
5237 g_free (state->method_name);
5239 if (state->value != NULL)
5240 g_variant_unref (state->value);
5241 if (state->fd_list != NULL)
5242 g_object_unref (state->fd_list);
5243 g_slice_free (CallState, state);
5246 /* called in any thread, with the connection's lock not held */
5248 g_dbus_connection_call_done (GObject *source,
5249 GAsyncResult *result,
5252 GSimpleAsyncResult *simple;
5253 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5254 CallState *state = user_data;
5256 GDBusMessage *reply;
5259 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5263 if (G_UNLIKELY (_g_dbus_debug_call ()))
5265 _g_dbus_debug_print_lock ();
5266 g_print ("========================================================================\n"
5267 "GDBus-debug:Call:\n"
5268 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5274 g_print ("SUCCESS\n");
5278 g_print ("FAILED: %s\n",
5281 _g_dbus_debug_print_unlock ();
5285 state->value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5287 simple = state->simple; /* why? because state is freed before we unref simple.. */
5290 g_simple_async_result_take_error (state->simple, error);
5291 g_simple_async_result_complete (state->simple);
5292 call_state_free (state);
5296 g_simple_async_result_set_op_res_gpointer (state->simple, state, (GDestroyNotify) call_state_free);
5297 g_simple_async_result_complete (state->simple);
5298 g_object_unref (reply);
5300 g_object_unref (simple);
5303 /* called in any thread, with the connection's lock not held */
5305 g_dbus_connection_call_internal (GDBusConnection *connection,
5306 const gchar *bus_name,
5307 const gchar *object_path,
5308 const gchar *interface_name,
5309 const gchar *method_name,
5310 GVariant *parameters,
5311 const GVariantType *reply_type,
5312 GDBusCallFlags flags,
5314 GUnixFDList *fd_list,
5315 GCancellable *cancellable,
5316 GAsyncReadyCallback callback,
5319 GDBusMessage *message;
5322 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5323 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5324 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5325 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5326 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5327 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5328 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5329 g_return_if_fail (check_initialized (connection));
5331 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5333 g_return_if_fail (fd_list == NULL);
5336 state = g_slice_new0 (CallState);
5337 state->simple = g_simple_async_result_new (G_OBJECT (connection),
5338 callback, user_data,
5339 g_dbus_connection_call_internal);
5340 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5342 if (reply_type == NULL)
5343 reply_type = G_VARIANT_TYPE_ANY;
5345 state->reply_type = g_variant_type_copy (reply_type);
5347 message = g_dbus_message_new_method_call (bus_name,
5351 add_call_flags (message, flags);
5352 if (parameters != NULL)
5353 g_dbus_message_set_body (message, parameters);
5356 if (fd_list != NULL)
5357 g_dbus_message_set_unix_fd_list (message, fd_list);
5360 g_dbus_connection_send_message_with_reply (connection,
5362 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5366 g_dbus_connection_call_done,
5369 if (G_UNLIKELY (_g_dbus_debug_call ()))
5371 _g_dbus_debug_print_lock ();
5372 g_print ("========================================================================\n"
5373 "GDBus-debug:Call:\n"
5374 " >>>> ASYNC %s.%s()\n"
5376 " owned by name %s (serial %d)\n",
5380 bus_name != NULL ? bus_name : "(none)",
5382 _g_dbus_debug_print_unlock ();
5385 if (message != NULL)
5386 g_object_unref (message);
5389 /* called in any thread, with the connection's lock not held */
5391 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
5392 GUnixFDList **out_fd_list,
5396 GSimpleAsyncResult *simple;
5399 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5400 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
5401 g_dbus_connection_call_internal), NULL);
5402 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5404 simple = G_SIMPLE_ASYNC_RESULT (res);
5406 if (g_simple_async_result_propagate_error (simple, error))
5409 state = g_simple_async_result_get_op_res_gpointer (simple);
5410 if (out_fd_list != NULL)
5411 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
5412 return g_variant_ref (state->value);
5415 /* called in any user thread, with the connection's lock not held */
5417 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
5418 const gchar *bus_name,
5419 const gchar *object_path,
5420 const gchar *interface_name,
5421 const gchar *method_name,
5422 GVariant *parameters,
5423 const GVariantType *reply_type,
5424 GDBusCallFlags flags,
5426 GUnixFDList *fd_list,
5427 GUnixFDList **out_fd_list,
5428 GCancellable *cancellable,
5431 GDBusMessage *message;
5432 GDBusMessage *reply;
5434 GError *local_error;
5435 GDBusSendMessageFlags send_flags;
5441 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5442 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5443 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5444 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5445 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5446 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5447 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5449 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
5451 g_return_val_if_fail (fd_list == NULL, NULL);
5453 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5455 if (!(flags & CALL_FLAGS_INITIALIZING))
5456 g_return_val_if_fail (check_initialized (connection), FALSE);
5458 if (reply_type == NULL)
5459 reply_type = G_VARIANT_TYPE_ANY;
5461 message = g_dbus_message_new_method_call (bus_name,
5465 add_call_flags (message, flags);
5466 if (parameters != NULL)
5467 g_dbus_message_set_body (message, parameters);
5470 if (fd_list != NULL)
5471 g_dbus_message_set_unix_fd_list (message, fd_list);
5474 if (G_UNLIKELY (_g_dbus_debug_call ()))
5476 _g_dbus_debug_print_lock ();
5477 g_print ("========================================================================\n"
5478 "GDBus-debug:Call:\n"
5479 " >>>> SYNC %s.%s()\n"
5481 " owned by name %s\n",
5485 bus_name != NULL ? bus_name : "(none)");
5486 _g_dbus_debug_print_unlock ();
5491 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
5493 /* translate from one flavour of flags to another... */
5494 if (flags & CALL_FLAGS_INITIALIZING)
5495 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
5497 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5501 NULL, /* volatile guint32 *out_serial */
5505 if (G_UNLIKELY (_g_dbus_debug_call ()))
5507 _g_dbus_debug_print_lock ();
5508 g_print ("========================================================================\n"
5509 "GDBus-debug:Call:\n"
5510 " <<<< SYNC COMPLETE %s.%s()\n"
5516 g_print ("SUCCESS\n");
5520 g_print ("FAILED: %s\n",
5521 local_error->message);
5523 _g_dbus_debug_print_unlock ();
5529 *error = local_error;
5531 g_error_free (local_error);
5535 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
5538 if (message != NULL)
5539 g_object_unref (message);
5541 g_object_unref (reply);
5546 /* ---------------------------------------------------------------------------------------------------- */
5549 * g_dbus_connection_call:
5550 * @connection: A #GDBusConnection.
5551 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5552 * @connection is not a message bus connection.
5553 * @object_path: Path of remote object.
5554 * @interface_name: D-Bus interface to invoke method on.
5555 * @method_name: The name of the method to invoke.
5556 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5557 * or %NULL if not passing parameters.
5558 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5559 * @flags: Flags from the #GDBusCallFlags enumeration.
5560 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5561 * timeout or %G_MAXINT for no timeout.
5562 * @cancellable: A #GCancellable or %NULL.
5563 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5564 * satisfied or %NULL if you don't care about the result of the
5565 * method invocation.
5566 * @user_data: The data to pass to @callback.
5568 * Asynchronously invokes the @method_name method on the
5569 * @interface_name D-Bus interface on the remote object at
5570 * @object_path owned by @bus_name.
5572 * If @connection is closed then the operation will fail with
5573 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
5574 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
5575 * not compatible with the D-Bus protocol, the operation fails with
5576 * %G_IO_ERROR_INVALID_ARGUMENT.
5578 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
5579 * error will be raised if it does not match. Said another way, if you give a @reply_type
5580 * then any non-%NULL return value will be of this type.
5582 * If the @parameters #GVariant is floating, it is consumed. This allows
5583 * convenient 'inline' use of g_variant_new(), e.g.:
5585 * g_dbus_connection_call (connection,
5586 * "org.freedesktop.StringThings",
5587 * "/org/freedesktop/StringThings",
5588 * "org.freedesktop.StringThings",
5590 * g_variant_new ("(ss)",
5594 * G_DBUS_CALL_FLAGS_NONE,
5597 * (GAsyncReadyCallback) two_strings_done,
5601 * This is an asynchronous method. When the operation is finished, @callback will be invoked
5602 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
5603 * of the thread you are calling this method from. You can then call
5604 * g_dbus_connection_call_finish() to get the result of the operation.
5605 * See g_dbus_connection_call_sync() for the synchronous version of this
5611 g_dbus_connection_call (GDBusConnection *connection,
5612 const gchar *bus_name,
5613 const gchar *object_path,
5614 const gchar *interface_name,
5615 const gchar *method_name,
5616 GVariant *parameters,
5617 const GVariantType *reply_type,
5618 GDBusCallFlags flags,
5620 GCancellable *cancellable,
5621 GAsyncReadyCallback callback,
5624 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);
5628 * g_dbus_connection_call_finish:
5629 * @connection: A #GDBusConnection.
5630 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
5631 * @error: Return location for error or %NULL.
5633 * Finishes an operation started with g_dbus_connection_call().
5635 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5636 * return values. Free with g_variant_unref().
5641 g_dbus_connection_call_finish (GDBusConnection *connection,
5645 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
5649 * g_dbus_connection_call_sync:
5650 * @connection: A #GDBusConnection.
5651 * @bus_name: A unique or well-known bus name.
5652 * @object_path: Path of remote object.
5653 * @interface_name: D-Bus interface to invoke method on.
5654 * @method_name: The name of the method to invoke.
5655 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5656 * or %NULL if not passing parameters.
5657 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5658 * @flags: Flags from the #GDBusCallFlags enumeration.
5659 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5660 * timeout or %G_MAXINT for no timeout.
5661 * @cancellable: A #GCancellable or %NULL.
5662 * @error: Return location for error or %NULL.
5664 * Synchronously invokes the @method_name method on the
5665 * @interface_name D-Bus interface on the remote object at
5666 * @object_path owned by @bus_name.
5668 * If @connection is closed then the operation will fail with
5669 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
5670 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
5671 * contains a value not compatible with the D-Bus protocol, the operation
5672 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
5674 * If @reply_type is non-%NULL then the reply will be checked for having
5675 * this type and an error will be raised if it does not match. Said
5676 * another way, if you give a @reply_type then any non-%NULL return
5677 * value will be of this type.
5679 * If the @parameters #GVariant is floating, it is consumed.
5680 * This allows convenient 'inline' use of g_variant_new(), e.g.:
5682 * g_dbus_connection_call_sync (connection,
5683 * "org.freedesktop.StringThings",
5684 * "/org/freedesktop/StringThings",
5685 * "org.freedesktop.StringThings",
5687 * g_variant_new ("(ss)",
5691 * G_DBUS_CALL_FLAGS_NONE,
5697 * The calling thread is blocked until a reply is received. See
5698 * g_dbus_connection_call() for the asynchronous version of
5701 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5702 * return values. Free with g_variant_unref().
5707 g_dbus_connection_call_sync (GDBusConnection *connection,
5708 const gchar *bus_name,
5709 const gchar *object_path,
5710 const gchar *interface_name,
5711 const gchar *method_name,
5712 GVariant *parameters,
5713 const GVariantType *reply_type,
5714 GDBusCallFlags flags,
5716 GCancellable *cancellable,
5719 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);
5722 /* ---------------------------------------------------------------------------------------------------- */
5727 * g_dbus_connection_call_with_unix_fd_list:
5728 * @connection: A #GDBusConnection.
5729 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5730 * @connection is not a message bus connection.
5731 * @object_path: Path of remote object.
5732 * @interface_name: D-Bus interface to invoke method on.
5733 * @method_name: The name of the method to invoke.
5734 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5735 * or %NULL if not passing parameters.
5736 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5737 * @flags: Flags from the #GDBusCallFlags enumeration.
5738 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5739 * timeout or %G_MAXINT for no timeout.
5740 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
5741 * @cancellable: A #GCancellable or %NULL.
5742 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5743 * satisfied or %NULL if you don't * care about the result of the
5744 * method invocation.
5745 * @user_data: The data to pass to @callback.
5747 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
5749 * This method is only available on UNIX.
5754 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
5755 const gchar *bus_name,
5756 const gchar *object_path,
5757 const gchar *interface_name,
5758 const gchar *method_name,
5759 GVariant *parameters,
5760 const GVariantType *reply_type,
5761 GDBusCallFlags flags,
5763 GUnixFDList *fd_list,
5764 GCancellable *cancellable,
5765 GAsyncReadyCallback callback,
5768 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);
5772 * g_dbus_connection_call_with_unix_fd_list_finish:
5773 * @connection: A #GDBusConnection.
5774 * @out_fd_list: (out): Return location for a #GUnixFDList or %NULL.
5775 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call_with_unix_fd_list().
5776 * @error: Return location for error or %NULL.
5778 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
5780 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5781 * return values. Free with g_variant_unref().
5786 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
5787 GUnixFDList **out_fd_list,
5791 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
5795 * g_dbus_connection_call_with_unix_fd_list_sync:
5796 * @connection: A #GDBusConnection.
5797 * @bus_name: A unique or well-known bus name.
5798 * @object_path: Path of remote object.
5799 * @interface_name: D-Bus interface to invoke method on.
5800 * @method_name: The name of the method to invoke.
5801 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5802 * or %NULL if not passing parameters.
5803 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5804 * @flags: Flags from the #GDBusCallFlags enumeration.
5805 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5806 * timeout or %G_MAXINT for no timeout.
5807 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
5808 * @out_fd_list: (out): Return location for a #GUnixFDList or %NULL.
5809 * @cancellable: A #GCancellable or %NULL.
5810 * @error: Return location for error or %NULL.
5812 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
5814 * This method is only available on UNIX.
5816 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5817 * return values. Free with g_variant_unref().
5822 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
5823 const gchar *bus_name,
5824 const gchar *object_path,
5825 const gchar *interface_name,
5826 const gchar *method_name,
5827 GVariant *parameters,
5828 const GVariantType *reply_type,
5829 GDBusCallFlags flags,
5831 GUnixFDList *fd_list,
5832 GUnixFDList **out_fd_list,
5833 GCancellable *cancellable,
5836 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);
5839 #endif /* G_OS_UNIX */
5841 /* ---------------------------------------------------------------------------------------------------- */
5843 struct ExportedSubtree
5847 GDBusConnection *connection;
5848 GDBusSubtreeVTable *vtable;
5849 GDBusSubtreeFlags flags;
5851 GMainContext *context;
5853 GDestroyNotify user_data_free_func;
5857 exported_subtree_free (ExportedSubtree *es)
5859 call_destroy_notify (es->context,
5860 es->user_data_free_func,
5863 g_main_context_unref (es->context);
5865 _g_dbus_subtree_vtable_free (es->vtable);
5866 g_free (es->object_path);
5870 /* called without lock held in the thread where the caller registered
5874 handle_subtree_introspect (GDBusConnection *connection,
5875 ExportedSubtree *es,
5876 GDBusMessage *message)
5880 GDBusMessage *reply;
5883 const gchar *sender;
5884 const gchar *requested_object_path;
5885 const gchar *requested_node;
5886 GDBusInterfaceInfo **interfaces;
5888 gchar **subnode_paths;
5889 gboolean has_properties_interface;
5890 gboolean has_introspectable_interface;
5894 requested_object_path = g_dbus_message_get_path (message);
5895 sender = g_dbus_message_get_sender (message);
5896 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5898 s = g_string_new (NULL);
5899 introspect_append_header (s);
5901 /* Strictly we don't need the children in dynamic mode, but we avoid the
5902 * conditionals to preserve code clarity
5904 children = es->vtable->enumerate (es->connection,
5911 requested_node = strrchr (requested_object_path, '/') + 1;
5913 /* Assert existence of object if we are not dynamic */
5914 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
5915 !_g_strv_has_string ((const gchar * const *) children, requested_node))
5920 requested_node = NULL;
5923 interfaces = es->vtable->introspect (es->connection,
5928 if (interfaces != NULL)
5930 has_properties_interface = FALSE;
5931 has_introspectable_interface = FALSE;
5933 for (n = 0; interfaces[n] != NULL; n++)
5935 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
5936 has_properties_interface = TRUE;
5937 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
5938 has_introspectable_interface = TRUE;
5940 if (!has_properties_interface)
5941 g_string_append (s, introspect_properties_interface);
5942 if (!has_introspectable_interface)
5943 g_string_append (s, introspect_introspectable_interface);
5945 for (n = 0; interfaces[n] != NULL; n++)
5947 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
5948 g_dbus_interface_info_unref (interfaces[n]);
5950 g_free (interfaces);
5953 /* then include <node> entries from the Subtree for the root */
5956 for (n = 0; children != NULL && children[n] != NULL; n++)
5957 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
5960 /* finally include nodes registered below us */
5961 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
5962 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
5963 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
5964 g_strfreev (subnode_paths);
5966 g_string_append (s, "</node>\n");
5968 reply = g_dbus_message_new_method_reply (message);
5969 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5970 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5971 g_object_unref (reply);
5976 g_string_free (s, TRUE);
5977 g_strfreev (children);
5981 /* called without lock held in the thread where the caller registered
5985 handle_subtree_method_invocation (GDBusConnection *connection,
5986 ExportedSubtree *es,
5987 GDBusMessage *message)
5990 const gchar *sender;
5991 const gchar *interface_name;
5992 const gchar *member;
5993 const gchar *signature;
5994 const gchar *requested_object_path;
5995 const gchar *requested_node;
5997 GDBusInterfaceInfo *interface_info;
5998 const GDBusInterfaceVTable *interface_vtable;
5999 gpointer interface_user_data;
6001 GDBusInterfaceInfo **interfaces;
6002 gboolean is_property_get;
6003 gboolean is_property_set;
6004 gboolean is_property_get_all;
6009 requested_object_path = g_dbus_message_get_path (message);
6010 sender = g_dbus_message_get_sender (message);
6011 interface_name = g_dbus_message_get_interface (message);
6012 member = g_dbus_message_get_member (message);
6013 signature = g_dbus_message_get_signature (message);
6014 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6016 is_property_get = FALSE;
6017 is_property_set = FALSE;
6018 is_property_get_all = FALSE;
6019 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6021 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6022 is_property_get = TRUE;
6023 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6024 is_property_set = TRUE;
6025 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6026 is_property_get_all = TRUE;
6031 requested_node = strrchr (requested_object_path, '/') + 1;
6033 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6035 /* We don't want to dispatch to unenumerated
6036 * nodes, so ensure that the child exists.
6041 children = es->vtable->enumerate (es->connection,
6046 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6047 g_strfreev (children);
6055 requested_node = NULL;
6058 /* get introspection data for the node */
6059 interfaces = es->vtable->introspect (es->connection,
6061 requested_object_path,
6065 if (interfaces == NULL)
6068 interface_info = NULL;
6069 for (n = 0; interfaces[n] != NULL; n++)
6071 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6072 interface_info = interfaces[n];
6075 /* dispatch the call if the user wants to handle it */
6076 if (interface_info != NULL)
6078 /* figure out where to dispatch the method call */
6079 interface_user_data = NULL;
6080 interface_vtable = es->vtable->dispatch (es->connection,
6085 &interface_user_data,
6087 if (interface_vtable == NULL)
6090 CONNECTION_LOCK (connection);
6091 handled = validate_and_maybe_schedule_method_call (es->connection,
6098 interface_user_data);
6099 CONNECTION_UNLOCK (connection);
6101 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6102 else if (is_property_get || is_property_set || is_property_get_all)
6104 if (is_property_get)
6105 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6106 else if (is_property_set)
6107 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6108 else if (is_property_get_all)
6109 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6111 g_assert_not_reached ();
6113 /* see if the object supports this interface at all */
6114 for (n = 0; interfaces[n] != NULL; n++)
6116 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6117 interface_info = interfaces[n];
6120 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6121 * claims it won't support the interface
6123 if (interface_info == NULL)
6125 GDBusMessage *reply;
6126 reply = g_dbus_message_new_method_error (message,
6127 "org.freedesktop.DBus.Error.InvalidArgs",
6128 _("No such interface `%s'"),
6130 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6131 g_object_unref (reply);
6136 /* figure out where to dispatch the property get/set/getall calls */
6137 interface_user_data = NULL;
6138 interface_vtable = es->vtable->dispatch (es->connection,
6143 &interface_user_data,
6145 if (interface_vtable == NULL)
6147 g_warning ("The subtree introspection function indicates that '%s' "
6148 "is a valid interface name, but calling the dispatch "
6149 "function on that interface gave us NULL", interface_name);
6153 if (is_property_get || is_property_set)
6155 CONNECTION_LOCK (connection);
6156 handled = validate_and_maybe_schedule_property_getset (es->connection,
6164 interface_user_data);
6165 CONNECTION_UNLOCK (connection);
6167 else if (is_property_get_all)
6169 CONNECTION_LOCK (connection);
6170 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6177 interface_user_data);
6178 CONNECTION_UNLOCK (connection);
6183 if (interfaces != NULL)
6185 for (n = 0; interfaces[n] != NULL; n++)
6186 g_dbus_interface_info_unref (interfaces[n]);
6187 g_free (interfaces);
6195 GDBusMessage *message;
6196 ExportedSubtree *es;
6197 } SubtreeDeferredData;
6200 subtree_deferred_data_free (SubtreeDeferredData *data)
6202 g_object_unref (data->message);
6206 /* called without lock held in the thread where the caller registered the subtree */
6208 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6210 SubtreeDeferredData *data = _data;
6215 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6216 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6217 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6218 handled = handle_subtree_introspect (data->es->connection,
6222 handled = handle_subtree_method_invocation (data->es->connection,
6228 CONNECTION_LOCK (data->es->connection);
6229 handled = handle_generic_unlocked (data->es->connection, data->message);
6230 CONNECTION_UNLOCK (data->es->connection);
6233 /* if we couldn't handle the request, just bail with the UnknownMethod error */
6236 GDBusMessage *reply;
6237 reply = g_dbus_message_new_method_error (data->message,
6238 "org.freedesktop.DBus.Error.UnknownMethod",
6239 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
6240 g_dbus_message_get_member (data->message),
6241 g_dbus_message_get_interface (data->message),
6242 g_dbus_message_get_signature (data->message));
6243 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6244 g_object_unref (reply);
6250 /* called in GDBusWorker thread with connection's lock held */
6252 subtree_message_func (GDBusConnection *connection,
6253 ExportedSubtree *es,
6254 GDBusMessage *message)
6256 GSource *idle_source;
6257 SubtreeDeferredData *data;
6259 data = g_new0 (SubtreeDeferredData, 1);
6260 data->message = g_object_ref (message);
6263 /* defer this call to an idle handler in the right thread */
6264 idle_source = g_idle_source_new ();
6265 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
6266 g_source_set_callback (idle_source,
6267 process_subtree_vtable_message_in_idle_cb,
6269 (GDestroyNotify) subtree_deferred_data_free);
6270 g_source_attach (idle_source, es->context);
6271 g_source_unref (idle_source);
6273 /* since we own the entire subtree, handlers for objects not in the subtree have been
6274 * tried already by libdbus-1 - so we just need to ensure that we're always going
6275 * to reply to the message
6281 * g_dbus_connection_register_subtree:
6282 * @connection: A #GDBusConnection.
6283 * @object_path: The object path to register the subtree at.
6284 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
6285 * @flags: Flags used to fine tune the behavior of the subtree.
6286 * @user_data: Data to pass to functions in @vtable.
6287 * @user_data_free_func: Function to call when the subtree is unregistered.
6288 * @error: Return location for error or %NULL.
6290 * Registers a whole subtree of <quote>dynamic</quote> objects.
6292 * The @enumerate and @introspection functions in @vtable are used to
6293 * convey, to remote callers, what nodes exist in the subtree rooted
6296 * When handling remote calls into any node in the subtree, first the
6297 * @enumerate function is used to check if the node exists. If the node exists
6298 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6299 * the @introspection function is used to check if the node supports the
6300 * requested method. If so, the @dispatch function is used to determine
6301 * where to dispatch the call. The collected #GDBusInterfaceVTable and
6302 * #gpointer will be used to call into the interface vtable for processing
6305 * All calls into user-provided code will be invoked in the <link
6306 * linkend="g-main-context-push-thread-default">thread-default main
6307 * loop</link> of the thread you are calling this method from.
6309 * If an existing subtree is already registered at @object_path or
6310 * then @error is set to #G_IO_ERROR_EXISTS.
6312 * Note that it is valid to register regular objects (using
6313 * g_dbus_connection_register_object()) in a subtree registered with
6314 * g_dbus_connection_register_subtree() - if so, the subtree handler
6315 * is tried as the last resort. One way to think about a subtree
6316 * handler is to consider it a <quote>fallback handler</quote>
6317 * for object paths not registered via g_dbus_connection_register_object()
6318 * or other bindings.
6320 * Note that @vtable will be copied so you cannot change it after
6323 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
6325 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
6326 * that can be used with g_dbus_connection_unregister_subtree() .
6331 g_dbus_connection_register_subtree (GDBusConnection *connection,
6332 const gchar *object_path,
6333 const GDBusSubtreeVTable *vtable,
6334 GDBusSubtreeFlags flags,
6336 GDestroyNotify user_data_free_func,
6340 ExportedSubtree *es;
6342 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
6343 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
6344 g_return_val_if_fail (vtable != NULL, 0);
6345 g_return_val_if_fail (error == NULL || *error == NULL, 0);
6346 g_return_val_if_fail (check_initialized (connection), 0);
6350 CONNECTION_LOCK (connection);
6352 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6358 _("A subtree is already exported for %s"),
6363 es = g_new0 (ExportedSubtree, 1);
6364 es->object_path = g_strdup (object_path);
6365 es->connection = connection;
6367 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
6369 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
6370 es->user_data = user_data;
6371 es->user_data_free_func = user_data_free_func;
6372 es->context = g_main_context_ref_thread_default ();
6374 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
6375 g_hash_table_insert (connection->map_id_to_es,
6376 GUINT_TO_POINTER (es->id),
6382 CONNECTION_UNLOCK (connection);
6387 /* ---------------------------------------------------------------------------------------------------- */
6390 * g_dbus_connection_unregister_subtree:
6391 * @connection: A #GDBusConnection.
6392 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
6394 * Unregisters a subtree.
6396 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
6401 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
6402 guint registration_id)
6404 ExportedSubtree *es;
6407 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
6408 g_return_val_if_fail (check_initialized (connection), FALSE);
6412 CONNECTION_LOCK (connection);
6414 es = g_hash_table_lookup (connection->map_id_to_es,
6415 GUINT_TO_POINTER (registration_id));
6419 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
6420 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
6425 CONNECTION_UNLOCK (connection);
6430 /* ---------------------------------------------------------------------------------------------------- */
6432 /* may be called in any thread, with connection's lock held */
6434 handle_generic_ping_unlocked (GDBusConnection *connection,
6435 const gchar *object_path,
6436 GDBusMessage *message)
6438 GDBusMessage *reply;
6439 reply = g_dbus_message_new_method_reply (message);
6440 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6441 g_object_unref (reply);
6444 /* may be called in any thread, with connection's lock held */
6446 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
6447 const gchar *object_path,
6448 GDBusMessage *message)
6450 GDBusMessage *reply;
6453 if (connection->machine_id == NULL)
6458 connection->machine_id = _g_dbus_get_machine_id (&error);
6459 if (connection->machine_id == NULL)
6461 reply = g_dbus_message_new_method_error_literal (message,
6462 "org.freedesktop.DBus.Error.Failed",
6464 g_error_free (error);
6470 reply = g_dbus_message_new_method_reply (message);
6471 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
6473 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6474 g_object_unref (reply);
6477 /* may be called in any thread, with connection's lock held */
6479 handle_generic_introspect_unlocked (GDBusConnection *connection,
6480 const gchar *object_path,
6481 GDBusMessage *message)
6486 GDBusMessage *reply;
6488 /* first the header */
6489 s = g_string_new (NULL);
6490 introspect_append_header (s);
6492 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
6493 for (n = 0; registered != NULL && registered[n] != NULL; n++)
6494 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
6495 g_strfreev (registered);
6496 g_string_append (s, "</node>\n");
6498 reply = g_dbus_message_new_method_reply (message);
6499 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6500 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6501 g_object_unref (reply);
6502 g_string_free (s, TRUE);
6505 /* may be called in any thread, with connection's lock held */
6507 handle_generic_unlocked (GDBusConnection *connection,
6508 GDBusMessage *message)
6511 const gchar *interface_name;
6512 const gchar *member;
6513 const gchar *signature;
6516 CONNECTION_ENSURE_LOCK (connection);
6520 interface_name = g_dbus_message_get_interface (message);
6521 member = g_dbus_message_get_member (message);
6522 signature = g_dbus_message_get_signature (message);
6523 path = g_dbus_message_get_path (message);
6525 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
6526 g_strcmp0 (member, "Introspect") == 0 &&
6527 g_strcmp0 (signature, "") == 0)
6529 handle_generic_introspect_unlocked (connection, path, message);
6532 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6533 g_strcmp0 (member, "Ping") == 0 &&
6534 g_strcmp0 (signature, "") == 0)
6536 handle_generic_ping_unlocked (connection, path, message);
6539 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6540 g_strcmp0 (member, "GetMachineId") == 0 &&
6541 g_strcmp0 (signature, "") == 0)
6543 handle_generic_get_machine_id_unlocked (connection, path, message);
6550 /* ---------------------------------------------------------------------------------------------------- */
6552 /* called in GDBusWorker thread with connection's lock held */
6554 distribute_method_call (GDBusConnection *connection,
6555 GDBusMessage *message)
6557 GDBusMessage *reply;
6559 ExportedSubtree *es;
6560 const gchar *object_path;
6561 const gchar *interface_name;
6562 const gchar *member;
6564 gchar *subtree_path;
6567 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
6569 interface_name = g_dbus_message_get_interface (message);
6570 member = g_dbus_message_get_member (message);
6571 path = g_dbus_message_get_path (message);
6572 subtree_path = g_strdup (path);
6573 needle = strrchr (subtree_path, '/');
6574 if (needle != NULL && needle != subtree_path)
6580 g_free (subtree_path);
6581 subtree_path = NULL;
6585 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
6587 _g_dbus_debug_print_lock ();
6588 g_print ("========================================================================\n"
6589 "GDBus-debug:Incoming:\n"
6590 " <<<< METHOD INVOCATION %s.%s()\n"
6592 " invoked by name %s\n"
6594 interface_name, member,
6596 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
6597 g_dbus_message_get_serial (message));
6598 _g_dbus_debug_print_unlock ();
6601 object_path = g_dbus_message_get_path (message);
6602 g_assert (object_path != NULL);
6604 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
6607 if (obj_message_func (connection, eo, message))
6611 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6614 if (subtree_message_func (connection, es, message))
6618 if (subtree_path != NULL)
6620 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
6623 if (subtree_message_func (connection, es, message))
6628 if (handle_generic_unlocked (connection, message))
6631 /* if we end up here, the message has not been not handled - so return an error saying this */
6632 reply = g_dbus_message_new_method_error (message,
6633 "org.freedesktop.DBus.Error.UnknownMethod",
6634 _("No such interface `%s' on object at path %s"),
6637 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6638 g_object_unref (reply);
6641 g_free (subtree_path);
6644 /* ---------------------------------------------------------------------------------------------------- */
6646 /* Called in any user thread, with the message_bus_lock held. */
6648 message_bus_get_singleton (GBusType bus_type,
6652 const gchar *starter_bus;
6658 case G_BUS_TYPE_SESSION:
6659 ret = &the_session_bus;
6662 case G_BUS_TYPE_SYSTEM:
6663 ret = &the_system_bus;
6666 case G_BUS_TYPE_STARTER:
6667 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
6668 if (g_strcmp0 (starter_bus, "session") == 0)
6670 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
6673 else if (g_strcmp0 (starter_bus, "system") == 0)
6675 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
6680 if (starter_bus != NULL)
6684 G_IO_ERROR_INVALID_ARGUMENT,
6685 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
6686 " - unknown value `%s'"),
6691 g_set_error_literal (error,
6693 G_IO_ERROR_INVALID_ARGUMENT,
6694 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
6695 "variable is not set"));
6701 g_assert_not_reached ();
6709 /* Called in any user thread, without holding locks. */
6710 static GDBusConnection *
6711 get_uninitialized_connection (GBusType bus_type,
6712 GCancellable *cancellable,
6715 GWeakRef *singleton;
6716 GDBusConnection *ret;
6720 G_LOCK (message_bus_lock);
6721 singleton = message_bus_get_singleton (bus_type, error);
6722 if (singleton == NULL)
6725 ret = g_weak_ref_get (singleton);
6730 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
6731 if (address == NULL)
6733 ret = g_object_new (G_TYPE_DBUS_CONNECTION,
6735 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
6736 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
6737 "exit-on-close", TRUE,
6740 g_weak_ref_set (singleton, ret);
6744 g_assert (ret != NULL);
6747 G_UNLOCK (message_bus_lock);
6753 * @bus_type: A #GBusType.
6754 * @cancellable: A #GCancellable or %NULL.
6755 * @error: Return location for error or %NULL.
6757 * Synchronously connects to the message bus specified by @bus_type.
6758 * Note that the returned object may shared with other callers,
6759 * e.g. if two separate parts of a process calls this function with
6760 * the same @bus_type, they will share the same object.
6762 * This is a synchronous failable function. See g_bus_get() and
6763 * g_bus_get_finish() for the asynchronous version.
6765 * The returned object is a singleton, that is, shared with other
6766 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6767 * event that you need a private message bus connection, use
6768 * g_dbus_address_get_for_bus_sync() and
6769 * g_dbus_connection_new_for_address().
6771 * Note that the returned #GDBusConnection object will (usually) have
6772 * the #GDBusConnection:exit-on-close property set to %TRUE.
6774 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6779 g_bus_get_sync (GBusType bus_type,
6780 GCancellable *cancellable,
6783 GDBusConnection *connection;
6785 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6787 connection = get_uninitialized_connection (bus_type, cancellable, error);
6788 if (connection == NULL)
6791 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
6793 g_object_unref (connection);
6802 bus_get_async_initable_cb (GObject *source_object,
6806 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
6810 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
6814 g_assert (error != NULL);
6815 g_simple_async_result_take_error (simple, error);
6816 g_object_unref (source_object);
6820 g_simple_async_result_set_op_res_gpointer (simple,
6824 g_simple_async_result_complete_in_idle (simple);
6825 g_object_unref (simple);
6830 * @bus_type: A #GBusType.
6831 * @cancellable: A #GCancellable or %NULL.
6832 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
6833 * @user_data: The data to pass to @callback.
6835 * Asynchronously connects to the message bus specified by @bus_type.
6837 * When the operation is finished, @callback will be invoked. You can
6838 * then call g_bus_get_finish() to get the result of the operation.
6840 * This is a asynchronous failable function. See g_bus_get_sync() for
6841 * the synchronous version.
6846 g_bus_get (GBusType bus_type,
6847 GCancellable *cancellable,
6848 GAsyncReadyCallback callback,
6851 GDBusConnection *connection;
6852 GSimpleAsyncResult *simple;
6855 simple = g_simple_async_result_new (NULL,
6861 connection = get_uninitialized_connection (bus_type, cancellable, &error);
6862 if (connection == NULL)
6864 g_assert (error != NULL);
6865 g_simple_async_result_take_error (simple, error);
6866 g_simple_async_result_complete_in_idle (simple);
6867 g_object_unref (simple);
6871 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
6874 bus_get_async_initable_cb,
6881 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
6882 * @error: Return location for error or %NULL.
6884 * Finishes an operation started with g_bus_get().
6886 * The returned object is a singleton, that is, shared with other
6887 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6888 * event that you need a private message bus connection, use
6889 * g_dbus_address_get_for_bus_sync() and
6890 * g_dbus_connection_new_for_address().
6892 * Note that the returned #GDBusConnection object will (usually) have
6893 * the #GDBusConnection:exit-on-close property set to %TRUE.
6895 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6900 g_bus_get_finish (GAsyncResult *res,
6903 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
6905 GDBusConnection *ret;
6907 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6909 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
6913 if (g_simple_async_result_propagate_error (simple, error))
6916 object = g_simple_async_result_get_op_res_gpointer (simple);
6917 g_assert (object != NULL);
6918 ret = g_object_ref (G_DBUS_CONNECTION (object));
6924 /* ---------------------------------------------------------------------------------------------------- */