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 * - Validate all data (e.g. UTF-8) and check all the required D-Bus headers
27 * are present and forbidden ones aren't
28 * - When writing: g_dbus_message_to_blob()
29 * - When reading: g_dbus_message_new_from_blob()
31 * - would be nice to expose GDBusAuthMechanism and an extension point
33 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
34 * the mechanism VFuncs need to be able to set an error.
36 * - Need to document other mechanisms/sources for determining the D-Bus
37 * address of a well-known bus.
39 * - e.g. on Win32 we need code like from here
41 * http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
43 * that was never copied over here because it originally was copy-paste
44 * from the GPLv2 / AFL 2.1 libdbus sources.
46 * - on OS X we need to look in launchd for the address
48 * https://bugs.freedesktop.org/show_bug.cgi?id=14259
50 * - on X11 we need to look in a X11 property on the X server
51 * - (we can also just use dbus-launch(1) from the D-Bus
54 * - (ideally) this requires D-Bus spec work because none of
55 * this has never really been specced out properly (excect
58 * - Related to the above, we also need to be able to launch a message bus
59 * instance.... Since we don't want to write our own bus daemon we should
60 * launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
62 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
63 * to specify where the nonce is stored. This will allow people to use
64 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
65 * to easily acheive secure RPC via nonce-tcp.
67 * - need to expose an extension point for resolving D-Bus address and
68 * turning them into GIOStream objects. This will allow us to implement
69 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
71 * - see g_dbus_address_connect() in gdbusaddress.c
73 * - would be cute to use kernel-specific APIs to resolve fds for
74 * debug output when using G_DBUS_DEBUG=messages, e.g. in addition to
76 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
78 * maybe we can show more information about what fd 21 really is.
79 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
80 * Initial experiments on Linux 2.6 suggests that the symlink looks
85 * e.g. not of much use.
87 * - GDBus High-Level docs
88 * - Proxy: properties, signals...
89 * - Connection: IOStream based, ::close, connection setup steps
90 * mainloop integration, threading
91 * - Differences from libdbus (extend "Migrating from")
92 * - the message handling thread
93 * - Using GVariant instead of GValue
94 * - Explain why the high-level API is a good thing and what
95 * kind of pitfalls it avoids
96 * - Export objects before claiming names
97 * - Talk about auto-starting services (cf. GBusNameWatcherFlags)
99 * - Mention in all API that the GVariant is sunk. Also mention
100 * when the returned GVariant is floating.
102 * - Consistent timeout handling (25s vs 30s?)
110 #include "gdbusauth.h"
111 #include "gdbusutils.h"
112 #include "gdbusaddress.h"
113 #include "gdbusmessage.h"
114 #include "gdbusconnection.h"
115 #include "gdbuserror.h"
116 #include "gioenumtypes.h"
117 #include "gdbusintrospection.h"
118 #include "gdbusmethodinvocation.h"
119 #include "gdbusprivate.h"
120 #include "gdbusauthobserver.h"
121 #include "gio-marshal.h"
122 #include "ginitable.h"
123 #include "gasyncinitable.h"
124 #include "giostream.h"
125 #include "gasyncresult.h"
126 #include "gsimpleasyncresult.h"
129 #include <gio/gunixconnection.h>
130 #include <gio/gunixfdmessage.h>
132 #include <sys/types.h>
135 #include "glibintl.h"
136 #include "gioalias.h"
139 * SECTION:gdbusconnection
140 * @short_description: D-Bus Connections
141 * @include: gio/gio.h
143 * The #GDBusConnection type is used for D-Bus connections to remote
144 * peers such as a message buses. It is a low-level API that offers a
145 * lot of flexibility. For instance, it lets you establish a connection
146 * over any transport that can by represented as an #GIOStream.
148 * This class is rarely used directly in D-Bus clients. If you are writing
149 * an D-Bus client, it is often easier to use the g_bus_own_name(),
150 * g_bus_watch_name() or g_bus_watch_proxy() APIs.
152 * <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>
154 * <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>
156 * <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>
158 * <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>
161 /* ---------------------------------------------------------------------------------------------------- */
163 G_LOCK_DEFINE_STATIC (message_bus_lock);
165 static GDBusConnection *the_session_bus = NULL;
166 static GDBusConnection *the_system_bus = NULL;
168 /* ---------------------------------------------------------------------------------------------------- */
171 _g_strv_has_string (const gchar* const *haystack,
176 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
178 if (g_strcmp0 (haystack[n], needle) == 0)
184 /* ---------------------------------------------------------------------------------------------------- */
187 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
189 // TODO: for some reason this doesn't work on Windows
190 #define CONNECTION_ENSURE_LOCK(obj) do { \
191 if (G_UNLIKELY (g_mutex_trylock((obj)->priv->lock))) \
193 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
194 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
199 #define CONNECTION_LOCK(obj) do { \
200 g_mutex_lock ((obj)->priv->lock); \
203 #define CONNECTION_UNLOCK(obj) do { \
204 g_mutex_unlock ((obj)->priv->lock); \
207 struct _GDBusConnectionPrivate
209 /* ------------------------------------------------------------------------ */
210 /* -- General object state ------------------------------------------------ */
211 /* ------------------------------------------------------------------------ */
213 /* object-wide lock */
216 /* A lock used in the init() method of the GInitable interface - see comments
217 * in initable_init() for why a separate lock is needed
221 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
222 * someone calls org.freedesktop.DBus.GetMachineId()
226 /* The underlying stream used for communication */
229 /* The object used for authentication (if any) */
232 /* Set to TRUE if the connection has been closed */
235 /* Last serial used */
238 /* The object used to send/receive message */
241 /* If connected to a message bus, this contains the unique name assigned to
242 * us by the bus (e.g. ":1.42")
244 gchar *bus_unique_name;
246 /* The GUID returned by the other side if we authenticed as a client or
247 * the GUID to use if authenticating as a server
251 /* set to TRUE exactly when initable_init() has finished running */
252 gboolean is_initialized;
254 /* If the connection could not be established during initable_init(), this GError will set */
255 GError *initialization_error;
257 /* The result of g_main_context_get_thread_default() when the object
258 * was created (the GObject _init() function) - this is used for delivery
259 * of the :closed GObject signal.
261 GMainContext *main_context_at_construction;
263 /* construct properties */
265 GDBusConnectionFlags flags;
267 /* Map used for managing method replies */
268 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
270 /* Maps used for managing signal subscription */
271 GHashTable *map_rule_to_signal_data; /* gchar* -> SignalData */
272 GHashTable *map_id_to_signal_data; /* guint -> SignalData */
273 GHashTable *map_sender_to_signal_data_array; /* gchar* -> GPtrArray* of SignalData */
275 /* Maps used for managing exported objects and subtrees */
276 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
277 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
278 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
279 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
281 /* Structure used for message filters */
284 /* Whether to exit on close */
285 gboolean exit_on_close;
287 /* Capabilities negotiated during authentication */
288 GDBusCapabilityFlags capabilities;
290 GDBusAuthObserver *authentication_observer;
291 GCredentials *crendentials;
294 typedef struct ExportedObject ExportedObject;
295 static void exported_object_free (ExportedObject *eo);
297 typedef struct ExportedSubtree ExportedSubtree;
298 static void exported_subtree_free (ExportedSubtree *es);
316 PROP_CAPABILITY_FLAGS,
317 PROP_AUTHENTICATION_OBSERVER,
320 static void distribute_signals (GDBusConnection *connection,
321 GDBusMessage *message);
323 static void distribute_method_call (GDBusConnection *connection,
324 GDBusMessage *message);
326 static gboolean handle_generic_unlocked (GDBusConnection *connection,
327 GDBusMessage *message);
330 static void purge_all_signal_subscriptions (GDBusConnection *connection);
331 static void purge_all_filters (GDBusConnection *connection);
333 #define _G_ENSURE_LOCK(name) do { \
334 if (G_UNLIKELY (G_TRYLOCK(name))) \
336 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
337 "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
341 static guint signals[LAST_SIGNAL] = { 0 };
343 static void initable_iface_init (GInitableIface *initable_iface);
344 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
346 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
347 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
348 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
352 g_dbus_connection_dispose (GObject *object)
354 GDBusConnection *connection = G_DBUS_CONNECTION (object);
356 G_LOCK (message_bus_lock);
357 //g_debug ("disposing %p", connection);
358 if (connection == the_session_bus)
360 the_session_bus = NULL;
362 else if (connection == the_system_bus)
364 the_system_bus = NULL;
366 if (connection->priv->worker != NULL)
368 _g_dbus_worker_stop (connection->priv->worker);
369 connection->priv->worker = NULL;
371 G_UNLOCK (message_bus_lock);
373 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
374 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
378 g_dbus_connection_finalize (GObject *object)
380 GDBusConnection *connection = G_DBUS_CONNECTION (object);
382 if (connection->priv->authentication_observer != NULL)
383 g_object_unref (connection->priv->authentication_observer);
385 if (connection->priv->auth != NULL)
386 g_object_unref (connection->priv->auth);
388 //g_debug ("finalizing %p", connection);
389 if (connection->priv->stream != NULL)
391 /* We don't really care if closing the stream succeeds or not */
392 g_io_stream_close_async (connection->priv->stream,
394 NULL, /* GCancellable */
395 NULL, /* GAsyncReadyCallback */
396 NULL); /* userdata */
397 g_object_unref (connection->priv->stream);
398 connection->priv->stream = NULL;
401 g_free (connection->priv->address);
403 g_free (connection->priv->guid);
404 g_free (connection->priv->bus_unique_name);
406 if (connection->priv->initialization_error != NULL)
407 g_error_free (connection->priv->initialization_error);
409 g_hash_table_unref (connection->priv->map_method_serial_to_send_message_data);
411 purge_all_signal_subscriptions (connection);
412 g_hash_table_unref (connection->priv->map_rule_to_signal_data);
413 g_hash_table_unref (connection->priv->map_id_to_signal_data);
414 g_hash_table_unref (connection->priv->map_sender_to_signal_data_array);
416 g_hash_table_unref (connection->priv->map_id_to_ei);
417 g_hash_table_unref (connection->priv->map_object_path_to_eo);
418 g_hash_table_unref (connection->priv->map_id_to_es);
419 g_hash_table_unref (connection->priv->map_object_path_to_es);
421 purge_all_filters (connection);
422 g_ptr_array_unref (connection->priv->filters);
424 if (connection->priv->main_context_at_construction != NULL)
425 g_main_context_unref (connection->priv->main_context_at_construction);
427 g_free (connection->priv->machine_id);
429 g_mutex_free (connection->priv->init_lock);
430 g_mutex_free (connection->priv->lock);
432 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
436 g_dbus_connection_get_property (GObject *object,
441 GDBusConnection *connection = G_DBUS_CONNECTION (object);
446 g_value_set_object (value, g_dbus_connection_get_stream (connection));
450 g_value_set_string (value, g_dbus_connection_get_guid (connection));
453 case PROP_UNIQUE_NAME:
454 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
458 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
461 case PROP_EXIT_ON_CLOSE:
462 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
465 case PROP_CAPABILITY_FLAGS:
466 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
470 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
476 g_dbus_connection_set_property (GObject *object,
481 GDBusConnection *connection = G_DBUS_CONNECTION (object);
486 connection->priv->stream = g_value_dup_object (value);
490 connection->priv->guid = g_value_dup_string (value);
494 connection->priv->address = g_value_dup_string (value);
498 connection->priv->flags = g_value_get_flags (value);
501 case PROP_EXIT_ON_CLOSE:
502 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
505 case PROP_AUTHENTICATION_OBSERVER:
506 connection->priv->authentication_observer = g_value_dup_object (value);
510 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
516 g_dbus_connection_real_closed (GDBusConnection *connection,
517 gboolean remote_peer_vanished,
520 if (remote_peer_vanished && connection->priv->exit_on_close)
522 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
528 g_dbus_connection_class_init (GDBusConnectionClass *klass)
530 GObjectClass *gobject_class;
532 g_type_class_add_private (klass, sizeof (GDBusConnectionPrivate));
534 gobject_class = G_OBJECT_CLASS (klass);
536 gobject_class->finalize = g_dbus_connection_finalize;
537 gobject_class->dispose = g_dbus_connection_dispose;
538 gobject_class->set_property = g_dbus_connection_set_property;
539 gobject_class->get_property = g_dbus_connection_get_property;
541 klass->closed = g_dbus_connection_real_closed;
544 * GDBusConnection:stream:
546 * The underlying #GIOStream used for I/O.
550 g_object_class_install_property (gobject_class,
552 g_param_spec_object ("stream",
554 P_("The underlying streams used for I/O"),
558 G_PARAM_CONSTRUCT_ONLY |
559 G_PARAM_STATIC_NAME |
560 G_PARAM_STATIC_BLURB |
561 G_PARAM_STATIC_NICK));
564 * GDBusConnection:address:
566 * A D-Bus address specifying potential endpoints that can be used
567 * when establishing the connection.
571 g_object_class_install_property (gobject_class,
573 g_param_spec_string ("address",
575 P_("D-Bus address specifying potential socket endpoints"),
578 G_PARAM_CONSTRUCT_ONLY |
579 G_PARAM_STATIC_NAME |
580 G_PARAM_STATIC_BLURB |
581 G_PARAM_STATIC_NICK));
584 * GDBusConnection:flags:
586 * Flags from the #GDBusConnectionFlags enumeration.
590 g_object_class_install_property (gobject_class,
592 g_param_spec_flags ("flags",
595 G_TYPE_DBUS_CONNECTION_FLAGS,
596 G_DBUS_CONNECTION_FLAGS_NONE,
598 G_PARAM_CONSTRUCT_ONLY |
599 G_PARAM_STATIC_NAME |
600 G_PARAM_STATIC_BLURB |
601 G_PARAM_STATIC_NICK));
604 * GDBusConnection:guid:
606 * The GUID of the peer performing the role of server when
609 * If you are constructing a #GDBusConnection and pass
610 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
611 * #GDBusConnection:flags property then you MUST also set this
612 * property to a valid guid.
614 * If you are constructing a #GDBusConnection and pass
615 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
616 * #GDBusConnection:flags property you will be able to read the GUID
617 * of the other peer here after the connection has been successfully
622 g_object_class_install_property (gobject_class,
624 g_param_spec_string ("guid",
626 P_("GUID of the server peer"),
630 G_PARAM_CONSTRUCT_ONLY |
631 G_PARAM_STATIC_NAME |
632 G_PARAM_STATIC_BLURB |
633 G_PARAM_STATIC_NICK));
636 * GDBusConnection:unique-name:
638 * The unique name as assigned by the message bus or %NULL if the
639 * connection is not open or not a message bus connection.
643 g_object_class_install_property (gobject_class,
645 g_param_spec_string ("unique-name",
647 P_("Unique name of bus connection"),
650 G_PARAM_STATIC_NAME |
651 G_PARAM_STATIC_BLURB |
652 G_PARAM_STATIC_NICK));
655 * GDBusConnection:closed:
657 * A boolean specifying whether the connection has been closed.
661 g_object_class_install_property (gobject_class,
663 g_param_spec_boolean ("closed",
665 P_("Whether the connection is closed"),
668 G_PARAM_STATIC_NAME |
669 G_PARAM_STATIC_BLURB |
670 G_PARAM_STATIC_NICK));
673 * GDBusConnection:exit-on-close:
675 * A boolean specifying whether the process will be terminated (by
676 * calling <literal>raise(SIGTERM)</literal>) if the connection
677 * is closed by the remote peer.
681 g_object_class_install_property (gobject_class,
683 g_param_spec_boolean ("exit-on-close",
685 P_("Whether the process is terminated when the connection is closed"),
689 G_PARAM_STATIC_NAME |
690 G_PARAM_STATIC_BLURB |
691 G_PARAM_STATIC_NICK));
694 * GDBusConnection:capabilities:
696 * Flags from the #GDBusCapabilityFlags enumeration
697 * representing connection features negotiated with the other peer.
701 g_object_class_install_property (gobject_class,
702 PROP_CAPABILITY_FLAGS,
703 g_param_spec_flags ("capabilities",
706 G_TYPE_DBUS_CAPABILITY_FLAGS,
707 G_DBUS_CAPABILITY_FLAGS_NONE,
709 G_PARAM_STATIC_NAME |
710 G_PARAM_STATIC_BLURB |
711 G_PARAM_STATIC_NICK));
714 * GDBusConnection:authentication-observer:
716 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
720 g_object_class_install_property (gobject_class,
721 PROP_AUTHENTICATION_OBSERVER,
722 g_param_spec_object ("authentication-observer",
723 P_("Authentication Observer"),
724 P_("Object used to assist in the authentication process"),
725 G_TYPE_DBUS_AUTH_OBSERVER,
727 G_PARAM_CONSTRUCT_ONLY |
728 G_PARAM_STATIC_NAME |
729 G_PARAM_STATIC_BLURB |
730 G_PARAM_STATIC_NICK));
733 * GDBusConnection::closed:
734 * @connection: The #GDBusConnection emitting the signal.
735 * @remote_peer_vanished: %TRUE if @connection is closed because the
736 * remote peer closed its end of the connection.
737 * @error: A #GError with more details about the event or %NULL.
739 * Emitted when the connection is closed.
741 * The cause of this event can be
744 * If g_dbus_connection_close() is called. In this case
745 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
748 * If the remote peer closes the connection. In this case
749 * @remote_peer_vanished is set to %TRUE and @error is set.
752 * If the remote peer sends invalid or malformed data. In this
753 * case @remote_peer_vanished is set to %FALSE and @error
758 * Upon receiving this signal, you should give up your reference to
759 * @connection. You are guaranteed that this signal is emitted only
764 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
765 G_TYPE_DBUS_CONNECTION,
767 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
770 _gio_marshal_VOID__BOOLEAN_BOXED,
778 g_dbus_connection_init (GDBusConnection *connection)
780 connection->priv = G_TYPE_INSTANCE_GET_PRIVATE (connection, G_TYPE_DBUS_CONNECTION, GDBusConnectionPrivate);
782 connection->priv->lock = g_mutex_new ();
783 connection->priv->init_lock = g_mutex_new ();
785 connection->priv->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
787 connection->priv->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
789 connection->priv->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
791 connection->priv->map_sender_to_signal_data_array = g_hash_table_new_full (g_str_hash,
796 connection->priv->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
799 (GDestroyNotify) exported_object_free);
801 connection->priv->map_id_to_ei = g_hash_table_new (g_direct_hash,
804 connection->priv->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
807 (GDestroyNotify) exported_subtree_free);
809 connection->priv->map_id_to_es = g_hash_table_new (g_direct_hash,
812 connection->priv->main_context_at_construction = g_main_context_get_thread_default ();
813 if (connection->priv->main_context_at_construction != NULL)
814 g_main_context_ref (connection->priv->main_context_at_construction);
816 connection->priv->filters = g_ptr_array_new ();
820 * g_dbus_connection_get_stream:
821 * @connection: a #GDBusConnection
823 * Gets the underlying stream used for IO.
825 * Returns: the stream used for IO
830 g_dbus_connection_get_stream (GDBusConnection *connection)
832 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
833 return connection->priv->stream;
838 * g_dbus_connection_is_closed:
839 * @connection: A #GDBusConnection.
841 * Gets whether @connection is closed.
843 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
848 g_dbus_connection_is_closed (GDBusConnection *connection)
850 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
851 return connection->priv->closed;
855 * g_dbus_connection_get_capabilities:
856 * @connection: A #GDBusConnection.
858 * Gets the capabilities negotiated with the remote peer
860 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
865 g_dbus_connection_get_capabilities (GDBusConnection *connection)
867 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
868 return connection->priv->capabilities;
872 /* ---------------------------------------------------------------------------------------------------- */
876 GDBusConnection *connection;
878 gboolean remote_peer_vanished;
882 emit_closed_data_free (EmitClosedData *data)
884 g_object_unref (data->connection);
885 if (data->error != NULL)
886 g_error_free (data->error);
891 emit_closed_in_idle (gpointer user_data)
893 EmitClosedData *data = user_data;
896 g_object_notify (G_OBJECT (data->connection), "closed");
897 g_signal_emit (data->connection,
898 signals[CLOSED_SIGNAL],
900 data->remote_peer_vanished,
906 /* Can be called from any thread, must hold lock */
908 set_closed_unlocked (GDBusConnection *connection,
909 gboolean remote_peer_vanished,
912 GSource *idle_source;
913 EmitClosedData *data;
915 CONNECTION_ENSURE_LOCK (connection);
917 g_assert (!connection->priv->closed);
919 connection->priv->closed = TRUE;
921 data = g_new0 (EmitClosedData, 1);
922 data->connection = g_object_ref (connection);
923 data->remote_peer_vanished = remote_peer_vanished;
924 data->error = error != NULL ? g_error_copy (error) : NULL;
926 idle_source = g_idle_source_new ();
927 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
928 g_source_set_callback (idle_source,
931 (GDestroyNotify) emit_closed_data_free);
932 g_source_attach (idle_source, connection->priv->main_context_at_construction);
933 g_source_unref (idle_source);
936 /* ---------------------------------------------------------------------------------------------------- */
939 * g_dbus_connection_close:
940 * @connection: A #GDBusConnection.
942 * Closes @connection. Note that this never causes the process to
943 * exit (this might only happen if the other end of a shared message
944 * bus connection disconnects).
946 * If @connection is already closed, this method does nothing.
951 g_dbus_connection_close (GDBusConnection *connection)
953 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
955 CONNECTION_LOCK (connection);
956 if (!connection->priv->closed)
958 GError *error = NULL;
960 /* TODO: do this async */
961 //g_debug ("closing connection %p's stream %p", connection, connection->priv->stream);
962 if (!g_io_stream_close (connection->priv->stream, NULL, &error))
964 g_warning ("Error closing stream: %s", error->message);
965 g_error_free (error);
968 set_closed_unlocked (connection, FALSE, NULL);
970 CONNECTION_UNLOCK (connection);
973 /* ---------------------------------------------------------------------------------------------------- */
976 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
977 GDBusMessage *message,
978 volatile guint32 *out_serial,
983 guint32 serial_to_use;
986 CONNECTION_ENSURE_LOCK (connection);
988 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
989 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
991 /* TODO: check all necessary headers are present */
996 if (out_serial != NULL)
999 if (connection->priv->closed)
1001 g_set_error_literal (error,
1004 _("The connection is closed"));
1008 blob = g_dbus_message_to_blob (message,
1010 connection->priv->capabilities,
1015 serial_to_use = ++connection->priv->last_serial; /* TODO: handle overflow */
1020 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1023 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1026 g_assert_not_reached ();
1031 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1032 blob_size, serial_to_use, connection);
1033 g_printerr ("----\n");
1034 hexdump (blob, blob_size);
1035 g_printerr ("----\n");
1038 /* TODO: use connection->priv->auth to encode the blob */
1040 if (out_serial != NULL)
1041 *out_serial = serial_to_use;
1043 g_dbus_message_set_serial (message, serial_to_use);
1045 _g_dbus_worker_send_message (connection->priv->worker,
1049 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1060 * g_dbus_connection_send_message:
1061 * @connection: A #GDBusConnection.
1062 * @message: A #GDBusMessage
1063 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1064 * @error: Return location for error or %NULL.
1066 * Asynchronously sends @message to the peer represented by @connection.
1068 * If @out_serial is not %NULL, then the serial number assigned to
1069 * @message by @connection will be written to this location prior to
1070 * submitting the message to the underlying transport.
1072 * If @connection is closed then the operation will fail with
1073 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1074 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1075 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1077 * See <xref linkend="gdbus-server"/> and <xref
1078 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1079 * low-level API to send and receive UNIX file descriptors.
1081 * Returns: %TRUE if the message was well-formed and queued for
1082 * transmission, %FALSE if @error is set.
1087 g_dbus_connection_send_message (GDBusConnection *connection,
1088 GDBusMessage *message,
1089 volatile guint32 *out_serial,
1094 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1095 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1096 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1098 CONNECTION_LOCK (connection);
1099 ret = g_dbus_connection_send_message_unlocked (connection, message, out_serial, error);
1100 CONNECTION_UNLOCK (connection);
1104 /* ---------------------------------------------------------------------------------------------------- */
1108 volatile gint ref_count;
1109 GDBusConnection *connection;
1111 GSimpleAsyncResult *simple;
1113 GMainContext *main_context;
1115 GCancellable *cancellable;
1117 gulong cancellable_handler_id;
1119 GSource *timeout_source;
1124 static SendMessageData *
1125 send_message_data_ref (SendMessageData *data)
1127 g_atomic_int_inc (&data->ref_count);
1132 send_message_data_unref (SendMessageData *data)
1134 if (g_atomic_int_dec_and_test (&data->ref_count))
1136 g_assert (data->timeout_source == NULL);
1137 g_assert (data->simple == NULL);
1138 g_assert (data->cancellable_handler_id == 0);
1139 g_object_unref (data->connection);
1140 if (data->cancellable != NULL)
1141 g_object_unref (data->cancellable);
1142 if (data->main_context != NULL)
1143 g_main_context_unref (data->main_context);
1148 /* ---------------------------------------------------------------------------------------------------- */
1150 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1152 send_message_with_reply_deliver (SendMessageData *data)
1154 CONNECTION_ENSURE_LOCK (data->connection);
1156 g_assert (!data->delivered);
1158 data->delivered = TRUE;
1160 g_simple_async_result_complete_in_idle (data->simple);
1161 g_object_unref (data->simple);
1162 data->simple = NULL;
1164 if (data->timeout_source != NULL)
1166 g_source_destroy (data->timeout_source);
1167 data->timeout_source = NULL;
1169 if (data->cancellable_handler_id > 0)
1171 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1172 data->cancellable_handler_id = 0;
1175 g_warn_if_fail (g_hash_table_remove (data->connection->priv->map_method_serial_to_send_message_data,
1176 GUINT_TO_POINTER (data->serial)));
1178 send_message_data_unref (data);
1181 /* ---------------------------------------------------------------------------------------------------- */
1183 /* must hold lock */
1185 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1186 GDBusMessage *reply)
1188 if (data->delivered)
1191 g_simple_async_result_set_op_res_gpointer (data->simple,
1192 g_object_ref (reply),
1195 send_message_with_reply_deliver (data);
1201 /* ---------------------------------------------------------------------------------------------------- */
1204 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1206 SendMessageData *data = user_data;
1208 CONNECTION_LOCK (data->connection);
1209 if (data->delivered)
1212 g_simple_async_result_set_error (data->simple,
1214 G_IO_ERROR_CANCELLED,
1215 _("Operation was cancelled"));
1217 send_message_with_reply_deliver (data);
1220 CONNECTION_UNLOCK (data->connection);
1224 /* Can be called from any thread with or without lock held */
1226 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1229 SendMessageData *data = user_data;
1230 GSource *idle_source;
1232 /* postpone cancellation to idle handler since we may be called directly
1233 * via g_cancellable_connect() (e.g. holding lock)
1235 idle_source = g_idle_source_new ();
1236 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1237 g_source_set_callback (idle_source,
1238 send_message_with_reply_cancelled_idle_cb,
1239 send_message_data_ref (data),
1240 (GDestroyNotify) send_message_data_unref);
1241 g_source_attach (idle_source, data->main_context);
1242 g_source_unref (idle_source);
1245 /* ---------------------------------------------------------------------------------------------------- */
1248 send_message_with_reply_timeout_cb (gpointer user_data)
1250 SendMessageData *data = user_data;
1252 CONNECTION_LOCK (data->connection);
1253 if (data->delivered)
1256 g_simple_async_result_set_error (data->simple,
1258 G_IO_ERROR_TIMED_OUT,
1259 _("Timeout was reached"));
1261 send_message_with_reply_deliver (data);
1264 CONNECTION_UNLOCK (data->connection);
1269 /* ---------------------------------------------------------------------------------------------------- */
1272 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1273 GDBusMessage *message,
1275 volatile guint32 *out_serial,
1276 GCancellable *cancellable,
1277 GAsyncReadyCallback callback,
1280 GSimpleAsyncResult *simple;
1281 SendMessageData *data;
1283 volatile guint32 serial;
1287 if (out_serial == NULL)
1288 out_serial = &serial;
1290 if (timeout_msec == -1)
1291 timeout_msec = 30 * 1000; /* TODO: check 30 secs is the default timeout */
1293 simple = g_simple_async_result_new (G_OBJECT (connection),
1296 g_dbus_connection_send_message_with_reply);
1298 if (g_cancellable_is_cancelled (cancellable))
1300 g_simple_async_result_set_error (simple,
1302 G_IO_ERROR_CANCELLED,
1303 _("Operation was cancelled"));
1304 g_simple_async_result_complete_in_idle (simple);
1305 g_object_unref (simple);
1309 if (connection->priv->closed)
1311 g_simple_async_result_set_error (simple,
1314 _("The connection is closed"));
1315 g_simple_async_result_complete_in_idle (simple);
1316 g_object_unref (simple);
1321 if (!g_dbus_connection_send_message_unlocked (connection, message, out_serial, &error))
1323 g_simple_async_result_set_from_error (simple, error);
1324 g_simple_async_result_complete_in_idle (simple);
1325 g_object_unref (simple);
1329 data = g_new0 (SendMessageData, 1);
1330 data->ref_count = 1;
1331 data->connection = g_object_ref (connection);
1332 data->simple = simple;
1333 data->serial = *out_serial;
1334 data->main_context = g_main_context_get_thread_default ();
1335 if (data->main_context != NULL)
1336 g_main_context_ref (data->main_context);
1338 if (cancellable != NULL)
1340 data->cancellable = g_object_ref (cancellable);
1341 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1342 G_CALLBACK (send_message_with_reply_cancelled_cb),
1343 send_message_data_ref (data),
1344 (GDestroyNotify) send_message_data_unref);
1345 g_object_set_data_full (G_OBJECT (simple),
1347 g_object_ref (cancellable),
1348 (GDestroyNotify) g_object_unref);
1351 data->timeout_source = g_timeout_source_new (timeout_msec);
1352 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1353 g_source_set_callback (data->timeout_source,
1354 send_message_with_reply_timeout_cb,
1355 send_message_data_ref (data),
1356 (GDestroyNotify) send_message_data_unref);
1357 g_source_attach (data->timeout_source, data->main_context);
1358 g_source_unref (data->timeout_source);
1360 g_hash_table_insert (connection->priv->map_method_serial_to_send_message_data,
1361 GUINT_TO_POINTER (*out_serial),
1369 * g_dbus_connection_send_message_with_reply:
1370 * @connection: A #GDBusConnection.
1371 * @message: A #GDBusMessage.
1372 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1373 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1374 * @cancellable: A #GCancellable or %NULL.
1375 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1376 * care about the result.
1377 * @user_data: The data to pass to @callback.
1379 * Asynchronously sends @message to the peer represented by @connection.
1381 * If @out_serial is not %NULL, then the serial number assigned to
1382 * @message by @connection will be written to this location prior to
1383 * submitting the message to the underlying transport.
1385 * If @connection is closed then the operation will fail with
1386 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1387 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1388 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1390 * This is an asynchronous method. When the operation is finished, @callback will be invoked
1391 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
1392 * of the thread you are calling this method from. You can then call
1393 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1394 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
1396 * See <xref linkend="gdbus-server"/> and <xref
1397 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1398 * low-level API to send and receive UNIX file descriptors.
1403 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
1404 GDBusMessage *message,
1406 volatile guint32 *out_serial,
1407 GCancellable *cancellable,
1408 GAsyncReadyCallback callback,
1411 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1412 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1413 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
1415 CONNECTION_LOCK (connection);
1416 g_dbus_connection_send_message_with_reply_unlocked (connection,
1423 CONNECTION_UNLOCK (connection);
1427 * g_dbus_connection_send_message_with_reply_finish:
1428 * @connection: a #GDBusConnection
1429 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
1430 * @error: Return location for error or %NULL.
1432 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
1434 * Note that @error is only set if a local in-process error
1435 * occured. That is to say that the returned #GDBusMessage object may
1436 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1437 * g_dbus_message_to_gerror() to transcode this to a #GError.
1439 * See <xref linkend="gdbus-server"/> and <xref
1440 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1441 * low-level API to send and receive UNIX file descriptors.
1443 * Returns: A #GDBusMessage or %NULL if @error is set.
1448 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
1452 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1453 GDBusMessage *reply;
1454 GCancellable *cancellable;
1456 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1457 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1461 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
1463 if (g_simple_async_result_propagate_error (simple, error))
1466 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
1467 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
1468 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
1470 g_object_unref (reply);
1472 g_set_error_literal (error,
1474 G_IO_ERROR_CANCELLED,
1475 _("Operation was cancelled"));
1481 /* ---------------------------------------------------------------------------------------------------- */
1486 GMainContext *context;
1488 } SendMessageSyncData;
1491 send_message_with_reply_sync_cb (GDBusConnection *connection,
1495 SendMessageSyncData *data = user_data;
1496 data->res = g_object_ref (res);
1497 g_main_loop_quit (data->loop);
1501 * g_dbus_connection_send_message_with_reply_sync:
1502 * @connection: A #GDBusConnection.
1503 * @message: A #GDBusMessage.
1504 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1505 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1506 * @cancellable: A #GCancellable or %NULL.
1507 * @error: Return location for error or %NULL.
1509 * Synchronously sends @message to the peer represented by @connection
1510 * and blocks the calling thread until a reply is received or the
1511 * timeout is reached. See g_dbus_connection_send_message_with_reply()
1512 * for the asynchronous version of this method.
1514 * If @out_serial is not %NULL, then the serial number assigned to
1515 * @message by @connection will be written to this location prior to
1516 * submitting the message to the underlying transport.
1518 * If @connection is closed then the operation will fail with
1519 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1520 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1521 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1523 * Note that @error is only set if a local in-process error
1524 * occured. That is to say that the returned #GDBusMessage object may
1525 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1526 * g_dbus_message_to_gerror() to transcode this to a #GError.
1528 * See <xref linkend="gdbus-server"/> and <xref
1529 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1530 * low-level API to send and receive UNIX file descriptors.
1532 * Returns: A #GDBusMessage that is the reply to @message or %NULL if @error is set.
1537 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
1538 GDBusMessage *message,
1540 volatile guint32 *out_serial,
1541 GCancellable *cancellable,
1544 SendMessageSyncData *data;
1545 GDBusMessage *reply;
1547 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1548 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
1549 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1550 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1552 data = g_new0 (SendMessageSyncData, 1);
1553 data->context = g_main_context_new ();
1554 data->loop = g_main_loop_new (data->context, FALSE);
1556 g_main_context_push_thread_default (data->context);
1558 g_dbus_connection_send_message_with_reply (connection,
1563 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
1565 g_main_loop_run (data->loop);
1566 reply = g_dbus_connection_send_message_with_reply_finish (connection,
1570 g_main_context_pop_thread_default (data->context);
1572 g_main_context_unref (data->context);
1573 g_main_loop_unref (data->loop);
1574 g_object_unref (data->res);
1580 /* ---------------------------------------------------------------------------------------------------- */
1584 GDBusMessageFilterFunction func;
1591 GDBusMessageFilterFunction filter_function;
1593 GDestroyNotify user_data_free_func;
1596 /* Called in worker's thread - we must not block */
1598 on_worker_message_received (GDBusWorker *worker,
1599 GDBusMessage *message,
1602 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1603 FilterCallback *filters;
1604 gboolean consumed_by_filter;
1608 //g_debug ("in on_worker_message_received");
1610 g_object_ref (connection);
1612 /* First collect the set of callback functions */
1613 CONNECTION_LOCK (connection);
1614 num_filters = connection->priv->filters->len;
1615 filters = g_new0 (FilterCallback, num_filters);
1616 for (n = 0; n < num_filters; n++)
1618 FilterData *data = connection->priv->filters->pdata[n];
1619 filters[n].func = data->filter_function;
1620 filters[n].user_data = data->user_data;
1622 CONNECTION_UNLOCK (connection);
1624 /* the call the filters in order (without holding the lock) */
1625 consumed_by_filter = FALSE;
1626 for (n = 0; n < num_filters; n++)
1628 consumed_by_filter = filters[n].func (connection,
1630 filters[n].user_data);
1631 if (consumed_by_filter)
1635 /* Standard dispatch unless the filter ate the message */
1636 if (!consumed_by_filter)
1638 GDBusMessageType message_type;
1640 message_type = g_dbus_message_get_message_type (message);
1641 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
1643 guint32 reply_serial;
1644 SendMessageData *send_message_data;
1646 reply_serial = g_dbus_message_get_reply_serial (message);
1647 CONNECTION_LOCK (connection);
1648 send_message_data = g_hash_table_lookup (connection->priv->map_method_serial_to_send_message_data,
1649 GUINT_TO_POINTER (reply_serial));
1650 if (send_message_data != NULL)
1652 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
1653 send_message_data_deliver_reply_unlocked (send_message_data, message);
1657 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
1659 CONNECTION_UNLOCK (connection);
1661 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
1663 CONNECTION_LOCK (connection);
1664 distribute_signals (connection, message);
1665 CONNECTION_UNLOCK (connection);
1667 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
1669 CONNECTION_LOCK (connection);
1670 distribute_method_call (connection, message);
1671 CONNECTION_UNLOCK (connection);
1675 g_object_unref (connection);
1679 /* Called in worker's thread - we must not block */
1681 on_worker_closed (GDBusWorker *worker,
1682 gboolean remote_peer_vanished,
1686 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1688 //g_debug ("in on_worker_closed: %s", error->message);
1690 CONNECTION_LOCK (connection);
1691 if (!connection->priv->closed)
1692 set_closed_unlocked (connection, remote_peer_vanished, error);
1693 CONNECTION_UNLOCK (connection);
1696 /* ---------------------------------------------------------------------------------------------------- */
1698 /* Determines the biggest set of capabilities we can support on this connection */
1699 static GDBusCapabilityFlags
1700 get_offered_capabilities_max (GDBusConnection *connection)
1702 GDBusCapabilityFlags ret;
1703 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
1705 if (G_IS_UNIX_CONNECTION (connection->priv->stream))
1706 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
1712 initable_init (GInitable *initable,
1713 GCancellable *cancellable,
1716 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
1719 /* This method needs to be idempotent to work with the singleton
1720 * pattern. See the docs for g_initable_init(). We implement this by
1723 * Unfortunately we can't use the main lock since the on_worker_*()
1724 * callbacks above needs the lock during initialization (for message
1725 * bus connections we do a synchronous Hello() call on the bus).
1727 g_mutex_lock (connection->priv->init_lock);
1731 if (connection->priv->is_initialized)
1733 if (connection->priv->stream != NULL)
1736 g_assert (connection->priv->initialization_error != NULL);
1739 g_assert (connection->priv->initialization_error == NULL);
1741 /* The user can pass multiple (but mutally exclusive) construct
1744 * - stream (of type GIOStream)
1745 * - address (of type gchar*)
1747 * At the end of the day we end up with a non-NULL GIOStream
1748 * object in connection->priv->stream.
1750 if (connection->priv->address != NULL)
1752 g_assert (connection->priv->stream == NULL);
1754 if ((connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
1755 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
1757 g_set_error_literal (error,
1759 G_IO_ERROR_INVALID_ARGUMENT,
1760 _("Unsupported flags encountered when constructing a client-side connection"));
1764 connection->priv->stream = g_dbus_address_get_stream_sync (connection->priv->address,
1765 NULL, /* TODO: out_guid */
1767 &connection->priv->initialization_error);
1768 if (connection->priv->stream == NULL)
1771 else if (connection->priv->stream != NULL)
1777 g_assert_not_reached ();
1780 /* Authenticate the connection */
1781 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
1783 g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
1784 g_assert (connection->priv->guid != NULL);
1785 connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1786 if (!_g_dbus_auth_run_server (connection->priv->auth,
1787 connection->priv->authentication_observer,
1788 connection->priv->guid,
1789 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
1790 get_offered_capabilities_max (connection),
1791 &connection->priv->capabilities,
1792 &connection->priv->crendentials,
1794 &connection->priv->initialization_error))
1797 else if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
1799 g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
1800 g_assert (connection->priv->guid == NULL);
1801 connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1802 connection->priv->guid = _g_dbus_auth_run_client (connection->priv->auth,
1803 get_offered_capabilities_max (connection),
1804 &connection->priv->capabilities,
1806 &connection->priv->initialization_error);
1807 if (connection->priv->guid == NULL)
1811 if (connection->priv->authentication_observer != NULL)
1813 g_object_unref (connection->priv->authentication_observer);
1814 connection->priv->authentication_observer = NULL;
1817 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->priv->stream)
1819 //g_debug ("haz unix fd passing powers: %d", connection->priv->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
1823 * https://bugzilla.gnome.org/show_bug.cgi?id=616458
1827 if (G_IS_SOCKET_CONNECTION (connection->priv->stream))
1829 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->priv->stream)), FALSE);
1832 connection->priv->worker = _g_dbus_worker_new (connection->priv->stream,
1833 connection->priv->capabilities,
1834 on_worker_message_received,
1838 /* if a bus connection, invoke org.freedesktop.DBus.Hello - this is how we're getting a name */
1839 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
1841 GVariant *hello_result;
1844 hello_result = g_dbus_connection_call_sync (connection,
1845 "org.freedesktop.DBus", /* name */
1846 "/org/freedesktop/DBus", /* path */
1847 "org.freedesktop.DBus", /* interface */
1849 NULL, /* parameters */
1850 G_DBUS_CALL_FLAGS_NONE,
1852 NULL, /* TODO: cancellable */
1853 &connection->priv->initialization_error);
1854 if (hello_result == NULL)
1857 g_variant_get (hello_result, "(s)", &s);
1858 connection->priv->bus_unique_name = g_strdup (s);
1859 g_variant_unref (hello_result);
1860 //g_debug ("unique name is `%s'", connection->priv->bus_unique_name);
1863 connection->priv->is_initialized = TRUE;
1869 g_assert (connection->priv->initialization_error != NULL);
1870 g_propagate_error (error, g_error_copy (connection->priv->initialization_error));
1873 g_mutex_unlock (connection->priv->init_lock);
1879 initable_iface_init (GInitableIface *initable_iface)
1881 initable_iface->init = initable_init;
1884 /* ---------------------------------------------------------------------------------------------------- */
1887 async_init_thread (GSimpleAsyncResult *res,
1889 GCancellable *cancellable)
1891 GError *error = NULL;
1893 if (!g_initable_init (G_INITABLE (object), cancellable, &error))
1895 g_simple_async_result_set_from_error (res, error);
1896 g_error_free (error);
1901 async_initable_init_async (GAsyncInitable *initable,
1903 GCancellable *cancellable,
1904 GAsyncReadyCallback callback,
1907 GSimpleAsyncResult *res;
1909 g_return_if_fail (G_IS_INITABLE (initable));
1911 res = g_simple_async_result_new (G_OBJECT (initable), callback, user_data,
1912 async_initable_init_async);
1913 g_simple_async_result_run_in_thread (res, async_init_thread,
1914 io_priority, cancellable);
1915 g_object_unref (res);
1919 async_initable_init_finish (GAsyncInitable *initable,
1923 return TRUE; /* Errors handled by base impl */
1927 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
1929 /* We basically just want to use GIO's default implementation - though that one is
1930 * unfortunately broken, see #615111. So we copy-paste a fixed-up version.
1932 async_initable_iface->init_async = async_initable_init_async;
1933 async_initable_iface->init_finish = async_initable_init_finish;
1936 /* ---------------------------------------------------------------------------------------------------- */
1939 * g_dbus_connection_new:
1940 * @stream: A #GIOStream.
1941 * @guid: The GUID to use if a authenticating as a server or %NULL.
1942 * @flags: Flags describing how to make the connection.
1943 * @observer: A #GDBusAuthObserver or %NULL.
1944 * @cancellable: A #GCancellable or %NULL.
1945 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
1946 * @user_data: The data to pass to @callback.
1948 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
1949 * with the end represented by @stream.
1951 * If %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER is set in @flags,
1952 * @observer (if not %NULL) is used to assist in the client
1953 * authentication process.
1955 * When the operation is finished, @callback will be invoked. You can
1956 * then call g_dbus_connection_new_finish() to get the result of the
1959 * This is a asynchronous failable constructor. See
1960 * g_dbus_connection_new_sync() for the synchronous
1966 g_dbus_connection_new (GIOStream *stream,
1968 GDBusConnectionFlags flags,
1969 GDBusAuthObserver *observer,
1970 GCancellable *cancellable,
1971 GAsyncReadyCallback callback,
1974 g_return_if_fail (G_IS_IO_STREAM (stream));
1975 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
1983 "authentication-observer", observer,
1988 * g_dbus_connection_new_finish:
1989 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
1990 * @error: Return location for error or %NULL.
1992 * Finishes an operation started with g_dbus_connection_new().
1994 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
1999 g_dbus_connection_new_finish (GAsyncResult *res,
2003 GObject *source_object;
2005 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2006 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2008 source_object = g_async_result_get_source_object (res);
2009 g_assert (source_object != NULL);
2010 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2013 g_object_unref (source_object);
2015 return G_DBUS_CONNECTION (object);
2021 * g_dbus_connection_new_sync:
2022 * @stream: A #GIOStream.
2023 * @guid: The GUID to use if a authenticating as a server or %NULL.
2024 * @flags: Flags describing how to make the connection.
2025 * @observer: A #GDBusAuthObserver or %NULL.
2026 * @cancellable: A #GCancellable or %NULL.
2027 * @error: Return location for error or %NULL.
2029 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2030 * with the end represented by @stream.
2032 * If %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER is set in @flags,
2033 * @observer (if not %NULL) is used to assist in the client
2034 * authentication process.
2036 * This is a synchronous failable constructor. See
2037 * g_dbus_connection_new() for the asynchronous version.
2039 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2044 g_dbus_connection_new_sync (GIOStream *stream,
2046 GDBusConnectionFlags flags,
2047 GDBusAuthObserver *observer,
2048 GCancellable *cancellable,
2051 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2052 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2053 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2059 "authentication-observer", observer,
2063 /* ---------------------------------------------------------------------------------------------------- */
2066 * g_dbus_connection_new_for_address:
2067 * @address: A D-Bus address.
2068 * @flags: Flags describing how to make the connection.
2069 * @cancellable: A #GCancellable or %NULL.
2070 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2071 * @user_data: The data to pass to @callback.
2073 * Asynchronously connects and sets up a D-Bus client connection for
2074 * exchanging D-Bus messages with an endpoint specified by @address
2075 * which must be in the D-Bus address format.
2077 * This constructor can only be used to initiate client-side
2078 * connections - use g_dbus_connection_new() if you need to act as the
2079 * server. In particular, @flags cannot contain the
2080 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2081 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2083 * When the operation is finished, @callback will be invoked. You can
2084 * then call g_dbus_connection_new_finish() to get the result of the
2087 * This is a asynchronous failable constructor. See
2088 * g_dbus_connection_new_for_address_sync() for the synchronous
2094 g_dbus_connection_new_for_address (const gchar *address,
2095 GDBusConnectionFlags flags,
2096 GCancellable *cancellable,
2097 GAsyncReadyCallback callback,
2100 g_return_if_fail (address != NULL);
2101 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2112 * g_dbus_connection_new_for_address_finish:
2113 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2114 * @error: Return location for error or %NULL.
2116 * Finishes an operation started with g_dbus_connection_new_for_address().
2118 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2123 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2127 GObject *source_object;
2129 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2130 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2132 source_object = g_async_result_get_source_object (res);
2133 g_assert (source_object != NULL);
2134 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2137 g_object_unref (source_object);
2139 return G_DBUS_CONNECTION (object);
2145 * g_dbus_connection_new_for_address_sync:
2146 * @address: A D-Bus address.
2147 * @flags: Flags describing how to make the connection.
2148 * @cancellable: A #GCancellable or %NULL.
2149 * @error: Return location for error or %NULL.
2151 * Synchronously connects and sets up a D-Bus client connection for
2152 * exchanging D-Bus messages with an endpoint specified by @address
2153 * which must be in the D-Bus address format.
2155 * This constructor can only be used to initiate client-side
2156 * connections - use g_dbus_connection_new_sync() if you need to act
2157 * as the server. In particular, @flags cannot contain the
2158 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2159 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2161 * This is a synchronous failable constructor. See
2162 * g_dbus_connection_new_for_address() for the asynchronous version.
2164 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2169 g_dbus_connection_new_for_address_sync (const gchar *address,
2170 GDBusConnectionFlags flags,
2171 GCancellable *cancellable,
2174 g_return_val_if_fail (address != NULL, NULL);
2175 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2176 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2184 /* ---------------------------------------------------------------------------------------------------- */
2187 * g_dbus_connection_set_exit_on_close:
2188 * @connection: A #GDBusConnection.
2189 * @exit_on_close: Whether the process should be terminated
2190 * when @connection is closed by the remote peer.
2192 * Sets whether the process should be terminated when @connection is
2193 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2199 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2200 gboolean exit_on_close)
2202 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2203 connection->priv->exit_on_close = exit_on_close;
2207 * g_dbus_connection_get_exit_on_close:
2208 * @connection: A #GDBusConnection.
2210 * Gets whether the process is terminated when @connection is
2211 * closed by the remote peer. See
2212 * #GDBusConnection:exit-on-close for more details.
2214 * Returns: Whether the process is terminated when @connection is
2215 * closed by the remote peer.
2220 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2222 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2223 return connection->priv->exit_on_close;
2227 * g_dbus_connection_get_guid:
2228 * @connection: A #GDBusConnection.
2230 * The GUID of the peer performing the role of server when
2231 * authenticating. See #GDBusConnection:guid for more details.
2233 * Returns: The GUID. Do not free this string, it is owned by
2239 g_dbus_connection_get_guid (GDBusConnection *connection)
2241 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2242 return connection->priv->guid;
2246 * g_dbus_connection_get_unique_name:
2247 * @connection: A #GDBusConnection.
2249 * Gets the unique name of @connection as assigned by the message
2250 * bus. This can also be used to figure out if @connection is a
2251 * message bus connection.
2253 * Returns: The unique name or %NULL if @connection is not a message
2254 * bus connection. Do not free this string, it is owned by
2260 g_dbus_connection_get_unique_name (GDBusConnection *connection)
2262 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2263 return connection->priv->bus_unique_name;
2267 * g_dbus_connection_get_peer_credentials:
2268 * @connection: A #GDBusConnection.
2270 * Gets the credentials of the authenticated peer. This will always
2271 * return %NULL unless @connection acted as a server
2272 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
2273 * when set up and the client passed credentials as part of the
2274 * authentication process.
2276 * In a message bus setup, the message bus is always the server and
2277 * each application is a client. So this method will always return
2278 * %NULL for message bus clients.
2280 * Returns: A #GCredentials or %NULL if not available. Do not free
2281 * this object, it is owned by @connection.
2286 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
2288 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2289 return connection->priv->crendentials;
2292 /* ---------------------------------------------------------------------------------------------------- */
2294 static guint _global_filter_id = 1;
2297 * g_dbus_connection_add_filter:
2298 * @connection: A #GDBusConnection.
2299 * @filter_function: A filter function.
2300 * @user_data: User data to pass to @filter_function.
2301 * @user_data_free_func: Function to free @user_data with when filter
2302 * is removed or %NULL.
2304 * Adds a message filter. Filters are handlers that are run on all
2305 * incoming messages, prior to standard dispatch. Filters are run in
2306 * the order that they were added. The same handler can be added as a
2307 * filter more than once, in which case it will be run more than once.
2308 * Filters added during a filter callback won't be run on the message
2311 * Note that filters are run in a dedicated message handling thread so
2312 * they can't block and, generally, can't do anything but signal a
2313 * worker thread. Also note that filters are rarely needed - use API
2314 * such as g_dbus_connection_send_message_with_reply(),
2315 * g_dbus_connection_signal_subscribe() or
2316 * g_dbus_connection_call() instead.
2318 * Returns: A filter identifier that can be used with
2319 * g_dbus_connection_remove_filter().
2324 g_dbus_connection_add_filter (GDBusConnection *connection,
2325 GDBusMessageFilterFunction filter_function,
2327 GDestroyNotify user_data_free_func)
2331 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2332 g_return_val_if_fail (filter_function != NULL, 0);
2334 CONNECTION_LOCK (connection);
2335 data = g_new0 (FilterData, 1);
2336 data->id = _global_filter_id++; /* TODO: overflow etc. */
2337 data->filter_function = filter_function;
2338 data->user_data = user_data;
2339 data->user_data_free_func = user_data_free_func;
2340 g_ptr_array_add (connection->priv->filters, data);
2341 CONNECTION_UNLOCK (connection);
2346 /* only called from finalize(), removes all filters */
2348 purge_all_filters (GDBusConnection *connection)
2351 for (n = 0; n < connection->priv->filters->len; n++)
2353 FilterData *data = connection->priv->filters->pdata[n];
2354 if (data->user_data_free_func != NULL)
2355 data->user_data_free_func (data->user_data);
2361 * g_dbus_connection_remove_filter:
2362 * @connection: a #GDBusConnection
2363 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
2370 g_dbus_connection_remove_filter (GDBusConnection *connection,
2374 FilterData *to_destroy;
2376 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2378 CONNECTION_LOCK (connection);
2380 for (n = 0; n < connection->priv->filters->len; n++)
2382 FilterData *data = connection->priv->filters->pdata[n];
2383 if (data->id == filter_id)
2385 g_ptr_array_remove_index (connection->priv->filters, n);
2390 CONNECTION_UNLOCK (connection);
2392 /* do free without holding lock */
2393 if (to_destroy != NULL)
2395 if (to_destroy->user_data_free_func != NULL)
2396 to_destroy->user_data_free_func (to_destroy->user_data);
2397 g_free (to_destroy);
2401 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
2405 /* ---------------------------------------------------------------------------------------------------- */
2411 gchar *interface_name;
2415 GArray *subscribers;
2420 GDBusSignalCallback callback;
2422 GDestroyNotify user_data_free_func;
2424 GMainContext *context;
2428 signal_data_free (SignalData *data)
2430 g_free (data->rule);
2431 g_free (data->sender);
2432 g_free (data->interface_name);
2433 g_free (data->member);
2434 g_free (data->object_path);
2435 g_free (data->arg0);
2436 g_array_free (data->subscribers, TRUE);
2441 args_to_rule (const gchar *sender,
2442 const gchar *interface_name,
2443 const gchar *member,
2444 const gchar *object_path,
2449 rule = g_string_new ("type='signal'");
2451 g_string_append_printf (rule, ",sender='%s'", sender);
2452 if (interface_name != NULL)
2453 g_string_append_printf (rule, ",interface='%s'", interface_name);
2455 g_string_append_printf (rule, ",member='%s'", member);
2456 if (object_path != NULL)
2457 g_string_append_printf (rule, ",path='%s'", object_path);
2459 g_string_append_printf (rule, ",arg0='%s'", arg0);
2461 return g_string_free (rule, FALSE);
2464 static guint _global_subscriber_id = 1;
2465 static guint _global_registration_id = 1;
2466 static guint _global_subtree_registration_id = 1;
2468 /* ---------------------------------------------------------------------------------------------------- */
2470 /* must hold lock when calling */
2472 add_match_rule (GDBusConnection *connection,
2473 const gchar *match_rule)
2476 GDBusMessage *message;
2478 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2479 "/org/freedesktop/DBus", /* path */
2480 "org.freedesktop.DBus", /* interface */
2482 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2485 if (!g_dbus_connection_send_message_unlocked (connection,
2490 g_critical ("Error while sending AddMatch() message: %s", error->message);
2491 g_error_free (error);
2493 g_object_unref (message);
2496 /* ---------------------------------------------------------------------------------------------------- */
2498 /* must hold lock when calling */
2500 remove_match_rule (GDBusConnection *connection,
2501 const gchar *match_rule)
2504 GDBusMessage *message;
2506 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2507 "/org/freedesktop/DBus", /* path */
2508 "org.freedesktop.DBus", /* interface */
2510 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2513 if (!g_dbus_connection_send_message_unlocked (connection,
2518 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
2519 g_error_free (error);
2521 g_object_unref (message);
2524 /* ---------------------------------------------------------------------------------------------------- */
2527 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
2529 return g_strcmp0 (signal_data->sender, "org.freedesktop.DBus") == 0 &&
2530 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
2531 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
2532 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
2533 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
2536 /* ---------------------------------------------------------------------------------------------------- */
2539 * g_dbus_connection_signal_subscribe:
2540 * @connection: A #GDBusConnection.
2541 * @sender: Sender name to match on. Must be either <literal>org.freedesktop.DBus</literal> (for listening to signals from the message bus daemon) or a unique name or %NULL to listen from all senders.
2542 * @interface_name: D-Bus interface name to match on or %NULL to match on all interfaces.
2543 * @member: D-Bus signal name to match on or %NULL to match on all signals.
2544 * @object_path: Object path to match on or %NULL to match on all object paths.
2545 * @arg0: Contents of first string argument to match on or %NULL to match on all kinds of arguments.
2546 * @callback: Callback to invoke when there is a signal matching the requested data.
2547 * @user_data: User data to pass to @callback.
2548 * @user_data_free_func: Function to free @user_data with when subscription is removed or %NULL.
2550 * Subscribes to signals on @connection and invokes @callback with a
2551 * whenever the signal is received. Note that @callback
2552 * will be invoked in the <link
2553 * linkend="g-main-context-push-thread-default">thread-default main
2554 * loop</link> of the thread you are calling this method from.
2556 * It is considered a programming error to use this function if @connection is closed.
2558 * Note that if @sender is not <literal>org.freedesktop.DBus</literal> (for listening to signals from the
2559 * message bus daemon), then it needs to be a unique bus name or %NULL (for listening to signals from any
2560 * name) - you cannot pass a name like <literal>com.example.MyApp</literal>.
2561 * Use e.g. g_bus_watch_name() to find the unique name for the owner of the name you are interested in. Also note
2562 * that this function does not remove a subscription if @sender vanishes from the bus. You have to manually
2563 * call g_dbus_connection_signal_unsubscribe() to remove a subscription.
2565 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
2570 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
2571 const gchar *sender,
2572 const gchar *interface_name,
2573 const gchar *member,
2574 const gchar *object_path,
2576 GDBusSignalCallback callback,
2578 GDestroyNotify user_data_free_func)
2581 SignalData *signal_data;
2582 SignalSubscriber subscriber;
2583 GPtrArray *signal_data_array;
2585 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
2586 * an OOM condition. We might want to change that but that would involve making
2587 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
2588 * handle that. And there's really no sensible way of handling this short of retrying
2589 * to add the match rule... and then there's the little thing that, hey, maybe there's
2590 * a reason the bus in an OOM condition.
2592 * Doable, but not really sure it's worth it...
2595 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2596 g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
2597 g_return_val_if_fail (sender == NULL || ((strcmp (sender, "org.freedesktop.DBus") == 0 || sender[0] == ':') &&
2598 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
2599 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
2600 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
2601 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
2602 g_return_val_if_fail (callback != NULL, 0);
2604 CONNECTION_LOCK (connection);
2606 rule = args_to_rule (sender, interface_name, member, object_path, arg0);
2611 subscriber.callback = callback;
2612 subscriber.user_data = user_data;
2613 subscriber.user_data_free_func = user_data_free_func;
2614 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
2615 subscriber.context = g_main_context_get_thread_default ();
2616 if (subscriber.context != NULL)
2617 g_main_context_ref (subscriber.context);
2619 /* see if we've already have this rule */
2620 signal_data = g_hash_table_lookup (connection->priv->map_rule_to_signal_data, rule);
2621 if (signal_data != NULL)
2623 g_array_append_val (signal_data->subscribers, subscriber);
2628 signal_data = g_new0 (SignalData, 1);
2629 signal_data->rule = rule;
2630 signal_data->sender = g_strdup (sender);
2631 signal_data->interface_name = g_strdup (interface_name);
2632 signal_data->member = g_strdup (member);
2633 signal_data->object_path = g_strdup (object_path);
2634 signal_data->arg0 = g_strdup (arg0);
2635 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2636 g_array_append_val (signal_data->subscribers, subscriber);
2638 g_hash_table_insert (connection->priv->map_rule_to_signal_data,
2642 /* Add the match rule to the bus...
2644 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
2645 * always send such messages to us.
2647 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2649 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2650 add_match_rule (connection, signal_data->rule);
2654 g_hash_table_insert (connection->priv->map_id_to_signal_data,
2655 GUINT_TO_POINTER (subscriber.id),
2658 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array,
2659 signal_data->sender);
2660 if (signal_data_array == NULL)
2662 signal_data_array = g_ptr_array_new ();
2663 g_hash_table_insert (connection->priv->map_sender_to_signal_data_array,
2664 g_strdup (signal_data->sender),
2667 g_ptr_array_add (signal_data_array, signal_data);
2669 CONNECTION_UNLOCK (connection);
2671 return subscriber.id;
2674 /* ---------------------------------------------------------------------------------------------------- */
2676 /* must hold lock when calling this */
2678 unsubscribe_id_internal (GDBusConnection *connection,
2679 guint subscription_id,
2680 GArray *out_removed_subscribers)
2682 SignalData *signal_data;
2683 GPtrArray *signal_data_array;
2686 signal_data = g_hash_table_lookup (connection->priv->map_id_to_signal_data,
2687 GUINT_TO_POINTER (subscription_id));
2688 if (signal_data == NULL)
2690 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
2694 for (n = 0; n < signal_data->subscribers->len; n++)
2696 SignalSubscriber *subscriber;
2698 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
2699 if (subscriber->id != subscription_id)
2702 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_signal_data,
2703 GUINT_TO_POINTER (subscription_id)));
2704 g_array_append_val (out_removed_subscribers, *subscriber);
2705 g_array_remove_index (signal_data->subscribers, n);
2707 if (signal_data->subscribers->len == 0)
2708 g_warn_if_fail (g_hash_table_remove (connection->priv->map_rule_to_signal_data, signal_data->rule));
2710 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array,
2711 signal_data->sender);
2712 g_warn_if_fail (signal_data_array != NULL);
2713 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
2715 if (signal_data_array->len == 0)
2717 g_warn_if_fail (g_hash_table_remove (connection->priv->map_sender_to_signal_data_array, signal_data->sender));
2719 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
2720 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2722 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2723 remove_match_rule (connection, signal_data->rule);
2726 signal_data_free (signal_data);
2732 g_assert_not_reached ();
2739 * g_dbus_connection_signal_unsubscribe:
2740 * @connection: A #GDBusConnection.
2741 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
2743 * Unsubscribes from signals.
2748 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
2749 guint subscription_id)
2751 GArray *subscribers;
2754 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2756 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2758 CONNECTION_LOCK (connection);
2759 unsubscribe_id_internal (connection,
2762 CONNECTION_UNLOCK (connection);
2765 g_assert (subscribers->len == 0 || subscribers->len == 1);
2767 /* call GDestroyNotify without lock held */
2768 for (n = 0; n < subscribers->len; n++)
2770 SignalSubscriber *subscriber;
2771 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
2772 if (subscriber->user_data_free_func != NULL)
2773 subscriber->user_data_free_func (subscriber->user_data);
2774 if (subscriber->context != NULL)
2775 g_main_context_unref (subscriber->context);
2778 g_array_free (subscribers, TRUE);
2781 /* ---------------------------------------------------------------------------------------------------- */
2785 guint subscription_id;
2786 GDBusSignalCallback callback;
2788 GDBusMessage *message;
2789 GDBusConnection *connection;
2790 const gchar *sender;
2792 const gchar *interface;
2793 const gchar *member;
2796 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
2800 emit_signal_instance_in_idle_cb (gpointer data)
2802 SignalInstance *signal_instance = data;
2803 GVariant *parameters;
2804 gboolean has_subscription;
2806 parameters = g_dbus_message_get_body (signal_instance->message);
2807 if (parameters == NULL)
2809 parameters = g_variant_new ("()");
2810 g_variant_ref_sink (parameters);
2814 g_variant_ref_sink (parameters);
2818 g_debug ("in emit_signal_instance_in_idle_cb (sender=%s path=%s interface=%s member=%s params=%s)",
2819 signal_instance->sender,
2820 signal_instance->path,
2821 signal_instance->interface,
2822 signal_instance->member,
2823 g_variant_print (parameters, TRUE));
2826 /* Careful here, don't do the callback if we no longer has the subscription */
2827 CONNECTION_LOCK (signal_instance->connection);
2828 has_subscription = FALSE;
2829 if (g_hash_table_lookup (signal_instance->connection->priv->map_id_to_signal_data,
2830 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
2831 has_subscription = TRUE;
2832 CONNECTION_UNLOCK (signal_instance->connection);
2834 if (has_subscription)
2835 signal_instance->callback (signal_instance->connection,
2836 signal_instance->sender,
2837 signal_instance->path,
2838 signal_instance->interface,
2839 signal_instance->member,
2841 signal_instance->user_data);
2843 if (parameters != NULL)
2844 g_variant_unref (parameters);
2850 signal_instance_free (SignalInstance *signal_instance)
2852 g_object_unref (signal_instance->message);
2853 g_object_unref (signal_instance->connection);
2854 g_free (signal_instance);
2857 /* called in message handler thread WITH lock held */
2859 schedule_callbacks (GDBusConnection *connection,
2860 GPtrArray *signal_data_array,
2861 GDBusMessage *message,
2862 const gchar *sender)
2865 const gchar *interface;
2866 const gchar *member;
2875 interface = g_dbus_message_get_interface (message);
2876 member = g_dbus_message_get_member (message);
2877 path = g_dbus_message_get_path (message);
2878 arg0 = g_dbus_message_get_arg0 (message);
2881 g_debug ("sender = `%s'", sender);
2882 g_debug ("interface = `%s'", interface);
2883 g_debug ("member = `%s'", member);
2884 g_debug ("path = `%s'", path);
2885 g_debug ("arg0 = `%s'", arg0);
2888 /* TODO: if this is slow, then we can change signal_data_array into
2889 * map_object_path_to_signal_data_array or something.
2891 for (n = 0; n < signal_data_array->len; n++)
2893 SignalData *signal_data = signal_data_array->pdata[n];
2895 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
2898 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
2901 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
2904 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
2907 for (m = 0; m < signal_data->subscribers->len; m++)
2909 SignalSubscriber *subscriber;
2910 GSource *idle_source;
2911 SignalInstance *signal_instance;
2913 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
2915 signal_instance = g_new0 (SignalInstance, 1);
2916 signal_instance->subscription_id = subscriber->id;
2917 signal_instance->callback = subscriber->callback;
2918 signal_instance->user_data = subscriber->user_data;
2919 signal_instance->message = g_object_ref (message);
2920 signal_instance->connection = g_object_ref (connection);
2921 signal_instance->sender = sender;
2922 signal_instance->path = path;
2923 signal_instance->interface = interface;
2924 signal_instance->member = member;
2926 idle_source = g_idle_source_new ();
2927 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
2928 g_source_set_callback (idle_source,
2929 emit_signal_instance_in_idle_cb,
2931 (GDestroyNotify) signal_instance_free);
2932 g_source_attach (idle_source, subscriber->context);
2933 g_source_unref (idle_source);
2938 /* called in message handler thread with lock held */
2940 distribute_signals (GDBusConnection *connection,
2941 GDBusMessage *message)
2943 GPtrArray *signal_data_array;
2944 const gchar *sender;
2946 sender = g_dbus_message_get_sender (message);
2948 /* collect subscribers that match on sender */
2951 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array, sender);
2952 if (signal_data_array != NULL)
2953 schedule_callbacks (connection, signal_data_array, message, sender);
2956 /* collect subscribers not matching on sender */
2957 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array, "");
2958 if (signal_data_array != NULL)
2959 schedule_callbacks (connection, signal_data_array, message, sender);
2962 /* ---------------------------------------------------------------------------------------------------- */
2964 /* only called from finalize(), removes all subscriptions */
2966 purge_all_signal_subscriptions (GDBusConnection *connection)
2968 GHashTableIter iter;
2971 GArray *subscribers;
2974 ids = g_array_new (FALSE, FALSE, sizeof (guint));
2975 g_hash_table_iter_init (&iter, connection->priv->map_id_to_signal_data);
2976 while (g_hash_table_iter_next (&iter, &key, NULL))
2978 guint subscription_id = GPOINTER_TO_UINT (key);
2979 g_array_append_val (ids, subscription_id);
2982 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2983 for (n = 0; n < ids->len; n++)
2985 guint subscription_id = g_array_index (ids, guint, n);
2986 unsubscribe_id_internal (connection,
2990 g_array_free (ids, TRUE);
2992 /* call GDestroyNotify without lock held */
2993 for (n = 0; n < subscribers->len; n++)
2995 SignalSubscriber *subscriber;
2996 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
2997 if (subscriber->user_data_free_func != NULL)
2998 subscriber->user_data_free_func (subscriber->user_data);
2999 if (subscriber->context != NULL)
3000 g_main_context_unref (subscriber->context);
3003 g_array_free (subscribers, TRUE);
3006 /* ---------------------------------------------------------------------------------------------------- */
3008 struct ExportedObject
3011 GDBusConnection *connection;
3013 /* maps gchar* -> ExportedInterface* */
3014 GHashTable *map_if_name_to_ei;
3017 /* only called with lock held */
3019 exported_object_free (ExportedObject *eo)
3021 g_free (eo->object_path);
3022 g_hash_table_unref (eo->map_if_name_to_ei);
3031 gchar *interface_name;
3032 const GDBusInterfaceVTable *vtable;
3033 const GDBusInterfaceInfo *introspection_data;
3035 GMainContext *context;
3037 GDestroyNotify user_data_free_func;
3038 } ExportedInterface;
3040 /* called with lock held */
3042 exported_interface_free (ExportedInterface *ei)
3044 if (ei->user_data_free_func != NULL)
3045 /* TODO: push to thread-default mainloop */
3046 ei->user_data_free_func (ei->user_data);
3048 if (ei->context != NULL)
3049 g_main_context_unref (ei->context);
3051 g_free (ei->interface_name);
3055 /* ---------------------------------------------------------------------------------------------------- */
3059 GDBusConnection *connection;
3060 GDBusMessage *message;
3062 const char *property_name;
3063 const GDBusInterfaceVTable *vtable;
3064 const GDBusInterfaceInfo *interface_info;
3065 const GDBusPropertyInfo *property_info;
3069 property_data_free (PropertyData *data)
3071 g_object_unref (data->connection);
3072 g_object_unref (data->message);
3076 /* called in thread where object was registered - no locks held */
3078 invoke_get_property_in_idle_cb (gpointer _data)
3080 PropertyData *data = _data;
3083 GDBusMessage *reply;
3086 value = data->vtable->get_property (data->connection,
3087 g_dbus_message_get_sender (data->message),
3088 g_dbus_message_get_path (data->message),
3089 data->interface_info->name,
3090 data->property_name,
3097 g_assert_no_error (error);
3099 g_variant_ref_sink (value);
3100 reply = g_dbus_message_new_method_reply (data->message);
3101 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
3102 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3103 g_variant_unref (value);
3104 g_object_unref (reply);
3108 gchar *dbus_error_name;
3110 g_assert (error != NULL);
3112 dbus_error_name = g_dbus_error_encode_gerror (error);
3113 reply = g_dbus_message_new_method_error_literal (data->message,
3116 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3117 g_free (dbus_error_name);
3118 g_error_free (error);
3119 g_object_unref (reply);
3125 /* called in thread where object was registered - no locks held */
3127 invoke_set_property_in_idle_cb (gpointer _data)
3129 PropertyData *data = _data;
3131 GDBusMessage *reply;
3137 g_variant_get (g_dbus_message_get_body (data->message),
3143 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
3144 * of the given value is wrong
3146 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
3148 reply = g_dbus_message_new_method_error (data->message,
3149 "org.freedesktop.DBus.Error.InvalidArgs",
3150 _("Error setting property `%s': Expected type `%s' but got `%s'"),
3151 data->property_info->name,
3152 data->property_info->signature,
3153 g_variant_get_type_string (value));
3157 if (!data->vtable->set_property (data->connection,
3158 g_dbus_message_get_sender (data->message),
3159 g_dbus_message_get_path (data->message),
3160 data->interface_info->name,
3161 data->property_name,
3166 gchar *dbus_error_name;
3167 g_assert (error != NULL);
3168 dbus_error_name = g_dbus_error_encode_gerror (error);
3169 reply = g_dbus_message_new_method_error_literal (data->message,
3172 g_free (dbus_error_name);
3173 g_error_free (error);
3177 reply = g_dbus_message_new_method_reply (data->message);
3181 g_assert (reply != NULL);
3182 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3183 g_object_unref (reply);
3188 /* called with lock held */
3190 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
3191 GDBusMessage *message,
3193 const GDBusInterfaceInfo *introspection_data,
3194 const GDBusInterfaceVTable *vtable,
3195 GMainContext *main_context,
3199 const char *interface_name;
3200 const char *property_name;
3201 const GDBusPropertyInfo *property_info;
3202 GSource *idle_source;
3203 PropertyData *property_data;
3204 GDBusMessage *reply;
3209 g_variant_get (g_dbus_message_get_body (message),
3214 g_variant_get (g_dbus_message_get_body (message),
3223 if (vtable == NULL || vtable->get_property == NULL)
3228 if (vtable == NULL || vtable->set_property == NULL)
3232 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
3234 property_info = NULL;
3236 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3237 property_info = g_dbus_interface_info_lookup_property (introspection_data, property_name);
3238 if (property_info == NULL)
3240 reply = g_dbus_message_new_method_error (message,
3241 "org.freedesktop.DBus.Error.InvalidArgs",
3242 _("No such property `%s'"),
3244 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3245 g_object_unref (reply);
3250 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3252 reply = g_dbus_message_new_method_error (message,
3253 "org.freedesktop.DBus.Error.InvalidArgs",
3254 _("Property `%s' is not readable"),
3256 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3257 g_object_unref (reply);
3261 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
3263 reply = g_dbus_message_new_method_error (message,
3264 "org.freedesktop.DBus.Error.InvalidArgs",
3265 _("Property `%s' is not writable"),
3267 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3268 g_object_unref (reply);
3273 /* ok, got the property info - call user code in an idle handler */
3274 property_data = g_new0 (PropertyData, 1);
3275 property_data->connection = g_object_ref (connection);
3276 property_data->message = g_object_ref (message);
3277 property_data->user_data = user_data;
3278 property_data->property_name = property_name;
3279 property_data->vtable = vtable;
3280 property_data->interface_info = introspection_data;
3281 property_data->property_info = property_info;
3283 idle_source = g_idle_source_new ();
3284 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3285 g_source_set_callback (idle_source,
3286 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
3288 (GDestroyNotify) property_data_free);
3289 g_source_attach (idle_source, main_context);
3290 g_source_unref (idle_source);
3298 /* called with lock held */
3300 handle_getset_property (GDBusConnection *connection,
3302 GDBusMessage *message,
3305 ExportedInterface *ei;
3307 const char *interface_name;
3308 const char *property_name;
3313 g_variant_get (g_dbus_message_get_body (message),
3318 g_variant_get (g_dbus_message_get_body (message),
3324 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3325 * no such interface registered
3327 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3330 GDBusMessage *reply;
3331 reply = g_dbus_message_new_method_error (message,
3332 "org.freedesktop.DBus.Error.InvalidArgs",
3333 _("No such interface `%s'"),
3335 g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3336 g_object_unref (reply);
3341 handled = validate_and_maybe_schedule_property_getset (eo->connection,
3344 ei->introspection_data,
3352 /* ---------------------------------------------------------------------------------------------------- */
3356 GDBusConnection *connection;
3357 GDBusMessage *message;
3359 const GDBusInterfaceVTable *vtable;
3360 const GDBusInterfaceInfo *interface_info;
3361 } PropertyGetAllData;
3364 property_get_all_data_free (PropertyData *data)
3366 g_object_unref (data->connection);
3367 g_object_unref (data->message);
3371 /* called in thread where object was registered - no locks held */
3373 invoke_get_all_properties_in_idle_cb (gpointer _data)
3375 PropertyGetAllData *data = _data;
3376 GVariantBuilder *builder;
3380 GDBusMessage *reply;
3385 /* TODO: Right now we never fail this call - we just omit values if
3386 * a get_property() call is failing.
3388 * We could fail the whole call if just a single get_property() call
3389 * returns an error. We need clarification in the D-Bus spec about this.
3391 builder = g_variant_builder_new (G_VARIANT_TYPE_ARRAY);
3392 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
3394 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
3397 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3400 value = data->vtable->get_property (data->connection,
3401 g_dbus_message_get_sender (data->message),
3402 g_dbus_message_get_path (data->message),
3403 data->interface_info->name,
3404 property_info->name,
3411 g_variant_ref_sink (value);
3412 g_variant_builder_add (builder,
3414 property_info->name,
3416 g_variant_unref (value);
3418 result = g_variant_builder_end (builder);
3420 builder = g_variant_builder_new (G_VARIANT_TYPE_TUPLE);
3421 g_variant_builder_add_value (builder, result); /* steals result since result is floating */
3422 packed = g_variant_builder_end (builder);
3424 reply = g_dbus_message_new_method_reply (data->message);
3425 g_dbus_message_set_body (reply, packed);
3426 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3427 g_object_unref (reply);
3432 /* called with lock held */
3434 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
3435 GDBusMessage *message,
3436 const GDBusInterfaceInfo *introspection_data,
3437 const GDBusInterfaceVTable *vtable,
3438 GMainContext *main_context,
3442 const char *interface_name;
3443 GSource *idle_source;
3444 PropertyGetAllData *property_get_all_data;
3448 g_variant_get (g_dbus_message_get_body (message),
3452 if (vtable == NULL || vtable->get_property == NULL)
3455 /* ok, got the property info - call user in an idle handler */
3456 property_get_all_data = g_new0 (PropertyGetAllData, 1);
3457 property_get_all_data->connection = g_object_ref (connection);
3458 property_get_all_data->message = g_object_ref (message);
3459 property_get_all_data->user_data = user_data;
3460 property_get_all_data->vtable = vtable;
3461 property_get_all_data->interface_info = introspection_data;
3463 idle_source = g_idle_source_new ();
3464 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3465 g_source_set_callback (idle_source,
3466 invoke_get_all_properties_in_idle_cb,
3467 property_get_all_data,
3468 (GDestroyNotify) property_get_all_data_free);
3469 g_source_attach (idle_source, main_context);
3470 g_source_unref (idle_source);
3478 /* called with lock held */
3480 handle_get_all_properties (GDBusConnection *connection,
3482 GDBusMessage *message)
3484 ExportedInterface *ei;
3486 const char *interface_name;
3490 g_variant_get (g_dbus_message_get_body (message),
3494 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3495 * no such interface registered
3497 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3500 GDBusMessage *reply;
3501 reply = g_dbus_message_new_method_error (message,
3502 "org.freedesktop.DBus.Error.InvalidArgs",
3503 _("No such interface"),
3505 g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3506 g_object_unref (reply);
3511 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
3513 ei->introspection_data,
3521 /* ---------------------------------------------------------------------------------------------------- */
3523 static const gchar introspect_header[] =
3524 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
3525 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
3526 "<!-- GDBus " PACKAGE_VERSION " -->\n"
3529 static const gchar introspect_tail[] =
3532 static const gchar introspect_standard_interfaces[] =
3533 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
3534 " <method name=\"Get\">\n"
3535 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3536 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3537 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
3539 " <method name=\"GetAll\">\n"
3540 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3541 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
3543 " <method name=\"Set\">\n"
3544 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3545 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3546 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
3548 " <signal name=\"PropertiesChanged\">\n"
3549 " <arg type=\"s\" name=\"interface_name\"/>\n"
3550 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
3551 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
3554 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
3555 " <method name=\"Introspect\">\n"
3556 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
3559 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
3560 " <method name=\"Ping\"/>\n"
3561 " <method name=\"GetMachineId\">\n"
3562 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
3567 introspect_append_header (GString *s)
3569 g_string_append (s, introspect_header);
3573 introspect_append_standard_interfaces (GString *s)
3575 g_string_append (s, introspect_standard_interfaces);
3579 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
3581 if (g_str_has_prefix (object_path, path) && strlen (object_path) >= path_len)
3587 begin = object_path + path_len;
3588 end = strchr (begin, '/');
3591 s = g_strndup (begin, end - begin);
3593 s = g_strdup (begin);
3595 if (g_hash_table_lookup (set, s) == NULL)
3596 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
3602 /* TODO: we want a nicer public interface for this */
3604 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
3609 GHashTableIter hash_iter;
3610 const gchar *object_path;
3616 CONNECTION_ENSURE_LOCK (connection);
3618 path_len = strlen (path);
3622 set = g_hash_table_new (g_str_hash, g_str_equal);
3624 g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_eo);
3625 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3626 maybe_add_path (path, path_len, object_path, set);
3628 g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_es);
3629 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3630 maybe_add_path (path, path_len, object_path, set);
3632 p = g_ptr_array_new ();
3633 keys = g_hash_table_get_keys (set);
3634 for (l = keys; l != NULL; l = l->next)
3635 g_ptr_array_add (p, l->data);
3636 g_hash_table_unref (set);
3639 g_ptr_array_add (p, NULL);
3640 ret = (gchar **) g_ptr_array_free (p, FALSE);
3645 g_dbus_connection_list_registered (GDBusConnection *connection,
3649 CONNECTION_LOCK (connection);
3650 ret = g_dbus_connection_list_registered_unlocked (connection, path);
3651 CONNECTION_UNLOCK (connection);
3655 /* called in message handler thread with lock held */
3657 handle_introspect (GDBusConnection *connection,
3659 GDBusMessage *message)
3663 GDBusMessage *reply;
3664 GHashTableIter hash_iter;
3665 ExportedInterface *ei;
3668 /* first the header with the standard interfaces */
3669 s = g_string_sized_new (sizeof (introspect_header) +
3670 sizeof (introspect_standard_interfaces) +
3671 sizeof (introspect_tail));
3672 introspect_append_header (s);
3673 introspect_append_standard_interfaces (s);
3675 /* then include the registered interfaces */
3676 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
3677 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
3678 g_dbus_interface_info_generate_xml (ei->introspection_data, 2, s);
3680 /* finally include nodes registered below us */
3681 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
3682 for (n = 0; registered != NULL && registered[n] != NULL; n++)
3683 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
3684 g_strfreev (registered);
3685 g_string_append (s, introspect_tail);
3687 reply = g_dbus_message_new_method_reply (message);
3688 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
3689 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3690 g_object_unref (reply);
3691 g_string_free (s, TRUE);
3696 /* called in thread where object was registered - no locks held */
3698 call_in_idle_cb (gpointer user_data)
3700 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
3701 GDBusInterfaceVTable *vtable;
3703 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
3704 g_assert (vtable != NULL && vtable->method_call != NULL);
3706 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
3707 g_dbus_method_invocation_get_sender (invocation),
3708 g_dbus_method_invocation_get_object_path (invocation),
3709 g_dbus_method_invocation_get_interface_name (invocation),
3710 g_dbus_method_invocation_get_method_name (invocation),
3711 g_dbus_method_invocation_get_parameters (invocation),
3712 g_object_ref (invocation),
3713 g_dbus_method_invocation_get_user_data (invocation));
3718 /* called in message handler thread with lock held */
3720 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
3721 GDBusMessage *message,
3722 const GDBusInterfaceInfo *introspection_data,
3723 const GDBusInterfaceVTable *vtable,
3724 GMainContext *main_context,
3727 GDBusMethodInvocation *invocation;
3728 const GDBusMethodInfo *method_info;
3729 GDBusMessage *reply;
3730 GVariant *parameters;
3731 GSource *idle_source;
3733 gchar *in_signature;
3737 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3738 method_info = g_dbus_interface_info_lookup_method (introspection_data, g_dbus_message_get_member (message));
3740 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
3741 * error to the caller
3743 if (method_info == NULL)
3745 reply = g_dbus_message_new_method_error (message,
3746 "org.freedesktop.DBus.Error.UnknownMethod",
3747 _("No such method `%s'"),
3748 g_dbus_message_get_member (message));
3749 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3750 g_object_unref (reply);
3755 /* Check that the incoming args are of the right type - if they are not, return
3756 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
3758 * TODO: might also be worth caching the combined signature.
3760 in_signature = _g_dbus_compute_complete_signature (method_info->in_args, FALSE);
3761 if (g_strcmp0 (g_dbus_message_get_signature (message), in_signature) != 0)
3763 reply = g_dbus_message_new_method_error (message,
3764 "org.freedesktop.DBus.Error.InvalidArgs",
3765 _("Signature of message, `%s', does not match expected signature `%s'"),
3766 g_dbus_message_get_signature (message),
3768 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3769 g_object_unref (reply);
3770 g_free (in_signature);
3774 g_free (in_signature);
3776 parameters = g_dbus_message_get_body (message);
3777 if (parameters == NULL)
3779 parameters = g_variant_new ("()");
3780 g_variant_ref_sink (parameters);
3784 g_variant_ref (parameters);
3787 /* schedule the call in idle */
3788 invocation = g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
3789 g_dbus_message_get_path (message),
3790 g_dbus_message_get_interface (message),
3791 g_dbus_message_get_member (message),
3797 g_variant_unref (parameters);
3798 g_object_set_data (G_OBJECT (invocation),
3799 "g-dbus-interface-vtable",
3802 idle_source = g_idle_source_new ();
3803 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3804 g_source_set_callback (idle_source,
3808 g_source_attach (idle_source, main_context);
3809 g_source_unref (idle_source);
3817 /* ---------------------------------------------------------------------------------------------------- */
3819 /* called in message handler thread with lock held */
3821 obj_message_func (GDBusConnection *connection,
3823 GDBusMessage *message)
3825 const gchar *interface_name;
3826 const gchar *member;
3827 const gchar *signature;
3832 interface_name = g_dbus_message_get_interface (message);
3833 member = g_dbus_message_get_member (message);
3834 signature = g_dbus_message_get_signature (message);
3836 /* see if we have an interface for handling this call */
3837 if (interface_name != NULL)
3839 ExportedInterface *ei;
3840 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3843 /* we do - invoke the handler in idle in the right thread */
3845 /* handle no vtable or handler being present */
3846 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
3849 handled = validate_and_maybe_schedule_method_call (connection,
3851 ei->introspection_data,
3859 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
3860 g_strcmp0 (member, "Introspect") == 0 &&
3861 g_strcmp0 (signature, "") == 0)
3863 handled = handle_introspect (connection, eo, message);
3866 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3867 g_strcmp0 (member, "Get") == 0 &&
3868 g_strcmp0 (signature, "ss") == 0)
3870 handled = handle_getset_property (connection, eo, message, TRUE);
3873 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3874 g_strcmp0 (member, "Set") == 0 &&
3875 g_strcmp0 (signature, "ssv") == 0)
3877 handled = handle_getset_property (connection, eo, message, FALSE);
3880 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3881 g_strcmp0 (member, "GetAll") == 0 &&
3882 g_strcmp0 (signature, "s") == 0)
3884 handled = handle_get_all_properties (connection, eo, message);
3893 * g_dbus_connection_register_object:
3894 * @connection: A #GDBusConnection.
3895 * @object_path: The object path to register at.
3896 * @introspection_data: Introspection data for the interface.
3897 * @vtable: A #GDBusInterfaceVTable to call into or %NULL.
3898 * @user_data: Data to pass to functions in @vtable.
3899 * @user_data_free_func: Function to call when the object path is unregistered.
3900 * @error: Return location for error or %NULL.
3902 * Registers callbacks for exported objects at @object_path with the
3903 * D-Bus interface that is described in @introspection_data.
3905 * Calls to functions in @vtable (and @user_data_free_func) will
3906 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
3907 * loop</link> of the thread you are calling this method from.
3909 * Note that all #GVariant values passed to functions in @vtable will match
3910 * the signature given in @introspection_data - if a remote caller passes
3911 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
3912 * is returned to the remote caller.
3914 * Additionally, if the remote caller attempts to invoke methods or
3915 * access properties not mentioned in @introspection_data the
3916 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
3917 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
3918 * are returned to the caller.
3920 * It is considered a programming error if the
3921 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
3922 * #GVariant of incorrect type.
3924 * If an existing callback is already registered at @object_path and
3925 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
3927 * GDBus automatically implements the standard D-Bus interfaces
3928 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
3929 * and org.freedesktop.Peer, so you don't have to implement those for
3930 * the objects you export. You <emphasis>can</emphasis> implement
3931 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
3932 * and setting of properties asynchronously.
3934 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
3936 * Returns: 0 if @error is set, otherwise a registration id (never 0)
3937 * that can be used with g_dbus_connection_unregister_object() .
3942 g_dbus_connection_register_object (GDBusConnection *connection,
3943 const gchar *object_path,
3944 const GDBusInterfaceInfo *introspection_data,
3945 const GDBusInterfaceVTable *vtable,
3947 GDestroyNotify user_data_free_func,
3951 ExportedInterface *ei;
3954 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3955 g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
3956 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
3957 g_return_val_if_fail (introspection_data != NULL, 0);
3958 g_return_val_if_fail (g_dbus_is_interface_name (introspection_data->name), 0);
3959 g_return_val_if_fail (error == NULL || *error == NULL, 0);
3963 CONNECTION_LOCK (connection);
3965 eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
3968 eo = g_new0 (ExportedObject, 1);
3969 eo->object_path = g_strdup (object_path);
3970 eo->connection = connection;
3971 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
3974 (GDestroyNotify) exported_interface_free);
3975 g_hash_table_insert (connection->priv->map_object_path_to_eo, eo->object_path, eo);
3978 ei = g_hash_table_lookup (eo->map_if_name_to_ei, introspection_data->name);
3984 _("An object is already exported for the interface %s at %s"),
3985 introspection_data->name,
3990 ei = g_new0 (ExportedInterface, 1);
3991 ei->id = _global_registration_id++; /* TODO: overflow etc. */
3993 ei->user_data = user_data;
3994 ei->user_data_free_func = user_data_free_func;
3995 ei->vtable = vtable;
3996 ei->introspection_data = introspection_data;
3997 ei->interface_name = g_strdup (introspection_data->name);
3998 ei->context = g_main_context_get_thread_default ();
3999 if (ei->context != NULL)
4000 g_main_context_ref (ei->context);
4002 g_hash_table_insert (eo->map_if_name_to_ei,
4003 (gpointer) ei->interface_name,
4005 g_hash_table_insert (connection->priv->map_id_to_ei,
4006 GUINT_TO_POINTER (ei->id),
4012 CONNECTION_UNLOCK (connection);
4018 * g_dbus_connection_unregister_object:
4019 * @connection: A #GDBusConnection.
4020 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
4022 * Unregisters an object.
4024 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
4029 g_dbus_connection_unregister_object (GDBusConnection *connection,
4030 guint registration_id)
4032 ExportedInterface *ei;
4036 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4040 CONNECTION_LOCK (connection);
4042 ei = g_hash_table_lookup (connection->priv->map_id_to_ei,
4043 GUINT_TO_POINTER (registration_id));
4049 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
4050 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
4051 /* unregister object path if we have no more exported interfaces */
4052 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
4053 g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_eo,
4059 CONNECTION_UNLOCK (connection);
4064 /* ---------------------------------------------------------------------------------------------------- */
4067 * g_dbus_connection_emit_signal:
4068 * @connection: A #GDBusConnection.
4069 * @destination_bus_name: The unique bus name for the destination for the signal or %NULL to emit to all listeners.
4070 * @object_path: Path of remote object.
4071 * @interface_name: D-Bus interface to emit a signal on.
4072 * @signal_name: The name of the signal to emit.
4073 * @parameters: A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
4074 * @error: Return location for error or %NULL.
4078 * This can only fail if @parameters is not compatible with the D-Bus protocol.
4080 * Returns: %TRUE unless @error is set.
4085 g_dbus_connection_emit_signal (GDBusConnection *connection,
4086 const gchar *destination_bus_name,
4087 const gchar *object_path,
4088 const gchar *interface_name,
4089 const gchar *signal_name,
4090 GVariant *parameters,
4093 GDBusMessage *message;
4099 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4100 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
4101 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
4102 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
4103 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
4104 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
4106 message = g_dbus_message_new_signal (object_path,
4110 if (destination_bus_name != NULL)
4111 g_dbus_message_set_header (message,
4112 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
4113 g_variant_new_string (destination_bus_name));
4115 if (parameters != NULL)
4116 g_dbus_message_set_body (message, parameters);
4118 ret = g_dbus_connection_send_message (connection, message, NULL, error);
4119 g_object_unref (message);
4125 add_call_flags (GDBusMessage *message,
4126 GDBusCallFlags flags)
4128 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
4129 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
4133 * g_dbus_connection_call:
4134 * @connection: A #GDBusConnection.
4135 * @bus_name: A unique or well-known bus name or %NULL if @connection is not a message bus connection.
4136 * @object_path: Path of remote object.
4137 * @interface_name: D-Bus interface to invoke method on.
4138 * @method_name: The name of the method to invoke.
4139 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4140 * @flags: Flags from the #GDBusCallFlags enumeration.
4141 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4142 * @cancellable: A #GCancellable or %NULL.
4143 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
4144 * care about the result of the method invocation.
4145 * @user_data: The data to pass to @callback.
4147 * Asynchronously invokes the @method_name method on the
4148 * @interface_name D-Bus interface on the remote object at
4149 * @object_path owned by @bus_name.
4151 * If @connection is closed then the operation will fail with
4152 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
4153 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
4154 * not compatible with the D-Bus protocol, the operation fails with
4155 * %G_IO_ERROR_INVALID_ARGUMENT.
4157 * If the @parameters #GVariant is floating, it is consumed. This allows
4158 * convenient 'inline' use of g_variant_new(), e.g.:
4160 * g_dbus_connection_call (connection,
4161 * "org.freedesktop.StringThings",
4162 * "/org/freedesktop/StringThings",
4163 * "org.freedesktop.StringThings",
4165 * g_variant_new ("(ss)",
4168 * G_DBUS_CALL_FLAGS_NONE,
4171 * (GAsyncReadyCallback) two_strings_done,
4175 * This is an asynchronous method. When the operation is finished, @callback will be invoked
4176 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
4177 * of the thread you are calling this method from. You can then call
4178 * g_dbus_connection_call_finish() to get the result of the operation.
4179 * See g_dbus_connection_call_sync() for the synchronous version of this
4185 g_dbus_connection_call (GDBusConnection *connection,
4186 const gchar *bus_name,
4187 const gchar *object_path,
4188 const gchar *interface_name,
4189 const gchar *method_name,
4190 GVariant *parameters,
4191 GDBusCallFlags flags,
4193 GCancellable *cancellable,
4194 GAsyncReadyCallback callback,
4197 GDBusMessage *message;
4199 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4200 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
4201 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
4202 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
4203 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
4204 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
4205 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
4207 message = g_dbus_message_new_method_call (bus_name,
4211 add_call_flags (message, flags);
4212 if (parameters != NULL)
4213 g_dbus_message_set_body (message, parameters);
4215 g_dbus_connection_send_message_with_reply (connection,
4218 NULL, /* volatile guint32 *out_serial */
4223 if (message != NULL)
4224 g_object_unref (message);
4228 decode_method_reply (GDBusMessage *reply,
4234 switch (g_dbus_message_get_message_type (reply))
4236 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
4237 result = g_dbus_message_get_body (reply);
4240 result = g_variant_new ("()");
4241 g_variant_ref_sink (result);
4245 g_variant_ref (result);
4249 case G_DBUS_MESSAGE_TYPE_ERROR:
4250 g_dbus_message_to_gerror (reply, error);
4254 g_assert_not_reached ();
4262 * g_dbus_connection_call_finish:
4263 * @connection: A #GDBusConnection.
4264 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
4265 * @error: Return location for error or %NULL.
4267 * Finishes an operation started with g_dbus_connection_call().
4269 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4270 * return values. Free with g_variant_unref().
4275 g_dbus_connection_call_finish (GDBusConnection *connection,
4279 GDBusMessage *reply;
4282 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4283 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
4284 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4288 reply = g_dbus_connection_send_message_with_reply_finish (connection, res, error);
4292 result = decode_method_reply (reply, error);
4294 g_object_unref (reply);
4300 /* ---------------------------------------------------------------------------------------------------- */
4303 * g_dbus_connection_call_sync:
4304 * @connection: A #GDBusConnection.
4305 * @bus_name: A unique or well-known bus name.
4306 * @object_path: Path of remote object.
4307 * @interface_name: D-Bus interface to invoke method on.
4308 * @method_name: The name of the method to invoke.
4309 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4310 * @flags: Flags from the #GDBusCallFlags enumeration.
4311 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4312 * @cancellable: A #GCancellable or %NULL.
4313 * @error: Return location for error or %NULL.
4315 * Synchronously invokes the @method_name method on the
4316 * @interface_name D-Bus interface on the remote object at
4317 * @object_path owned by @bus_name.
4319 * If @connection is closed then the operation will fail with
4320 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
4321 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
4322 * contains a value not compatible with the D-Bus protocol, the operation
4323 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
4325 * If the @parameters #GVariant is floating, it is consumed.
4326 * This allows convenient 'inline' use of g_variant_new(), e.g.:
4328 * g_dbus_connection_call_sync (connection,
4329 * "org.freedesktop.StringThings",
4330 * "/org/freedesktop/StringThings",
4331 * "org.freedesktop.StringThings",
4333 * g_variant_new ("(ss)",
4336 * G_DBUS_CALL_FLAGS_NONE,
4342 * The calling thread is blocked until a reply is received. See
4343 * g_dbus_connection_call() for the asynchronous version of
4346 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4347 * return values. Free with g_variant_unref().
4352 g_dbus_connection_call_sync (GDBusConnection *connection,
4353 const gchar *bus_name,
4354 const gchar *object_path,
4355 const gchar *interface_name,
4356 const gchar *method_name,
4357 GVariant *parameters,
4358 GDBusCallFlags flags,
4360 GCancellable *cancellable,
4363 GDBusMessage *message;
4364 GDBusMessage *reply;
4371 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4372 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
4373 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
4374 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
4375 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
4376 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
4377 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
4379 message = g_dbus_message_new_method_call (bus_name,
4383 add_call_flags (message, flags);
4384 if (parameters != NULL)
4385 g_dbus_message_set_body (message, parameters);
4387 reply = g_dbus_connection_send_message_with_reply_sync (connection,
4390 NULL, /* volatile guint32 *out_serial */
4397 result = decode_method_reply (reply, error);
4400 if (message != NULL)
4401 g_object_unref (message);
4403 g_object_unref (reply);
4408 /* ---------------------------------------------------------------------------------------------------- */
4410 struct ExportedSubtree
4414 GDBusConnection *connection;
4415 const GDBusSubtreeVTable *vtable;
4416 GDBusSubtreeFlags flags;
4418 GMainContext *context;
4420 GDestroyNotify user_data_free_func;
4424 exported_subtree_free (ExportedSubtree *es)
4426 if (es->user_data_free_func != NULL)
4427 /* TODO: push to thread-default mainloop */
4428 es->user_data_free_func (es->user_data);
4430 if (es->context != NULL)
4431 g_main_context_unref (es->context);
4433 g_free (es->object_path);
4437 /* called without lock held */
4439 handle_subtree_introspect (GDBusConnection *connection,
4440 ExportedSubtree *es,
4441 GDBusMessage *message)
4445 GDBusMessage *reply;
4448 const gchar *sender;
4449 const gchar *requested_object_path;
4450 const gchar *requested_node;
4451 GPtrArray *interfaces;
4453 gchar **subnode_paths;
4457 requested_object_path = g_dbus_message_get_path (message);
4458 sender = g_dbus_message_get_sender (message);
4459 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4461 s = g_string_new (NULL);
4462 introspect_append_header (s);
4464 /* Strictly we don't need the children in dynamic mode, but we avoid the
4465 * conditionals to preserve code clarity
4467 children = es->vtable->enumerate (es->connection,
4474 requested_node = strrchr (requested_object_path, '/') + 1;
4476 /* Assert existence of object if we are not dynamic */
4477 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4478 !_g_strv_has_string ((const gchar * const *) children, requested_node))
4483 requested_node = "/";
4486 interfaces = es->vtable->introspect (es->connection,
4491 if (interfaces != NULL)
4493 if (interfaces->len > 0)
4495 /* we're in business */
4496 introspect_append_standard_interfaces (s);
4498 for (n = 0; n < interfaces->len; n++)
4500 const GDBusInterfaceInfo *interface_info = interfaces->pdata[n];
4501 g_dbus_interface_info_generate_xml (interface_info, 2, s);
4504 g_ptr_array_unref (interfaces);
4507 /* then include <node> entries from the Subtree for the root */
4510 for (n = 0; children != NULL && children[n] != NULL; n++)
4511 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
4514 /* finally include nodes registered below us */
4515 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
4516 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
4517 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
4518 g_strfreev (subnode_paths);
4520 g_string_append (s, "</node>\n");
4522 reply = g_dbus_message_new_method_reply (message);
4523 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4524 g_dbus_connection_send_message (connection, reply, NULL, NULL);
4525 g_object_unref (reply);
4530 g_string_free (s, TRUE);
4531 g_strfreev (children);
4535 /* called without lock held */
4537 handle_subtree_method_invocation (GDBusConnection *connection,
4538 ExportedSubtree *es,
4539 GDBusMessage *message)
4542 const gchar *sender;
4543 const gchar *interface_name;
4544 const gchar *member;
4545 const gchar *signature;
4546 const gchar *requested_object_path;
4547 const gchar *requested_node;
4550 const GDBusInterfaceInfo *introspection_data;
4551 const GDBusInterfaceVTable *interface_vtable;
4552 gpointer interface_user_data;
4554 GPtrArray *interfaces;
4555 gboolean is_property_get;
4556 gboolean is_property_set;
4557 gboolean is_property_get_all;
4562 requested_object_path = g_dbus_message_get_path (message);
4563 sender = g_dbus_message_get_sender (message);
4564 interface_name = g_dbus_message_get_interface (message);
4565 member = g_dbus_message_get_member (message);
4566 signature = g_dbus_message_get_signature (message);
4567 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4569 is_property_get = FALSE;
4570 is_property_set = FALSE;
4571 is_property_get_all = FALSE;
4572 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
4574 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
4575 is_property_get = TRUE;
4576 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
4577 is_property_set = TRUE;
4578 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
4579 is_property_get_all = TRUE;
4582 children = es->vtable->enumerate (es->connection,
4589 requested_node = strrchr (requested_object_path, '/') + 1;
4591 /* If not dynamic, skip if requested node is not part of children */
4592 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4593 !_g_strv_has_string ((const gchar * const *) children, requested_node))
4598 requested_node = "/";
4601 /* get introspection data for the node */
4602 interfaces = es->vtable->introspect (es->connection,
4604 requested_object_path,
4607 g_assert (interfaces != NULL);
4608 introspection_data = NULL;
4609 for (n = 0; n < interfaces->len; n++)
4611 const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4612 if (g_strcmp0 (id_n->name, interface_name) == 0)
4613 introspection_data = id_n;
4616 /* dispatch the call if the user wants to handle it */
4617 if (introspection_data != NULL)
4619 /* figure out where to dispatch the method call */
4620 interface_user_data = NULL;
4621 interface_vtable = es->vtable->dispatch (es->connection,
4626 &interface_user_data,
4628 if (interface_vtable == NULL)
4631 CONNECTION_LOCK (connection);
4632 handled = validate_and_maybe_schedule_method_call (es->connection,
4637 interface_user_data);
4638 CONNECTION_UNLOCK (connection);
4640 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
4641 else if (is_property_get || is_property_set || is_property_get_all)
4643 if (is_property_get)
4644 g_variant_get (g_dbus_message_get_body (message), "(ss)", &interface_name, NULL);
4645 else if (is_property_set)
4646 g_variant_get (g_dbus_message_get_body (message), "(ssv)", &interface_name, NULL, NULL);
4647 else if (is_property_get_all)
4648 g_variant_get (g_dbus_message_get_body (message), "(s)", &interface_name, NULL, NULL);
4650 g_assert_not_reached ();
4652 /* see if the object supports this interface at all */
4653 for (n = 0; n < interfaces->len; n++)
4655 const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4656 if (g_strcmp0 (id_n->name, interface_name) == 0)
4657 introspection_data = id_n;
4660 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
4661 * claims it won't support the interface
4663 if (introspection_data == NULL)
4665 GDBusMessage *reply;
4666 reply = g_dbus_message_new_method_error (message,
4667 "org.freedesktop.DBus.Error.InvalidArgs",
4668 _("No such interface `%s'"),
4670 g_dbus_connection_send_message (es->connection, reply, NULL, NULL);
4671 g_object_unref (reply);
4676 /* figure out where to dispatch the property get/set/getall calls */
4677 interface_user_data = NULL;
4678 interface_vtable = es->vtable->dispatch (es->connection,
4683 &interface_user_data,
4685 if (interface_vtable == NULL)
4688 if (is_property_get || is_property_set)
4690 CONNECTION_LOCK (connection);
4691 handled = validate_and_maybe_schedule_property_getset (es->connection,
4697 interface_user_data);
4698 CONNECTION_UNLOCK (connection);
4700 else if (is_property_get_all)
4702 CONNECTION_LOCK (connection);
4703 handled = validate_and_maybe_schedule_property_get_all (es->connection,
4708 interface_user_data);
4709 CONNECTION_UNLOCK (connection);
4714 if (interfaces != NULL)
4715 g_ptr_array_unref (interfaces);
4716 g_strfreev (children);
4722 GDBusMessage *message;
4723 ExportedSubtree *es;
4724 } SubtreeDeferredData;
4727 subtree_deferred_data_free (SubtreeDeferredData *data)
4729 g_object_unref (data->message);
4733 /* called without lock held in the thread where the caller registered the subtree */
4735 process_subtree_vtable_message_in_idle_cb (gpointer _data)
4737 SubtreeDeferredData *data = _data;
4742 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
4743 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
4744 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
4745 handled = handle_subtree_introspect (data->es->connection,
4749 handled = handle_subtree_method_invocation (data->es->connection,
4755 CONNECTION_LOCK (data->es->connection);
4756 handled = handle_generic_unlocked (data->es->connection, data->message);
4757 CONNECTION_UNLOCK (data->es->connection);
4760 /* if we couldn't handle the request, just bail with the UnknownMethod error */
4763 GDBusMessage *reply;
4764 reply = g_dbus_message_new_method_error (data->message,
4765 "org.freedesktop.DBus.Error.UnknownMethod",
4766 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
4767 g_dbus_message_get_member (data->message),
4768 g_dbus_message_get_interface (data->message),
4769 g_dbus_message_get_signature (data->message));
4770 g_dbus_connection_send_message (data->es->connection, reply, NULL, NULL);
4771 g_object_unref (reply);
4777 /* called in message handler thread with lock held */
4779 subtree_message_func (GDBusConnection *connection,
4780 ExportedSubtree *es,
4781 GDBusMessage *message)
4783 GSource *idle_source;
4784 SubtreeDeferredData *data;
4786 data = g_new0 (SubtreeDeferredData, 1);
4787 data->message = g_object_ref (message);
4790 /* defer this call to an idle handler in the right thread */
4791 idle_source = g_idle_source_new ();
4792 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
4793 g_source_set_callback (idle_source,
4794 process_subtree_vtable_message_in_idle_cb,
4796 (GDestroyNotify) subtree_deferred_data_free);
4797 g_source_attach (idle_source, es->context);
4798 g_source_unref (idle_source);
4800 /* since we own the entire subtree, handlers for objects not in the subtree have been
4801 * tried already by libdbus-1 - so we just need to ensure that we're always going
4802 * to reply to the message
4808 * g_dbus_connection_register_subtree:
4809 * @connection: A #GDBusConnection.
4810 * @object_path: The object path to register the subtree at.
4811 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
4812 * @flags: Flags used to fine tune the behavior of the subtree.
4813 * @user_data: Data to pass to functions in @vtable.
4814 * @user_data_free_func: Function to call when the subtree is unregistered.
4815 * @error: Return location for error or %NULL.
4817 * Registers a whole subtree of <quote>dynamic</quote> objects.
4819 * The @enumerate and @introspection functions in @vtable are used to
4820 * convey, to remote callers, what nodes exist in the subtree rooted
4823 * When handling remote calls into any node in the subtree, first the
4824 * @enumerate function is used to check if the node exists. If the node exists
4825 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
4826 * the @introspection function is used to check if the node supports the
4827 * requested method. If so, the @dispatch function is used to determine
4828 * where to dispatch the call. The collected #GDBusInterfaceVTable and
4829 * #gpointer will be used to call into the interface vtable for processing
4832 * All calls into user-provided code will be invoked in the <link
4833 * linkend="g-main-context-push-thread-default">thread-default main
4834 * loop</link> of the thread you are calling this method from.
4836 * If an existing subtree is already registered at @object_path or
4837 * then @error is set to #G_IO_ERROR_EXISTS.
4839 * Note that it is valid to register regular objects (using
4840 * g_dbus_connection_register_object()) in a subtree registered with
4841 * g_dbus_connection_register_subtree() - if so, the subtree handler
4842 * is tried as the last resort. One way to think about a subtree
4843 * handler is to consider it a <quote>fallback handler</quote>
4844 * for object paths not registered via g_dbus_connection_register_object()
4845 * or other bindings.
4847 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
4849 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
4850 * that can be used with g_dbus_connection_unregister_subtree() .
4855 g_dbus_connection_register_subtree (GDBusConnection *connection,
4856 const gchar *object_path,
4857 const GDBusSubtreeVTable *vtable,
4858 GDBusSubtreeFlags flags,
4860 GDestroyNotify user_data_free_func,
4864 ExportedSubtree *es;
4866 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4867 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4868 g_return_val_if_fail (vtable != NULL, 0);
4869 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4873 CONNECTION_LOCK (connection);
4875 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
4881 _("A subtree is already exported for %s"),
4886 es = g_new0 (ExportedSubtree, 1);
4887 es->object_path = g_strdup (object_path);
4888 es->connection = connection;
4890 es->vtable = vtable;
4892 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
4893 es->user_data = user_data;
4894 es->user_data_free_func = user_data_free_func;
4895 es->context = g_main_context_get_thread_default ();
4896 if (es->context != NULL)
4897 g_main_context_ref (es->context);
4899 g_hash_table_insert (connection->priv->map_object_path_to_es, es->object_path, es);
4900 g_hash_table_insert (connection->priv->map_id_to_es,
4901 GUINT_TO_POINTER (es->id),
4907 CONNECTION_UNLOCK (connection);
4912 /* ---------------------------------------------------------------------------------------------------- */
4915 * g_dbus_connection_unregister_subtree:
4916 * @connection: A #GDBusConnection.
4917 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
4919 * Unregisters a subtree.
4921 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
4926 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
4927 guint registration_id)
4929 ExportedSubtree *es;
4932 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4936 CONNECTION_LOCK (connection);
4938 es = g_hash_table_lookup (connection->priv->map_id_to_es,
4939 GUINT_TO_POINTER (registration_id));
4943 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_es, GUINT_TO_POINTER (es->id)));
4944 g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_es, es->object_path));
4949 CONNECTION_UNLOCK (connection);
4954 /* ---------------------------------------------------------------------------------------------------- */
4956 /* must be called with lock held */
4958 handle_generic_ping_unlocked (GDBusConnection *connection,
4959 const gchar *object_path,
4960 GDBusMessage *message)
4962 GDBusMessage *reply;
4963 reply = g_dbus_message_new_method_reply (message);
4964 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4965 g_object_unref (reply);
4968 /* must be called with lock held */
4970 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
4971 const gchar *object_path,
4972 GDBusMessage *message)
4974 GDBusMessage *reply;
4977 if (connection->priv->machine_id == NULL)
4981 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
4982 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
4983 &connection->priv->machine_id,
4987 reply = g_dbus_message_new_method_error (message,
4988 "org.freedesktop.DBus.Error.Failed",
4989 _("Unable to load /var/lib/dbus/machine-id: %s"),
4991 g_error_free (error);
4995 g_strstrip (connection->priv->machine_id);
4996 /* TODO: validate value */
5002 reply = g_dbus_message_new_method_reply (message);
5003 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->priv->machine_id));
5005 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
5006 g_object_unref (reply);
5009 /* must be called with lock held */
5011 handle_generic_introspect_unlocked (GDBusConnection *connection,
5012 const gchar *object_path,
5013 GDBusMessage *message)
5018 GDBusMessage *reply;
5020 /* first the header */
5021 s = g_string_new (NULL);
5022 introspect_append_header (s);
5024 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
5025 for (n = 0; registered != NULL && registered[n] != NULL; n++)
5026 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
5027 g_strfreev (registered);
5028 g_string_append (s, "</node>\n");
5030 reply = g_dbus_message_new_method_reply (message);
5031 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5032 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
5033 g_object_unref (reply);
5034 g_string_free (s, TRUE);
5037 /* must be called with lock held */
5039 handle_generic_unlocked (GDBusConnection *connection,
5040 GDBusMessage *message)
5043 const gchar *interface_name;
5044 const gchar *member;
5045 const gchar *signature;
5048 CONNECTION_ENSURE_LOCK (connection);
5052 interface_name = g_dbus_message_get_interface (message);
5053 member = g_dbus_message_get_member (message);
5054 signature = g_dbus_message_get_signature (message);
5055 path = g_dbus_message_get_path (message);
5057 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5058 g_strcmp0 (member, "Introspect") == 0 &&
5059 g_strcmp0 (signature, "") == 0)
5061 handle_generic_introspect_unlocked (connection, path, message);
5064 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5065 g_strcmp0 (member, "Ping") == 0 &&
5066 g_strcmp0 (signature, "") == 0)
5068 handle_generic_ping_unlocked (connection, path, message);
5071 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5072 g_strcmp0 (member, "GetMachineId") == 0 &&
5073 g_strcmp0 (signature, "") == 0)
5075 handle_generic_get_machine_id_unlocked (connection, path, message);
5082 /* ---------------------------------------------------------------------------------------------------- */
5084 /* called in message handler thread with lock held */
5086 distribute_method_call (GDBusConnection *connection,
5087 GDBusMessage *message)
5090 ExportedSubtree *es;
5091 const gchar *object_path;
5092 const gchar *interface_name;
5093 const gchar *member;
5094 const gchar *signature;
5096 gchar *subtree_path;
5099 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
5101 interface_name = g_dbus_message_get_interface (message);
5102 member = g_dbus_message_get_member (message);
5103 signature = g_dbus_message_get_signature (message);
5104 path = g_dbus_message_get_path (message);
5105 subtree_path = g_strdup (path);
5106 needle = strrchr (subtree_path, '/');
5107 if (needle != NULL && needle != subtree_path)
5113 g_free (subtree_path);
5114 subtree_path = NULL;
5118 g_debug ("interface = `%s'", interface_name);
5119 g_debug ("member = `%s'", member);
5120 g_debug ("signature = `%s'", signature);
5121 g_debug ("path = `%s'", path);
5122 g_debug ("subtree_path = `%s'", subtree_path != NULL ? subtree_path : "N/A");
5125 object_path = g_dbus_message_get_path (message);
5126 g_assert (object_path != NULL);
5128 eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
5131 if (obj_message_func (connection, eo, message))
5135 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
5138 if (subtree_message_func (connection, es, message))
5142 if (subtree_path != NULL)
5144 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, subtree_path);
5147 if (subtree_message_func (connection, es, message))
5152 if (handle_generic_unlocked (connection, message))
5155 /* if we end up here, the message has not been not handled */
5158 g_free (subtree_path);
5161 /* ---------------------------------------------------------------------------------------------------- */
5163 static GDBusConnection **
5164 message_bus_get_singleton (GBusType bus_type,
5167 GDBusConnection **ret;
5168 const gchar *starter_bus;
5174 case G_BUS_TYPE_SESSION:
5175 ret = &the_session_bus;
5178 case G_BUS_TYPE_SYSTEM:
5179 ret = &the_system_bus;
5182 case G_BUS_TYPE_STARTER:
5183 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
5184 if (g_strcmp0 (starter_bus, "session") == 0)
5186 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
5189 else if (g_strcmp0 (starter_bus, "system") == 0)
5191 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
5196 if (starter_bus != NULL)
5200 G_IO_ERROR_INVALID_ARGUMENT,
5201 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
5202 " - unknown value `%s'"),
5207 g_set_error_literal (error,
5209 G_IO_ERROR_INVALID_ARGUMENT,
5210 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
5211 "variable is not set"));
5217 g_assert_not_reached ();
5225 static GDBusConnection *
5226 get_uninitialized_connection (GBusType bus_type,
5227 GCancellable *cancellable,
5230 GDBusConnection **singleton;
5231 GDBusConnection *ret;
5235 G_LOCK (message_bus_lock);
5236 singleton = message_bus_get_singleton (bus_type, error);
5237 if (singleton == NULL)
5240 if (*singleton == NULL)
5243 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
5244 if (address == NULL)
5246 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
5248 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
5249 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
5250 "exit-on-close", TRUE,
5255 ret = g_object_ref (*singleton);
5258 g_assert (ret != NULL);
5261 G_UNLOCK (message_bus_lock);
5267 * @bus_type: A #GBusType.
5268 * @cancellable: A #GCancellable or %NULL.
5269 * @error: Return location for error or %NULL.
5271 * Synchronously connects to the message bus specified by @bus_type.
5272 * Note that the returned object may shared with other callers,
5273 * e.g. if two separate parts of a process calls this function with
5274 * the same @bus_type, they will share the same object.
5276 * This is a synchronous failable function. See g_bus_get() and
5277 * g_bus_get_finish() for the asynchronous version.
5279 * The returned object is a singleton, that is, shared with other
5280 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5281 * event that you need a private message bus connection, use
5282 * g_dbus_address_get_for_bus_sync() and
5283 * g_dbus_connection_new_for_address().
5285 * Note that the returned #GDBusConnection object will (usually) have
5286 * the #GDBusConnection:exit-on-close property set to %TRUE.
5288 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5293 g_bus_get_sync (GBusType bus_type,
5294 GCancellable *cancellable,
5297 GDBusConnection *connection;
5299 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5301 connection = get_uninitialized_connection (bus_type, cancellable, error);
5302 if (connection == NULL)
5305 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
5307 g_object_unref (connection);
5316 bus_get_async_initable_cb (GObject *source_object,
5320 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
5324 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
5328 g_assert (error != NULL);
5329 g_simple_async_result_set_from_error (simple, error);
5330 g_error_free (error);
5331 g_object_unref (source_object);
5335 g_simple_async_result_set_op_res_gpointer (simple,
5339 g_simple_async_result_complete_in_idle (simple);
5340 g_object_unref (simple);
5345 * @bus_type: A #GBusType.
5346 * @cancellable: A #GCancellable or %NULL.
5347 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
5348 * @user_data: The data to pass to @callback.
5350 * Asynchronously connects to the message bus specified by @bus_type.
5352 * When the operation is finished, @callback will be invoked. You can
5353 * then call g_bus_get_finish() to get the result of the operation.
5355 * This is a asynchronous failable function. See g_bus_get_sync() for
5356 * the synchronous version.
5361 g_bus_get (GBusType bus_type,
5362 GCancellable *cancellable,
5363 GAsyncReadyCallback callback,
5366 GDBusConnection *connection;
5367 GSimpleAsyncResult *simple;
5370 simple = g_simple_async_result_new (NULL,
5376 connection = get_uninitialized_connection (bus_type, cancellable, &error);
5377 if (connection == NULL)
5379 g_assert (error != NULL);
5380 g_simple_async_result_set_from_error (simple, error);
5381 g_error_free (error);
5382 g_simple_async_result_complete_in_idle (simple);
5383 g_object_unref (simple);
5387 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
5390 bus_get_async_initable_cb,
5397 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
5398 * @error: Return location for error or %NULL.
5400 * Finishes an operation started with g_bus_get().
5402 * The returned object is a singleton, that is, shared with other
5403 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5404 * event that you need a private message bus connection, use
5405 * g_dbus_address_get_for_bus() and
5406 * g_dbus_connection_new_for_address().
5408 * Note that the returned #GDBusConnection object will (usually) have
5409 * the #GDBusConnection:exit-on-close property set to %TRUE.
5411 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5416 g_bus_get_finish (GAsyncResult *res,
5419 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
5421 GDBusConnection *ret;
5423 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5425 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
5429 if (g_simple_async_result_propagate_error (simple, error))
5432 object = g_simple_async_result_get_op_res_gpointer (simple);
5433 g_assert (object != NULL);
5434 ret = g_object_ref (G_DBUS_CONNECTION (object));
5440 /* ---------------------------------------------------------------------------------------------------- */
5442 #define __G_DBUS_CONNECTION_C__
5443 #include "gioaliasdef.c"