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?)
104 * - Update GDBusAuthObserver (s/deny/authorize/)
112 #include "gdbusauth.h"
113 #include "gdbusutils.h"
114 #include "gdbusaddress.h"
115 #include "gdbusmessage.h"
116 #include "gdbusconnection.h"
117 #include "gdbuserror.h"
118 #include "gioenumtypes.h"
119 #include "gdbusintrospection.h"
120 #include "gdbusmethodinvocation.h"
121 #include "gdbusprivate.h"
122 #include "gdbusauthobserver.h"
123 #include "gio-marshal.h"
124 #include "ginitable.h"
125 #include "gasyncinitable.h"
126 #include "giostream.h"
127 #include "gasyncresult.h"
128 #include "gsimpleasyncresult.h"
131 #include <gio/gunixconnection.h>
132 #include <gio/gunixfdmessage.h>
134 #include <sys/types.h>
137 #include "glibintl.h"
138 #include "gioalias.h"
141 * SECTION:gdbusconnection
142 * @short_description: D-Bus Connections
143 * @include: gio/gio.h
145 * The #GDBusConnection type is used for D-Bus connections to remote
146 * peers such as a message buses. It is a low-level API that offers a
147 * lot of flexibility. For instance, it lets you establish a connection
148 * over any transport that can by represented as an #GIOStream.
150 * This class is rarely used directly in D-Bus clients. If you are writing
151 * an D-Bus client, it is often easier to use the g_bus_own_name(),
152 * g_bus_watch_name() or g_bus_watch_proxy() APIs.
154 * <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>
156 * <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>
158 * <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>
160 * <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>
163 /* ---------------------------------------------------------------------------------------------------- */
165 G_LOCK_DEFINE_STATIC (message_bus_lock);
167 static GDBusConnection *the_session_bus = NULL;
168 static GDBusConnection *the_system_bus = NULL;
170 /* ---------------------------------------------------------------------------------------------------- */
173 _g_strv_has_string (const gchar* const *haystack,
178 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
180 if (g_strcmp0 (haystack[n], needle) == 0)
186 /* ---------------------------------------------------------------------------------------------------- */
189 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
191 // TODO: for some reason this doesn't work on Windows
192 #define CONNECTION_ENSURE_LOCK(obj) do { \
193 if (G_UNLIKELY (g_mutex_trylock((obj)->priv->lock))) \
195 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
196 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
201 #define CONNECTION_LOCK(obj) do { \
202 g_mutex_lock ((obj)->priv->lock); \
205 #define CONNECTION_UNLOCK(obj) do { \
206 g_mutex_unlock ((obj)->priv->lock); \
209 struct _GDBusConnectionPrivate
211 /* ------------------------------------------------------------------------ */
212 /* -- General object state ------------------------------------------------ */
213 /* ------------------------------------------------------------------------ */
215 /* object-wide lock */
218 /* A lock used in the init() method of the GInitable interface - see comments
219 * in initable_init() for why a separate lock is needed
223 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
224 * someone calls org.freedesktop.DBus.GetMachineId()
228 /* The underlying stream used for communication */
231 /* The object used for authentication (if any) */
234 /* Set to TRUE if the connection has been closed */
237 /* Last serial used */
240 /* The object used to send/receive message */
243 /* If connected to a message bus, this contains the unique name assigned to
244 * us by the bus (e.g. ":1.42")
246 gchar *bus_unique_name;
248 /* The GUID returned by the other side if we authenticed as a client or
249 * the GUID to use if authenticating as a server
253 /* set to TRUE exactly when initable_init() has finished running */
254 gboolean is_initialized;
256 /* If the connection could not be established during initable_init(), this GError will set */
257 GError *initialization_error;
259 /* The result of g_main_context_get_thread_default() when the object
260 * was created (the GObject _init() function) - this is used for delivery
261 * of the :closed GObject signal.
263 GMainContext *main_context_at_construction;
265 /* construct properties */
267 GDBusConnectionFlags flags;
269 /* Map used for managing method replies */
270 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
272 /* Maps used for managing signal subscription */
273 GHashTable *map_rule_to_signal_data; /* gchar* -> SignalData */
274 GHashTable *map_id_to_signal_data; /* guint -> SignalData */
275 GHashTable *map_sender_to_signal_data_array; /* gchar* -> GPtrArray* of SignalData */
277 /* Maps used for managing exported objects and subtrees */
278 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
279 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
280 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
281 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
283 /* Structure used for message filters */
286 /* Whether to exit on close */
287 gboolean exit_on_close;
289 /* Capabilities negotiated during authentication */
290 GDBusCapabilityFlags capabilities;
292 GDBusAuthObserver *authentication_observer;
293 GCredentials *crendentials;
296 typedef struct ExportedObject ExportedObject;
297 static void exported_object_free (ExportedObject *eo);
299 typedef struct ExportedSubtree ExportedSubtree;
300 static void exported_subtree_free (ExportedSubtree *es);
318 PROP_CAPABILITY_FLAGS,
319 PROP_AUTHENTICATION_OBSERVER,
322 static void distribute_signals (GDBusConnection *connection,
323 GDBusMessage *message);
325 static void distribute_method_call (GDBusConnection *connection,
326 GDBusMessage *message);
328 static gboolean handle_generic_unlocked (GDBusConnection *connection,
329 GDBusMessage *message);
332 static void purge_all_signal_subscriptions (GDBusConnection *connection);
333 static void purge_all_filters (GDBusConnection *connection);
335 #define _G_ENSURE_LOCK(name) do { \
336 if (G_UNLIKELY (G_TRYLOCK(name))) \
338 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
339 "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
343 static guint signals[LAST_SIGNAL] = { 0 };
345 static void initable_iface_init (GInitableIface *initable_iface);
346 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
348 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
349 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
350 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
354 g_dbus_connection_dispose (GObject *object)
356 GDBusConnection *connection = G_DBUS_CONNECTION (object);
358 G_LOCK (message_bus_lock);
359 //g_debug ("disposing %p", connection);
360 if (connection == the_session_bus)
362 the_session_bus = NULL;
364 else if (connection == the_system_bus)
366 the_system_bus = NULL;
368 if (connection->priv->worker != NULL)
370 _g_dbus_worker_stop (connection->priv->worker);
371 connection->priv->worker = NULL;
373 G_UNLOCK (message_bus_lock);
375 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
376 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
380 g_dbus_connection_finalize (GObject *object)
382 GDBusConnection *connection = G_DBUS_CONNECTION (object);
384 if (connection->priv->authentication_observer != NULL)
385 g_object_unref (connection->priv->authentication_observer);
387 if (connection->priv->auth != NULL)
388 g_object_unref (connection->priv->auth);
390 //g_debug ("finalizing %p", connection);
391 if (connection->priv->stream != NULL)
393 /* We don't really care if closing the stream succeeds or not */
394 g_io_stream_close_async (connection->priv->stream,
396 NULL, /* GCancellable */
397 NULL, /* GAsyncReadyCallback */
398 NULL); /* userdata */
399 g_object_unref (connection->priv->stream);
400 connection->priv->stream = NULL;
403 g_free (connection->priv->address);
405 g_free (connection->priv->guid);
406 g_free (connection->priv->bus_unique_name);
408 if (connection->priv->initialization_error != NULL)
409 g_error_free (connection->priv->initialization_error);
411 g_hash_table_unref (connection->priv->map_method_serial_to_send_message_data);
413 purge_all_signal_subscriptions (connection);
414 g_hash_table_unref (connection->priv->map_rule_to_signal_data);
415 g_hash_table_unref (connection->priv->map_id_to_signal_data);
416 g_hash_table_unref (connection->priv->map_sender_to_signal_data_array);
418 g_hash_table_unref (connection->priv->map_id_to_ei);
419 g_hash_table_unref (connection->priv->map_object_path_to_eo);
420 g_hash_table_unref (connection->priv->map_id_to_es);
421 g_hash_table_unref (connection->priv->map_object_path_to_es);
423 purge_all_filters (connection);
424 g_ptr_array_unref (connection->priv->filters);
426 if (connection->priv->main_context_at_construction != NULL)
427 g_main_context_unref (connection->priv->main_context_at_construction);
429 g_free (connection->priv->machine_id);
431 g_mutex_free (connection->priv->init_lock);
432 g_mutex_free (connection->priv->lock);
434 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
438 g_dbus_connection_get_property (GObject *object,
443 GDBusConnection *connection = G_DBUS_CONNECTION (object);
448 g_value_set_object (value, g_dbus_connection_get_stream (connection));
452 g_value_set_string (value, g_dbus_connection_get_guid (connection));
455 case PROP_UNIQUE_NAME:
456 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
460 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
463 case PROP_EXIT_ON_CLOSE:
464 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
467 case PROP_CAPABILITY_FLAGS:
468 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
472 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
478 g_dbus_connection_set_property (GObject *object,
483 GDBusConnection *connection = G_DBUS_CONNECTION (object);
488 connection->priv->stream = g_value_dup_object (value);
492 connection->priv->guid = g_value_dup_string (value);
496 connection->priv->address = g_value_dup_string (value);
500 connection->priv->flags = g_value_get_flags (value);
503 case PROP_EXIT_ON_CLOSE:
504 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
507 case PROP_AUTHENTICATION_OBSERVER:
508 connection->priv->authentication_observer = g_value_dup_object (value);
512 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
518 g_dbus_connection_real_closed (GDBusConnection *connection,
519 gboolean remote_peer_vanished,
522 if (remote_peer_vanished && connection->priv->exit_on_close)
524 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
530 g_dbus_connection_class_init (GDBusConnectionClass *klass)
532 GObjectClass *gobject_class;
534 g_type_class_add_private (klass, sizeof (GDBusConnectionPrivate));
536 gobject_class = G_OBJECT_CLASS (klass);
538 gobject_class->finalize = g_dbus_connection_finalize;
539 gobject_class->dispose = g_dbus_connection_dispose;
540 gobject_class->set_property = g_dbus_connection_set_property;
541 gobject_class->get_property = g_dbus_connection_get_property;
543 klass->closed = g_dbus_connection_real_closed;
546 * GDBusConnection:stream:
548 * The underlying #GIOStream used for I/O.
552 g_object_class_install_property (gobject_class,
554 g_param_spec_object ("stream",
556 P_("The underlying streams used for I/O"),
560 G_PARAM_CONSTRUCT_ONLY |
561 G_PARAM_STATIC_NAME |
562 G_PARAM_STATIC_BLURB |
563 G_PARAM_STATIC_NICK));
566 * GDBusConnection:address:
568 * A D-Bus address specifying potential endpoints that can be used
569 * when establishing the connection.
573 g_object_class_install_property (gobject_class,
575 g_param_spec_string ("address",
577 P_("D-Bus address specifying potential socket endpoints"),
580 G_PARAM_CONSTRUCT_ONLY |
581 G_PARAM_STATIC_NAME |
582 G_PARAM_STATIC_BLURB |
583 G_PARAM_STATIC_NICK));
586 * GDBusConnection:flags:
588 * Flags from the #GDBusConnectionFlags enumeration.
592 g_object_class_install_property (gobject_class,
594 g_param_spec_flags ("flags",
597 G_TYPE_DBUS_CONNECTION_FLAGS,
598 G_DBUS_CONNECTION_FLAGS_NONE,
600 G_PARAM_CONSTRUCT_ONLY |
601 G_PARAM_STATIC_NAME |
602 G_PARAM_STATIC_BLURB |
603 G_PARAM_STATIC_NICK));
606 * GDBusConnection:guid:
608 * The GUID of the peer performing the role of server when
611 * If you are constructing a #GDBusConnection and pass
612 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
613 * #GDBusConnection:flags property then you MUST also set this
614 * property to a valid guid.
616 * If you are constructing a #GDBusConnection and pass
617 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
618 * #GDBusConnection:flags property you will be able to read the GUID
619 * of the other peer here after the connection has been successfully
624 g_object_class_install_property (gobject_class,
626 g_param_spec_string ("guid",
628 P_("GUID of the server peer"),
632 G_PARAM_CONSTRUCT_ONLY |
633 G_PARAM_STATIC_NAME |
634 G_PARAM_STATIC_BLURB |
635 G_PARAM_STATIC_NICK));
638 * GDBusConnection:unique-name:
640 * The unique name as assigned by the message bus or %NULL if the
641 * connection is not open or not a message bus connection.
645 g_object_class_install_property (gobject_class,
647 g_param_spec_string ("unique-name",
649 P_("Unique name of bus connection"),
652 G_PARAM_STATIC_NAME |
653 G_PARAM_STATIC_BLURB |
654 G_PARAM_STATIC_NICK));
657 * GDBusConnection:closed:
659 * A boolean specifying whether the connection has been closed.
663 g_object_class_install_property (gobject_class,
665 g_param_spec_boolean ("closed",
667 P_("Whether the connection is closed"),
670 G_PARAM_STATIC_NAME |
671 G_PARAM_STATIC_BLURB |
672 G_PARAM_STATIC_NICK));
675 * GDBusConnection:exit-on-close:
677 * A boolean specifying whether the process will be terminated (by
678 * calling <literal>raise(SIGTERM)</literal>) if the connection
679 * is closed by the remote peer.
683 g_object_class_install_property (gobject_class,
685 g_param_spec_boolean ("exit-on-close",
687 P_("Whether the process is terminated when the connection is closed"),
691 G_PARAM_STATIC_NAME |
692 G_PARAM_STATIC_BLURB |
693 G_PARAM_STATIC_NICK));
696 * GDBusConnection:capabilities:
698 * Flags from the #GDBusCapabilityFlags enumeration
699 * representing connection features negotiated with the other peer.
703 g_object_class_install_property (gobject_class,
704 PROP_CAPABILITY_FLAGS,
705 g_param_spec_flags ("capabilities",
708 G_TYPE_DBUS_CAPABILITY_FLAGS,
709 G_DBUS_CAPABILITY_FLAGS_NONE,
711 G_PARAM_STATIC_NAME |
712 G_PARAM_STATIC_BLURB |
713 G_PARAM_STATIC_NICK));
716 * GDBusConnection:authentication-observer:
718 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
722 g_object_class_install_property (gobject_class,
723 PROP_AUTHENTICATION_OBSERVER,
724 g_param_spec_object ("authentication-observer",
725 P_("Authentication Observer"),
726 P_("Object used to assist in the authentication process"),
727 G_TYPE_DBUS_AUTH_OBSERVER,
729 G_PARAM_CONSTRUCT_ONLY |
730 G_PARAM_STATIC_NAME |
731 G_PARAM_STATIC_BLURB |
732 G_PARAM_STATIC_NICK));
735 * GDBusConnection::closed:
736 * @connection: The #GDBusConnection emitting the signal.
737 * @remote_peer_vanished: %TRUE if @connection is closed because the
738 * remote peer closed its end of the connection.
739 * @error: A #GError with more details about the event or %NULL.
741 * Emitted when the connection is closed.
743 * The cause of this event can be
746 * If g_dbus_connection_close() is called. In this case
747 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
750 * If the remote peer closes the connection. In this case
751 * @remote_peer_vanished is set to %TRUE and @error is set.
754 * If the remote peer sends invalid or malformed data. In this
755 * case @remote_peer_vanished is set to %FALSE and @error
760 * Upon receiving this signal, you should give up your reference to
761 * @connection. You are guaranteed that this signal is emitted only
766 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
767 G_TYPE_DBUS_CONNECTION,
769 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
772 _gio_marshal_VOID__BOOLEAN_BOXED,
780 g_dbus_connection_init (GDBusConnection *connection)
782 connection->priv = G_TYPE_INSTANCE_GET_PRIVATE (connection, G_TYPE_DBUS_CONNECTION, GDBusConnectionPrivate);
784 connection->priv->lock = g_mutex_new ();
785 connection->priv->init_lock = g_mutex_new ();
787 connection->priv->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
789 connection->priv->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
791 connection->priv->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
793 connection->priv->map_sender_to_signal_data_array = g_hash_table_new_full (g_str_hash,
798 connection->priv->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
801 (GDestroyNotify) exported_object_free);
803 connection->priv->map_id_to_ei = g_hash_table_new (g_direct_hash,
806 connection->priv->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
809 (GDestroyNotify) exported_subtree_free);
811 connection->priv->map_id_to_es = g_hash_table_new (g_direct_hash,
814 connection->priv->main_context_at_construction = g_main_context_get_thread_default ();
815 if (connection->priv->main_context_at_construction != NULL)
816 g_main_context_ref (connection->priv->main_context_at_construction);
818 connection->priv->filters = g_ptr_array_new ();
822 * g_dbus_connection_get_stream:
823 * @connection: a #GDBusConnection
825 * Gets the underlying stream used for IO.
827 * Returns: the stream used for IO
832 g_dbus_connection_get_stream (GDBusConnection *connection)
834 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
835 return connection->priv->stream;
840 * g_dbus_connection_is_closed:
841 * @connection: A #GDBusConnection.
843 * Gets whether @connection is closed.
845 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
850 g_dbus_connection_is_closed (GDBusConnection *connection)
852 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
853 return connection->priv->closed;
857 * g_dbus_connection_get_capabilities:
858 * @connection: A #GDBusConnection.
860 * Gets the capabilities negotiated with the remote peer
862 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
867 g_dbus_connection_get_capabilities (GDBusConnection *connection)
869 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
870 return connection->priv->capabilities;
874 /* ---------------------------------------------------------------------------------------------------- */
878 GDBusConnection *connection;
880 gboolean remote_peer_vanished;
884 emit_closed_data_free (EmitClosedData *data)
886 g_object_unref (data->connection);
887 if (data->error != NULL)
888 g_error_free (data->error);
893 emit_closed_in_idle (gpointer user_data)
895 EmitClosedData *data = user_data;
898 g_object_notify (G_OBJECT (data->connection), "closed");
899 g_signal_emit (data->connection,
900 signals[CLOSED_SIGNAL],
902 data->remote_peer_vanished,
908 /* Can be called from any thread, must hold lock */
910 set_closed_unlocked (GDBusConnection *connection,
911 gboolean remote_peer_vanished,
914 GSource *idle_source;
915 EmitClosedData *data;
917 CONNECTION_ENSURE_LOCK (connection);
919 g_assert (!connection->priv->closed);
921 connection->priv->closed = TRUE;
923 data = g_new0 (EmitClosedData, 1);
924 data->connection = g_object_ref (connection);
925 data->remote_peer_vanished = remote_peer_vanished;
926 data->error = error != NULL ? g_error_copy (error) : NULL;
928 idle_source = g_idle_source_new ();
929 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
930 g_source_set_callback (idle_source,
933 (GDestroyNotify) emit_closed_data_free);
934 g_source_attach (idle_source, connection->priv->main_context_at_construction);
935 g_source_unref (idle_source);
938 /* ---------------------------------------------------------------------------------------------------- */
941 * g_dbus_connection_close:
942 * @connection: A #GDBusConnection.
944 * Closes @connection. Note that this never causes the process to
945 * exit (this might only happen if the other end of a shared message
946 * bus connection disconnects).
948 * If @connection is already closed, this method does nothing.
953 g_dbus_connection_close (GDBusConnection *connection)
955 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
957 CONNECTION_LOCK (connection);
958 if (!connection->priv->closed)
960 GError *error = NULL;
962 /* TODO: do this async */
963 //g_debug ("closing connection %p's stream %p", connection, connection->priv->stream);
964 if (!g_io_stream_close (connection->priv->stream, NULL, &error))
966 g_warning ("Error closing stream: %s", error->message);
967 g_error_free (error);
970 set_closed_unlocked (connection, FALSE, NULL);
972 CONNECTION_UNLOCK (connection);
975 /* ---------------------------------------------------------------------------------------------------- */
978 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
979 GDBusMessage *message,
980 volatile guint32 *out_serial,
985 guint32 serial_to_use;
988 CONNECTION_ENSURE_LOCK (connection);
990 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
991 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
993 /* TODO: check all necessary headers are present */
998 if (out_serial != NULL)
1001 if (connection->priv->closed)
1003 g_set_error_literal (error,
1006 _("The connection is closed"));
1010 blob = g_dbus_message_to_blob (message,
1012 connection->priv->capabilities,
1017 serial_to_use = ++connection->priv->last_serial; /* TODO: handle overflow */
1022 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1025 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1028 g_assert_not_reached ();
1033 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1034 blob_size, serial_to_use, connection);
1035 g_printerr ("----\n");
1036 hexdump (blob, blob_size);
1037 g_printerr ("----\n");
1040 /* TODO: use connection->priv->auth to encode the blob */
1042 if (out_serial != NULL)
1043 *out_serial = serial_to_use;
1045 g_dbus_message_set_serial (message, serial_to_use);
1047 _g_dbus_worker_send_message (connection->priv->worker,
1051 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1062 * g_dbus_connection_send_message:
1063 * @connection: A #GDBusConnection.
1064 * @message: A #GDBusMessage
1065 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1066 * @error: Return location for error or %NULL.
1068 * Asynchronously sends @message to the peer represented by @connection.
1070 * If @out_serial is not %NULL, then the serial number assigned to
1071 * @message by @connection will be written to this location prior to
1072 * submitting the message to the underlying transport.
1074 * If @connection is closed then the operation will fail with
1075 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1076 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1077 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1079 * See <xref linkend="gdbus-server"/> and <xref
1080 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1081 * low-level API to send and receive UNIX file descriptors.
1083 * Returns: %TRUE if the message was well-formed and queued for
1084 * transmission, %FALSE if @error is set.
1089 g_dbus_connection_send_message (GDBusConnection *connection,
1090 GDBusMessage *message,
1091 volatile guint32 *out_serial,
1096 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1097 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1098 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1100 CONNECTION_LOCK (connection);
1101 ret = g_dbus_connection_send_message_unlocked (connection, message, out_serial, error);
1102 CONNECTION_UNLOCK (connection);
1106 /* ---------------------------------------------------------------------------------------------------- */
1110 volatile gint ref_count;
1111 GDBusConnection *connection;
1113 GSimpleAsyncResult *simple;
1115 GMainContext *main_context;
1117 GCancellable *cancellable;
1119 gulong cancellable_handler_id;
1121 GSource *timeout_source;
1126 static SendMessageData *
1127 send_message_data_ref (SendMessageData *data)
1129 g_atomic_int_inc (&data->ref_count);
1134 send_message_data_unref (SendMessageData *data)
1136 if (g_atomic_int_dec_and_test (&data->ref_count))
1138 g_assert (data->timeout_source == NULL);
1139 g_assert (data->simple == NULL);
1140 g_assert (data->cancellable_handler_id == 0);
1141 g_object_unref (data->connection);
1142 if (data->cancellable != NULL)
1143 g_object_unref (data->cancellable);
1144 if (data->main_context != NULL)
1145 g_main_context_unref (data->main_context);
1150 /* ---------------------------------------------------------------------------------------------------- */
1152 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1154 send_message_with_reply_deliver (SendMessageData *data)
1156 CONNECTION_ENSURE_LOCK (data->connection);
1158 g_assert (!data->delivered);
1160 data->delivered = TRUE;
1162 g_simple_async_result_complete_in_idle (data->simple);
1163 g_object_unref (data->simple);
1164 data->simple = NULL;
1166 if (data->timeout_source != NULL)
1168 g_source_destroy (data->timeout_source);
1169 data->timeout_source = NULL;
1171 if (data->cancellable_handler_id > 0)
1173 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1174 data->cancellable_handler_id = 0;
1177 g_warn_if_fail (g_hash_table_remove (data->connection->priv->map_method_serial_to_send_message_data,
1178 GUINT_TO_POINTER (data->serial)));
1180 send_message_data_unref (data);
1183 /* ---------------------------------------------------------------------------------------------------- */
1185 /* must hold lock */
1187 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1188 GDBusMessage *reply)
1190 if (data->delivered)
1193 g_simple_async_result_set_op_res_gpointer (data->simple,
1194 g_object_ref (reply),
1197 send_message_with_reply_deliver (data);
1203 /* ---------------------------------------------------------------------------------------------------- */
1206 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1208 SendMessageData *data = user_data;
1210 CONNECTION_LOCK (data->connection);
1211 if (data->delivered)
1214 g_simple_async_result_set_error (data->simple,
1216 G_IO_ERROR_CANCELLED,
1217 _("Operation was cancelled"));
1219 send_message_with_reply_deliver (data);
1222 CONNECTION_UNLOCK (data->connection);
1226 /* Can be called from any thread with or without lock held */
1228 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1231 SendMessageData *data = user_data;
1232 GSource *idle_source;
1234 /* postpone cancellation to idle handler since we may be called directly
1235 * via g_cancellable_connect() (e.g. holding lock)
1237 idle_source = g_idle_source_new ();
1238 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1239 g_source_set_callback (idle_source,
1240 send_message_with_reply_cancelled_idle_cb,
1241 send_message_data_ref (data),
1242 (GDestroyNotify) send_message_data_unref);
1243 g_source_attach (idle_source, data->main_context);
1244 g_source_unref (idle_source);
1247 /* ---------------------------------------------------------------------------------------------------- */
1250 send_message_with_reply_timeout_cb (gpointer user_data)
1252 SendMessageData *data = user_data;
1254 CONNECTION_LOCK (data->connection);
1255 if (data->delivered)
1258 g_simple_async_result_set_error (data->simple,
1260 G_IO_ERROR_TIMED_OUT,
1261 _("Timeout was reached"));
1263 send_message_with_reply_deliver (data);
1266 CONNECTION_UNLOCK (data->connection);
1271 /* ---------------------------------------------------------------------------------------------------- */
1274 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1275 GDBusMessage *message,
1277 volatile guint32 *out_serial,
1278 GCancellable *cancellable,
1279 GAsyncReadyCallback callback,
1282 GSimpleAsyncResult *simple;
1283 SendMessageData *data;
1285 volatile guint32 serial;
1289 if (out_serial == NULL)
1290 out_serial = &serial;
1292 if (timeout_msec == -1)
1293 timeout_msec = 30 * 1000; /* TODO: check 30 secs is the default timeout */
1295 simple = g_simple_async_result_new (G_OBJECT (connection),
1298 g_dbus_connection_send_message_with_reply);
1300 if (g_cancellable_is_cancelled (cancellable))
1302 g_simple_async_result_set_error (simple,
1304 G_IO_ERROR_CANCELLED,
1305 _("Operation was cancelled"));
1306 g_simple_async_result_complete_in_idle (simple);
1307 g_object_unref (simple);
1311 if (connection->priv->closed)
1313 g_simple_async_result_set_error (simple,
1316 _("The connection is closed"));
1317 g_simple_async_result_complete_in_idle (simple);
1318 g_object_unref (simple);
1323 if (!g_dbus_connection_send_message_unlocked (connection, message, out_serial, &error))
1325 g_simple_async_result_set_from_error (simple, error);
1326 g_simple_async_result_complete_in_idle (simple);
1327 g_object_unref (simple);
1331 data = g_new0 (SendMessageData, 1);
1332 data->ref_count = 1;
1333 data->connection = g_object_ref (connection);
1334 data->simple = simple;
1335 data->serial = *out_serial;
1336 data->main_context = g_main_context_get_thread_default ();
1337 if (data->main_context != NULL)
1338 g_main_context_ref (data->main_context);
1340 if (cancellable != NULL)
1342 data->cancellable = g_object_ref (cancellable);
1343 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1344 G_CALLBACK (send_message_with_reply_cancelled_cb),
1345 send_message_data_ref (data),
1346 (GDestroyNotify) send_message_data_unref);
1347 g_object_set_data_full (G_OBJECT (simple),
1349 g_object_ref (cancellable),
1350 (GDestroyNotify) g_object_unref);
1353 data->timeout_source = g_timeout_source_new (timeout_msec);
1354 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1355 g_source_set_callback (data->timeout_source,
1356 send_message_with_reply_timeout_cb,
1357 send_message_data_ref (data),
1358 (GDestroyNotify) send_message_data_unref);
1359 g_source_attach (data->timeout_source, data->main_context);
1360 g_source_unref (data->timeout_source);
1362 g_hash_table_insert (connection->priv->map_method_serial_to_send_message_data,
1363 GUINT_TO_POINTER (*out_serial),
1371 * g_dbus_connection_send_message_with_reply:
1372 * @connection: A #GDBusConnection.
1373 * @message: A #GDBusMessage.
1374 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1375 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1376 * @cancellable: A #GCancellable or %NULL.
1377 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1378 * care about the result.
1379 * @user_data: The data to pass to @callback.
1381 * Asynchronously sends @message to the peer represented by @connection.
1383 * If @out_serial is not %NULL, then the serial number assigned to
1384 * @message by @connection will be written to this location prior to
1385 * submitting the message to the underlying transport.
1387 * If @connection is closed then the operation will fail with
1388 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1389 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1390 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1392 * This is an asynchronous method. When the operation is finished, @callback will be invoked
1393 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
1394 * of the thread you are calling this method from. You can then call
1395 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1396 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
1398 * See <xref linkend="gdbus-server"/> and <xref
1399 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1400 * low-level API to send and receive UNIX file descriptors.
1405 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
1406 GDBusMessage *message,
1408 volatile guint32 *out_serial,
1409 GCancellable *cancellable,
1410 GAsyncReadyCallback callback,
1413 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1414 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1415 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
1417 CONNECTION_LOCK (connection);
1418 g_dbus_connection_send_message_with_reply_unlocked (connection,
1425 CONNECTION_UNLOCK (connection);
1429 * g_dbus_connection_send_message_with_reply_finish:
1430 * @connection: a #GDBusConnection
1431 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
1432 * @error: Return location for error or %NULL.
1434 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
1436 * Note that @error is only set if a local in-process error
1437 * occured. That is to say that the returned #GDBusMessage object may
1438 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1439 * g_dbus_message_to_gerror() to transcode this to a #GError.
1441 * See <xref linkend="gdbus-server"/> and <xref
1442 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1443 * low-level API to send and receive UNIX file descriptors.
1445 * Returns: A #GDBusMessage or %NULL if @error is set.
1450 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
1454 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1455 GDBusMessage *reply;
1456 GCancellable *cancellable;
1458 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1459 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1463 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
1465 if (g_simple_async_result_propagate_error (simple, error))
1468 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
1469 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
1470 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
1472 g_object_unref (reply);
1474 g_set_error_literal (error,
1476 G_IO_ERROR_CANCELLED,
1477 _("Operation was cancelled"));
1483 /* ---------------------------------------------------------------------------------------------------- */
1488 GMainContext *context;
1490 } SendMessageSyncData;
1493 send_message_with_reply_sync_cb (GDBusConnection *connection,
1497 SendMessageSyncData *data = user_data;
1498 data->res = g_object_ref (res);
1499 g_main_loop_quit (data->loop);
1503 * g_dbus_connection_send_message_with_reply_sync:
1504 * @connection: A #GDBusConnection.
1505 * @message: A #GDBusMessage.
1506 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1507 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1508 * @cancellable: A #GCancellable or %NULL.
1509 * @error: Return location for error or %NULL.
1511 * Synchronously sends @message to the peer represented by @connection
1512 * and blocks the calling thread until a reply is received or the
1513 * timeout is reached. See g_dbus_connection_send_message_with_reply()
1514 * for the asynchronous version of this method.
1516 * If @out_serial is not %NULL, then the serial number assigned to
1517 * @message by @connection will be written to this location prior to
1518 * submitting the message to the underlying transport.
1520 * If @connection is closed then the operation will fail with
1521 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1522 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1523 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1525 * Note that @error is only set if a local in-process error
1526 * occured. That is to say that the returned #GDBusMessage object may
1527 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1528 * g_dbus_message_to_gerror() to transcode this to a #GError.
1530 * See <xref linkend="gdbus-server"/> and <xref
1531 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1532 * low-level API to send and receive UNIX file descriptors.
1534 * Returns: A #GDBusMessage that is the reply to @message or %NULL if @error is set.
1539 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
1540 GDBusMessage *message,
1542 volatile guint32 *out_serial,
1543 GCancellable *cancellable,
1546 SendMessageSyncData *data;
1547 GDBusMessage *reply;
1549 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1550 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
1551 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1552 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1554 data = g_new0 (SendMessageSyncData, 1);
1555 data->context = g_main_context_new ();
1556 data->loop = g_main_loop_new (data->context, FALSE);
1558 g_main_context_push_thread_default (data->context);
1560 g_dbus_connection_send_message_with_reply (connection,
1565 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
1567 g_main_loop_run (data->loop);
1568 reply = g_dbus_connection_send_message_with_reply_finish (connection,
1572 g_main_context_pop_thread_default (data->context);
1574 g_main_context_unref (data->context);
1575 g_main_loop_unref (data->loop);
1576 g_object_unref (data->res);
1582 /* ---------------------------------------------------------------------------------------------------- */
1586 GDBusMessageFilterFunction func;
1593 GDBusMessageFilterFunction filter_function;
1595 GDestroyNotify user_data_free_func;
1598 /* Called in worker's thread - we must not block */
1600 on_worker_message_received (GDBusWorker *worker,
1601 GDBusMessage *message,
1604 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1605 FilterCallback *filters;
1606 gboolean consumed_by_filter;
1610 //g_debug ("in on_worker_message_received");
1612 g_object_ref (connection);
1614 /* First collect the set of callback functions */
1615 CONNECTION_LOCK (connection);
1616 num_filters = connection->priv->filters->len;
1617 filters = g_new0 (FilterCallback, num_filters);
1618 for (n = 0; n < num_filters; n++)
1620 FilterData *data = connection->priv->filters->pdata[n];
1621 filters[n].func = data->filter_function;
1622 filters[n].user_data = data->user_data;
1624 CONNECTION_UNLOCK (connection);
1626 /* the call the filters in order (without holding the lock) */
1627 consumed_by_filter = FALSE;
1628 for (n = 0; n < num_filters; n++)
1630 consumed_by_filter = filters[n].func (connection,
1632 filters[n].user_data);
1633 if (consumed_by_filter)
1637 /* Standard dispatch unless the filter ate the message */
1638 if (!consumed_by_filter)
1640 GDBusMessageType message_type;
1642 message_type = g_dbus_message_get_message_type (message);
1643 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
1645 guint32 reply_serial;
1646 SendMessageData *send_message_data;
1648 reply_serial = g_dbus_message_get_reply_serial (message);
1649 CONNECTION_LOCK (connection);
1650 send_message_data = g_hash_table_lookup (connection->priv->map_method_serial_to_send_message_data,
1651 GUINT_TO_POINTER (reply_serial));
1652 if (send_message_data != NULL)
1654 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
1655 send_message_data_deliver_reply_unlocked (send_message_data, message);
1659 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
1661 CONNECTION_UNLOCK (connection);
1663 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
1665 CONNECTION_LOCK (connection);
1666 distribute_signals (connection, message);
1667 CONNECTION_UNLOCK (connection);
1669 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
1671 CONNECTION_LOCK (connection);
1672 distribute_method_call (connection, message);
1673 CONNECTION_UNLOCK (connection);
1677 g_object_unref (connection);
1681 /* Called in worker's thread - we must not block */
1683 on_worker_closed (GDBusWorker *worker,
1684 gboolean remote_peer_vanished,
1688 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1690 //g_debug ("in on_worker_closed: %s", error->message);
1692 CONNECTION_LOCK (connection);
1693 if (!connection->priv->closed)
1694 set_closed_unlocked (connection, remote_peer_vanished, error);
1695 CONNECTION_UNLOCK (connection);
1698 /* ---------------------------------------------------------------------------------------------------- */
1700 /* Determines the biggest set of capabilities we can support on this connection */
1701 static GDBusCapabilityFlags
1702 get_offered_capabilities_max (GDBusConnection *connection)
1704 GDBusCapabilityFlags ret;
1705 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
1707 if (G_IS_UNIX_CONNECTION (connection->priv->stream))
1708 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
1714 initable_init (GInitable *initable,
1715 GCancellable *cancellable,
1718 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
1721 /* This method needs to be idempotent to work with the singleton
1722 * pattern. See the docs for g_initable_init(). We implement this by
1725 * Unfortunately we can't use the main lock since the on_worker_*()
1726 * callbacks above needs the lock during initialization (for message
1727 * bus connections we do a synchronous Hello() call on the bus).
1729 g_mutex_lock (connection->priv->init_lock);
1733 if (connection->priv->is_initialized)
1735 if (connection->priv->stream != NULL)
1738 g_assert (connection->priv->initialization_error != NULL);
1741 g_assert (connection->priv->initialization_error == NULL);
1743 /* The user can pass multiple (but mutally exclusive) construct
1746 * - stream (of type GIOStream)
1747 * - address (of type gchar*)
1749 * At the end of the day we end up with a non-NULL GIOStream
1750 * object in connection->priv->stream.
1752 if (connection->priv->address != NULL)
1754 g_assert (connection->priv->stream == NULL);
1756 if ((connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
1757 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
1759 g_set_error_literal (error,
1761 G_IO_ERROR_INVALID_ARGUMENT,
1762 _("Unsupported flags encountered when constructing a client-side connection"));
1766 connection->priv->stream = g_dbus_address_get_stream_sync (connection->priv->address,
1767 NULL, /* TODO: out_guid */
1769 &connection->priv->initialization_error);
1770 if (connection->priv->stream == NULL)
1773 else if (connection->priv->stream != NULL)
1779 g_assert_not_reached ();
1782 /* Authenticate the connection */
1783 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
1785 g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
1786 g_assert (connection->priv->guid != NULL);
1787 connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1788 if (!_g_dbus_auth_run_server (connection->priv->auth,
1789 connection->priv->authentication_observer,
1790 connection->priv->guid,
1791 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
1792 get_offered_capabilities_max (connection),
1793 &connection->priv->capabilities,
1794 &connection->priv->crendentials,
1796 &connection->priv->initialization_error))
1799 else if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
1801 g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
1802 g_assert (connection->priv->guid == NULL);
1803 connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1804 connection->priv->guid = _g_dbus_auth_run_client (connection->priv->auth,
1805 get_offered_capabilities_max (connection),
1806 &connection->priv->capabilities,
1808 &connection->priv->initialization_error);
1809 if (connection->priv->guid == NULL)
1813 if (connection->priv->authentication_observer != NULL)
1815 g_object_unref (connection->priv->authentication_observer);
1816 connection->priv->authentication_observer = NULL;
1819 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->priv->stream)
1821 //g_debug ("haz unix fd passing powers: %d", connection->priv->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
1825 * https://bugzilla.gnome.org/show_bug.cgi?id=616458
1829 if (G_IS_SOCKET_CONNECTION (connection->priv->stream))
1831 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->priv->stream)), FALSE);
1834 connection->priv->worker = _g_dbus_worker_new (connection->priv->stream,
1835 connection->priv->capabilities,
1836 on_worker_message_received,
1840 /* if a bus connection, invoke org.freedesktop.DBus.Hello - this is how we're getting a name */
1841 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
1843 GVariant *hello_result;
1846 hello_result = g_dbus_connection_call_sync (connection,
1847 "org.freedesktop.DBus", /* name */
1848 "/org/freedesktop/DBus", /* path */
1849 "org.freedesktop.DBus", /* interface */
1851 NULL, /* parameters */
1852 G_DBUS_CALL_FLAGS_NONE,
1854 NULL, /* TODO: cancellable */
1855 &connection->priv->initialization_error);
1856 if (hello_result == NULL)
1859 g_variant_get (hello_result, "(s)", &s);
1860 connection->priv->bus_unique_name = g_strdup (s);
1861 g_variant_unref (hello_result);
1862 //g_debug ("unique name is `%s'", connection->priv->bus_unique_name);
1865 connection->priv->is_initialized = TRUE;
1871 g_assert (connection->priv->initialization_error != NULL);
1872 g_propagate_error (error, g_error_copy (connection->priv->initialization_error));
1875 g_mutex_unlock (connection->priv->init_lock);
1881 initable_iface_init (GInitableIface *initable_iface)
1883 initable_iface->init = initable_init;
1886 /* ---------------------------------------------------------------------------------------------------- */
1889 async_init_thread (GSimpleAsyncResult *res,
1891 GCancellable *cancellable)
1893 GError *error = NULL;
1895 if (!g_initable_init (G_INITABLE (object), cancellable, &error))
1897 g_simple_async_result_set_from_error (res, error);
1898 g_error_free (error);
1903 async_initable_init_async (GAsyncInitable *initable,
1905 GCancellable *cancellable,
1906 GAsyncReadyCallback callback,
1909 GSimpleAsyncResult *res;
1911 g_return_if_fail (G_IS_INITABLE (initable));
1913 res = g_simple_async_result_new (G_OBJECT (initable), callback, user_data,
1914 async_initable_init_async);
1915 g_simple_async_result_run_in_thread (res, async_init_thread,
1916 io_priority, cancellable);
1917 g_object_unref (res);
1921 async_initable_init_finish (GAsyncInitable *initable,
1925 return TRUE; /* Errors handled by base impl */
1929 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
1931 /* We basically just want to use GIO's default implementation - though that one is
1932 * unfortunately broken, see #615111. So we copy-paste a fixed-up version.
1934 async_initable_iface->init_async = async_initable_init_async;
1935 async_initable_iface->init_finish = async_initable_init_finish;
1938 /* ---------------------------------------------------------------------------------------------------- */
1941 * g_dbus_connection_new:
1942 * @stream: A #GIOStream.
1943 * @guid: The GUID to use if a authenticating as a server or %NULL.
1944 * @flags: Flags describing how to make the connection.
1945 * @observer: A #GDBusAuthObserver or %NULL.
1946 * @cancellable: A #GCancellable or %NULL.
1947 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
1948 * @user_data: The data to pass to @callback.
1950 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
1951 * with the end represented by @stream.
1953 * If %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER is set in @flags,
1954 * @observer (if not %NULL) is used to assist in the client
1955 * authentication process.
1957 * When the operation is finished, @callback will be invoked. You can
1958 * then call g_dbus_connection_new_finish() to get the result of the
1961 * This is a asynchronous failable constructor. See
1962 * g_dbus_connection_new_sync() for the synchronous
1968 g_dbus_connection_new (GIOStream *stream,
1970 GDBusConnectionFlags flags,
1971 GDBusAuthObserver *observer,
1972 GCancellable *cancellable,
1973 GAsyncReadyCallback callback,
1976 g_return_if_fail (G_IS_IO_STREAM (stream));
1977 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
1985 "authentication-observer", observer,
1990 * g_dbus_connection_new_finish:
1991 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
1992 * @error: Return location for error or %NULL.
1994 * Finishes an operation started with g_dbus_connection_new().
1996 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2001 g_dbus_connection_new_finish (GAsyncResult *res,
2005 GObject *source_object;
2007 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2008 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2010 source_object = g_async_result_get_source_object (res);
2011 g_assert (source_object != NULL);
2012 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2015 g_object_unref (source_object);
2017 return G_DBUS_CONNECTION (object);
2023 * g_dbus_connection_new_sync:
2024 * @stream: A #GIOStream.
2025 * @guid: The GUID to use if a authenticating as a server or %NULL.
2026 * @flags: Flags describing how to make the connection.
2027 * @observer: A #GDBusAuthObserver or %NULL.
2028 * @cancellable: A #GCancellable or %NULL.
2029 * @error: Return location for error or %NULL.
2031 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2032 * with the end represented by @stream.
2034 * If %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER is set in @flags,
2035 * @observer (if not %NULL) is used to assist in the client
2036 * authentication process.
2038 * This is a synchronous failable constructor. See
2039 * g_dbus_connection_new() for the asynchronous version.
2041 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2046 g_dbus_connection_new_sync (GIOStream *stream,
2048 GDBusConnectionFlags flags,
2049 GDBusAuthObserver *observer,
2050 GCancellable *cancellable,
2053 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2054 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2055 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2061 "authentication-observer", observer,
2065 /* ---------------------------------------------------------------------------------------------------- */
2068 * g_dbus_connection_new_for_address:
2069 * @address: A D-Bus address.
2070 * @flags: Flags describing how to make the connection.
2071 * @cancellable: A #GCancellable or %NULL.
2072 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2073 * @user_data: The data to pass to @callback.
2075 * Asynchronously connects and sets up a D-Bus client connection for
2076 * exchanging D-Bus messages with an endpoint specified by @address
2077 * which must be in the D-Bus address format.
2079 * This constructor can only be used to initiate client-side
2080 * connections - use g_dbus_connection_new() if you need to act as the
2081 * server. In particular, @flags cannot contain the
2082 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2083 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2085 * When the operation is finished, @callback will be invoked. You can
2086 * then call g_dbus_connection_new_finish() to get the result of the
2089 * This is a asynchronous failable constructor. See
2090 * g_dbus_connection_new_for_address_sync() for the synchronous
2096 g_dbus_connection_new_for_address (const gchar *address,
2097 GDBusConnectionFlags flags,
2098 GCancellable *cancellable,
2099 GAsyncReadyCallback callback,
2102 g_return_if_fail (address != NULL);
2103 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2114 * g_dbus_connection_new_for_address_finish:
2115 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2116 * @error: Return location for error or %NULL.
2118 * Finishes an operation started with g_dbus_connection_new_for_address().
2120 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2125 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2129 GObject *source_object;
2131 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2132 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2134 source_object = g_async_result_get_source_object (res);
2135 g_assert (source_object != NULL);
2136 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2139 g_object_unref (source_object);
2141 return G_DBUS_CONNECTION (object);
2147 * g_dbus_connection_new_for_address_sync:
2148 * @address: A D-Bus address.
2149 * @flags: Flags describing how to make the connection.
2150 * @cancellable: A #GCancellable or %NULL.
2151 * @error: Return location for error or %NULL.
2153 * Synchronously connects and sets up a D-Bus client connection for
2154 * exchanging D-Bus messages with an endpoint specified by @address
2155 * which must be in the D-Bus address format.
2157 * This constructor can only be used to initiate client-side
2158 * connections - use g_dbus_connection_new_sync() if you need to act
2159 * as the server. In particular, @flags cannot contain the
2160 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2161 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2163 * This is a synchronous failable constructor. See
2164 * g_dbus_connection_new_for_address() for the asynchronous version.
2166 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2171 g_dbus_connection_new_for_address_sync (const gchar *address,
2172 GDBusConnectionFlags flags,
2173 GCancellable *cancellable,
2176 g_return_val_if_fail (address != NULL, NULL);
2177 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2178 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2186 /* ---------------------------------------------------------------------------------------------------- */
2189 * g_dbus_connection_set_exit_on_close:
2190 * @connection: A #GDBusConnection.
2191 * @exit_on_close: Whether the process should be terminated
2192 * when @connection is closed by the remote peer.
2194 * Sets whether the process should be terminated when @connection is
2195 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2201 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2202 gboolean exit_on_close)
2204 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2205 connection->priv->exit_on_close = exit_on_close;
2209 * g_dbus_connection_get_exit_on_close:
2210 * @connection: A #GDBusConnection.
2212 * Gets whether the process is terminated when @connection is
2213 * closed by the remote peer. See
2214 * #GDBusConnection:exit-on-close for more details.
2216 * Returns: Whether the process is terminated when @connection is
2217 * closed by the remote peer.
2222 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2224 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2225 return connection->priv->exit_on_close;
2229 * g_dbus_connection_get_guid:
2230 * @connection: A #GDBusConnection.
2232 * The GUID of the peer performing the role of server when
2233 * authenticating. See #GDBusConnection:guid for more details.
2235 * Returns: The GUID. Do not free this string, it is owned by
2241 g_dbus_connection_get_guid (GDBusConnection *connection)
2243 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2244 return connection->priv->guid;
2248 * g_dbus_connection_get_unique_name:
2249 * @connection: A #GDBusConnection.
2251 * Gets the unique name of @connection as assigned by the message
2252 * bus. This can also be used to figure out if @connection is a
2253 * message bus connection.
2255 * Returns: The unique name or %NULL if @connection is not a message
2256 * bus connection. Do not free this string, it is owned by
2262 g_dbus_connection_get_unique_name (GDBusConnection *connection)
2264 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2265 return connection->priv->bus_unique_name;
2269 * g_dbus_connection_get_peer_credentials:
2270 * @connection: A #GDBusConnection.
2272 * Gets the credentials of the authenticated peer. This will always
2273 * return %NULL unless @connection acted as a server
2274 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
2275 * when set up and the client passed credentials as part of the
2276 * authentication process.
2278 * In a message bus setup, the message bus is always the server and
2279 * each application is a client. So this method will always return
2280 * %NULL for message bus clients.
2282 * Returns: A #GCredentials or %NULL if not available. Do not free
2283 * this object, it is owned by @connection.
2288 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
2290 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2291 return connection->priv->crendentials;
2294 /* ---------------------------------------------------------------------------------------------------- */
2296 static guint _global_filter_id = 1;
2299 * g_dbus_connection_add_filter:
2300 * @connection: A #GDBusConnection.
2301 * @filter_function: A filter function.
2302 * @user_data: User data to pass to @filter_function.
2303 * @user_data_free_func: Function to free @user_data with when filter
2304 * is removed or %NULL.
2306 * Adds a message filter. Filters are handlers that are run on all
2307 * incoming messages, prior to standard dispatch. Filters are run in
2308 * the order that they were added. The same handler can be added as a
2309 * filter more than once, in which case it will be run more than once.
2310 * Filters added during a filter callback won't be run on the message
2313 * Note that filters are run in a dedicated message handling thread so
2314 * they can't block and, generally, can't do anything but signal a
2315 * worker thread. Also note that filters are rarely needed - use API
2316 * such as g_dbus_connection_send_message_with_reply(),
2317 * g_dbus_connection_signal_subscribe() or
2318 * g_dbus_connection_call() instead.
2320 * Returns: A filter identifier that can be used with
2321 * g_dbus_connection_remove_filter().
2326 g_dbus_connection_add_filter (GDBusConnection *connection,
2327 GDBusMessageFilterFunction filter_function,
2329 GDestroyNotify user_data_free_func)
2333 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2334 g_return_val_if_fail (filter_function != NULL, 0);
2336 CONNECTION_LOCK (connection);
2337 data = g_new0 (FilterData, 1);
2338 data->id = _global_filter_id++; /* TODO: overflow etc. */
2339 data->filter_function = filter_function;
2340 data->user_data = user_data;
2341 data->user_data_free_func = user_data_free_func;
2342 g_ptr_array_add (connection->priv->filters, data);
2343 CONNECTION_UNLOCK (connection);
2348 /* only called from finalize(), removes all filters */
2350 purge_all_filters (GDBusConnection *connection)
2353 for (n = 0; n < connection->priv->filters->len; n++)
2355 FilterData *data = connection->priv->filters->pdata[n];
2356 if (data->user_data_free_func != NULL)
2357 data->user_data_free_func (data->user_data);
2363 * g_dbus_connection_remove_filter:
2364 * @connection: a #GDBusConnection
2365 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
2372 g_dbus_connection_remove_filter (GDBusConnection *connection,
2376 FilterData *to_destroy;
2378 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2380 CONNECTION_LOCK (connection);
2382 for (n = 0; n < connection->priv->filters->len; n++)
2384 FilterData *data = connection->priv->filters->pdata[n];
2385 if (data->id == filter_id)
2387 g_ptr_array_remove_index (connection->priv->filters, n);
2392 CONNECTION_UNLOCK (connection);
2394 /* do free without holding lock */
2395 if (to_destroy != NULL)
2397 if (to_destroy->user_data_free_func != NULL)
2398 to_destroy->user_data_free_func (to_destroy->user_data);
2399 g_free (to_destroy);
2403 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
2407 /* ---------------------------------------------------------------------------------------------------- */
2413 gchar *interface_name;
2417 GArray *subscribers;
2422 GDBusSignalCallback callback;
2424 GDestroyNotify user_data_free_func;
2426 GMainContext *context;
2430 signal_data_free (SignalData *data)
2432 g_free (data->rule);
2433 g_free (data->sender);
2434 g_free (data->interface_name);
2435 g_free (data->member);
2436 g_free (data->object_path);
2437 g_free (data->arg0);
2438 g_array_free (data->subscribers, TRUE);
2443 args_to_rule (const gchar *sender,
2444 const gchar *interface_name,
2445 const gchar *member,
2446 const gchar *object_path,
2451 rule = g_string_new ("type='signal'");
2453 g_string_append_printf (rule, ",sender='%s'", sender);
2454 if (interface_name != NULL)
2455 g_string_append_printf (rule, ",interface='%s'", interface_name);
2457 g_string_append_printf (rule, ",member='%s'", member);
2458 if (object_path != NULL)
2459 g_string_append_printf (rule, ",path='%s'", object_path);
2461 g_string_append_printf (rule, ",arg0='%s'", arg0);
2463 return g_string_free (rule, FALSE);
2466 static guint _global_subscriber_id = 1;
2467 static guint _global_registration_id = 1;
2468 static guint _global_subtree_registration_id = 1;
2470 /* ---------------------------------------------------------------------------------------------------- */
2472 /* must hold lock when calling */
2474 add_match_rule (GDBusConnection *connection,
2475 const gchar *match_rule)
2478 GDBusMessage *message;
2480 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2481 "/org/freedesktop/DBus", /* path */
2482 "org.freedesktop.DBus", /* interface */
2484 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2487 if (!g_dbus_connection_send_message_unlocked (connection,
2492 g_critical ("Error while sending AddMatch() message: %s", error->message);
2493 g_error_free (error);
2495 g_object_unref (message);
2498 /* ---------------------------------------------------------------------------------------------------- */
2500 /* must hold lock when calling */
2502 remove_match_rule (GDBusConnection *connection,
2503 const gchar *match_rule)
2506 GDBusMessage *message;
2508 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2509 "/org/freedesktop/DBus", /* path */
2510 "org.freedesktop.DBus", /* interface */
2512 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2515 if (!g_dbus_connection_send_message_unlocked (connection,
2520 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
2521 g_error_free (error);
2523 g_object_unref (message);
2526 /* ---------------------------------------------------------------------------------------------------- */
2529 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
2531 return g_strcmp0 (signal_data->sender, "org.freedesktop.DBus") == 0 &&
2532 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
2533 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
2534 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
2535 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
2538 /* ---------------------------------------------------------------------------------------------------- */
2541 * g_dbus_connection_signal_subscribe:
2542 * @connection: A #GDBusConnection.
2543 * @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.
2544 * @interface_name: D-Bus interface name to match on or %NULL to match on all interfaces.
2545 * @member: D-Bus signal name to match on or %NULL to match on all signals.
2546 * @object_path: Object path to match on or %NULL to match on all object paths.
2547 * @arg0: Contents of first string argument to match on or %NULL to match on all kinds of arguments.
2548 * @callback: Callback to invoke when there is a signal matching the requested data.
2549 * @user_data: User data to pass to @callback.
2550 * @user_data_free_func: Function to free @user_data with when subscription is removed or %NULL.
2552 * Subscribes to signals on @connection and invokes @callback with a
2553 * whenever the signal is received. Note that @callback
2554 * will be invoked in the <link
2555 * linkend="g-main-context-push-thread-default">thread-default main
2556 * loop</link> of the thread you are calling this method from.
2558 * It is considered a programming error to use this function if @connection is closed.
2560 * Note that if @sender is not <literal>org.freedesktop.DBus</literal> (for listening to signals from the
2561 * message bus daemon), then it needs to be a unique bus name or %NULL (for listening to signals from any
2562 * name) - you cannot pass a name like <literal>com.example.MyApp</literal>.
2563 * Use e.g. g_bus_watch_name() to find the unique name for the owner of the name you are interested in. Also note
2564 * that this function does not remove a subscription if @sender vanishes from the bus. You have to manually
2565 * call g_dbus_connection_signal_unsubscribe() to remove a subscription.
2567 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
2572 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
2573 const gchar *sender,
2574 const gchar *interface_name,
2575 const gchar *member,
2576 const gchar *object_path,
2578 GDBusSignalCallback callback,
2580 GDestroyNotify user_data_free_func)
2583 SignalData *signal_data;
2584 SignalSubscriber subscriber;
2585 GPtrArray *signal_data_array;
2587 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
2588 * an OOM condition. We might want to change that but that would involve making
2589 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
2590 * handle that. And there's really no sensible way of handling this short of retrying
2591 * to add the match rule... and then there's the little thing that, hey, maybe there's
2592 * a reason the bus in an OOM condition.
2594 * Doable, but not really sure it's worth it...
2597 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2598 g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
2599 g_return_val_if_fail (sender == NULL || ((strcmp (sender, "org.freedesktop.DBus") == 0 || sender[0] == ':') &&
2600 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
2601 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
2602 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
2603 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
2604 g_return_val_if_fail (callback != NULL, 0);
2606 CONNECTION_LOCK (connection);
2608 rule = args_to_rule (sender, interface_name, member, object_path, arg0);
2613 subscriber.callback = callback;
2614 subscriber.user_data = user_data;
2615 subscriber.user_data_free_func = user_data_free_func;
2616 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
2617 subscriber.context = g_main_context_get_thread_default ();
2618 if (subscriber.context != NULL)
2619 g_main_context_ref (subscriber.context);
2621 /* see if we've already have this rule */
2622 signal_data = g_hash_table_lookup (connection->priv->map_rule_to_signal_data, rule);
2623 if (signal_data != NULL)
2625 g_array_append_val (signal_data->subscribers, subscriber);
2630 signal_data = g_new0 (SignalData, 1);
2631 signal_data->rule = rule;
2632 signal_data->sender = g_strdup (sender);
2633 signal_data->interface_name = g_strdup (interface_name);
2634 signal_data->member = g_strdup (member);
2635 signal_data->object_path = g_strdup (object_path);
2636 signal_data->arg0 = g_strdup (arg0);
2637 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2638 g_array_append_val (signal_data->subscribers, subscriber);
2640 g_hash_table_insert (connection->priv->map_rule_to_signal_data,
2644 /* Add the match rule to the bus...
2646 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
2647 * always send such messages to us.
2649 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2651 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2652 add_match_rule (connection, signal_data->rule);
2656 g_hash_table_insert (connection->priv->map_id_to_signal_data,
2657 GUINT_TO_POINTER (subscriber.id),
2660 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array,
2661 signal_data->sender);
2662 if (signal_data_array == NULL)
2664 signal_data_array = g_ptr_array_new ();
2665 g_hash_table_insert (connection->priv->map_sender_to_signal_data_array,
2666 g_strdup (signal_data->sender),
2669 g_ptr_array_add (signal_data_array, signal_data);
2671 CONNECTION_UNLOCK (connection);
2673 return subscriber.id;
2676 /* ---------------------------------------------------------------------------------------------------- */
2678 /* must hold lock when calling this */
2680 unsubscribe_id_internal (GDBusConnection *connection,
2681 guint subscription_id,
2682 GArray *out_removed_subscribers)
2684 SignalData *signal_data;
2685 GPtrArray *signal_data_array;
2688 signal_data = g_hash_table_lookup (connection->priv->map_id_to_signal_data,
2689 GUINT_TO_POINTER (subscription_id));
2690 if (signal_data == NULL)
2692 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
2696 for (n = 0; n < signal_data->subscribers->len; n++)
2698 SignalSubscriber *subscriber;
2700 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
2701 if (subscriber->id != subscription_id)
2704 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_signal_data,
2705 GUINT_TO_POINTER (subscription_id)));
2706 g_array_append_val (out_removed_subscribers, *subscriber);
2707 g_array_remove_index (signal_data->subscribers, n);
2709 if (signal_data->subscribers->len == 0)
2710 g_warn_if_fail (g_hash_table_remove (connection->priv->map_rule_to_signal_data, signal_data->rule));
2712 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array,
2713 signal_data->sender);
2714 g_warn_if_fail (signal_data_array != NULL);
2715 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
2717 if (signal_data_array->len == 0)
2719 g_warn_if_fail (g_hash_table_remove (connection->priv->map_sender_to_signal_data_array, signal_data->sender));
2721 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
2722 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2724 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2725 remove_match_rule (connection, signal_data->rule);
2728 signal_data_free (signal_data);
2734 g_assert_not_reached ();
2741 * g_dbus_connection_signal_unsubscribe:
2742 * @connection: A #GDBusConnection.
2743 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
2745 * Unsubscribes from signals.
2750 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
2751 guint subscription_id)
2753 GArray *subscribers;
2756 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2758 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2760 CONNECTION_LOCK (connection);
2761 unsubscribe_id_internal (connection,
2764 CONNECTION_UNLOCK (connection);
2767 g_assert (subscribers->len == 0 || subscribers->len == 1);
2769 /* call GDestroyNotify without lock held */
2770 for (n = 0; n < subscribers->len; n++)
2772 SignalSubscriber *subscriber;
2773 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
2774 if (subscriber->user_data_free_func != NULL)
2775 subscriber->user_data_free_func (subscriber->user_data);
2776 if (subscriber->context != NULL)
2777 g_main_context_unref (subscriber->context);
2780 g_array_free (subscribers, TRUE);
2783 /* ---------------------------------------------------------------------------------------------------- */
2787 guint subscription_id;
2788 GDBusSignalCallback callback;
2790 GDBusMessage *message;
2791 GDBusConnection *connection;
2792 const gchar *sender;
2794 const gchar *interface;
2795 const gchar *member;
2798 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
2802 emit_signal_instance_in_idle_cb (gpointer data)
2804 SignalInstance *signal_instance = data;
2805 GVariant *parameters;
2806 gboolean has_subscription;
2808 parameters = g_dbus_message_get_body (signal_instance->message);
2809 if (parameters == NULL)
2811 parameters = g_variant_new ("()");
2812 g_variant_ref_sink (parameters);
2816 g_variant_ref_sink (parameters);
2820 g_debug ("in emit_signal_instance_in_idle_cb (sender=%s path=%s interface=%s member=%s params=%s)",
2821 signal_instance->sender,
2822 signal_instance->path,
2823 signal_instance->interface,
2824 signal_instance->member,
2825 g_variant_print (parameters, TRUE));
2828 /* Careful here, don't do the callback if we no longer has the subscription */
2829 CONNECTION_LOCK (signal_instance->connection);
2830 has_subscription = FALSE;
2831 if (g_hash_table_lookup (signal_instance->connection->priv->map_id_to_signal_data,
2832 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
2833 has_subscription = TRUE;
2834 CONNECTION_UNLOCK (signal_instance->connection);
2836 if (has_subscription)
2837 signal_instance->callback (signal_instance->connection,
2838 signal_instance->sender,
2839 signal_instance->path,
2840 signal_instance->interface,
2841 signal_instance->member,
2843 signal_instance->user_data);
2845 if (parameters != NULL)
2846 g_variant_unref (parameters);
2852 signal_instance_free (SignalInstance *signal_instance)
2854 g_object_unref (signal_instance->message);
2855 g_object_unref (signal_instance->connection);
2856 g_free (signal_instance);
2859 /* called in message handler thread WITH lock held */
2861 schedule_callbacks (GDBusConnection *connection,
2862 GPtrArray *signal_data_array,
2863 GDBusMessage *message,
2864 const gchar *sender)
2867 const gchar *interface;
2868 const gchar *member;
2877 interface = g_dbus_message_get_interface (message);
2878 member = g_dbus_message_get_member (message);
2879 path = g_dbus_message_get_path (message);
2880 arg0 = g_dbus_message_get_arg0 (message);
2883 g_debug ("sender = `%s'", sender);
2884 g_debug ("interface = `%s'", interface);
2885 g_debug ("member = `%s'", member);
2886 g_debug ("path = `%s'", path);
2887 g_debug ("arg0 = `%s'", arg0);
2890 /* TODO: if this is slow, then we can change signal_data_array into
2891 * map_object_path_to_signal_data_array or something.
2893 for (n = 0; n < signal_data_array->len; n++)
2895 SignalData *signal_data = signal_data_array->pdata[n];
2897 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
2900 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
2903 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
2906 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
2909 for (m = 0; m < signal_data->subscribers->len; m++)
2911 SignalSubscriber *subscriber;
2912 GSource *idle_source;
2913 SignalInstance *signal_instance;
2915 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
2917 signal_instance = g_new0 (SignalInstance, 1);
2918 signal_instance->subscription_id = subscriber->id;
2919 signal_instance->callback = subscriber->callback;
2920 signal_instance->user_data = subscriber->user_data;
2921 signal_instance->message = g_object_ref (message);
2922 signal_instance->connection = g_object_ref (connection);
2923 signal_instance->sender = sender;
2924 signal_instance->path = path;
2925 signal_instance->interface = interface;
2926 signal_instance->member = member;
2928 idle_source = g_idle_source_new ();
2929 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
2930 g_source_set_callback (idle_source,
2931 emit_signal_instance_in_idle_cb,
2933 (GDestroyNotify) signal_instance_free);
2934 g_source_attach (idle_source, subscriber->context);
2935 g_source_unref (idle_source);
2940 /* called in message handler thread with lock held */
2942 distribute_signals (GDBusConnection *connection,
2943 GDBusMessage *message)
2945 GPtrArray *signal_data_array;
2946 const gchar *sender;
2948 sender = g_dbus_message_get_sender (message);
2950 /* collect subscribers that match on sender */
2953 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array, sender);
2954 if (signal_data_array != NULL)
2955 schedule_callbacks (connection, signal_data_array, message, sender);
2958 /* collect subscribers not matching on sender */
2959 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array, "");
2960 if (signal_data_array != NULL)
2961 schedule_callbacks (connection, signal_data_array, message, sender);
2964 /* ---------------------------------------------------------------------------------------------------- */
2966 /* only called from finalize(), removes all subscriptions */
2968 purge_all_signal_subscriptions (GDBusConnection *connection)
2970 GHashTableIter iter;
2973 GArray *subscribers;
2976 ids = g_array_new (FALSE, FALSE, sizeof (guint));
2977 g_hash_table_iter_init (&iter, connection->priv->map_id_to_signal_data);
2978 while (g_hash_table_iter_next (&iter, &key, NULL))
2980 guint subscription_id = GPOINTER_TO_UINT (key);
2981 g_array_append_val (ids, subscription_id);
2984 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2985 for (n = 0; n < ids->len; n++)
2987 guint subscription_id = g_array_index (ids, guint, n);
2988 unsubscribe_id_internal (connection,
2992 g_array_free (ids, TRUE);
2994 /* call GDestroyNotify without lock held */
2995 for (n = 0; n < subscribers->len; n++)
2997 SignalSubscriber *subscriber;
2998 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
2999 if (subscriber->user_data_free_func != NULL)
3000 subscriber->user_data_free_func (subscriber->user_data);
3001 if (subscriber->context != NULL)
3002 g_main_context_unref (subscriber->context);
3005 g_array_free (subscribers, TRUE);
3008 /* ---------------------------------------------------------------------------------------------------- */
3010 struct ExportedObject
3013 GDBusConnection *connection;
3015 /* maps gchar* -> ExportedInterface* */
3016 GHashTable *map_if_name_to_ei;
3019 /* only called with lock held */
3021 exported_object_free (ExportedObject *eo)
3023 g_free (eo->object_path);
3024 g_hash_table_unref (eo->map_if_name_to_ei);
3033 gchar *interface_name;
3034 const GDBusInterfaceVTable *vtable;
3035 const GDBusInterfaceInfo *introspection_data;
3037 GMainContext *context;
3039 GDestroyNotify user_data_free_func;
3040 } ExportedInterface;
3042 /* called with lock held */
3044 exported_interface_free (ExportedInterface *ei)
3046 if (ei->user_data_free_func != NULL)
3047 /* TODO: push to thread-default mainloop */
3048 ei->user_data_free_func (ei->user_data);
3050 if (ei->context != NULL)
3051 g_main_context_unref (ei->context);
3053 g_free (ei->interface_name);
3057 /* ---------------------------------------------------------------------------------------------------- */
3061 GDBusConnection *connection;
3062 GDBusMessage *message;
3064 const char *property_name;
3065 const GDBusInterfaceVTable *vtable;
3066 const GDBusInterfaceInfo *interface_info;
3067 const GDBusPropertyInfo *property_info;
3071 property_data_free (PropertyData *data)
3073 g_object_unref (data->connection);
3074 g_object_unref (data->message);
3078 /* called in thread where object was registered - no locks held */
3080 invoke_get_property_in_idle_cb (gpointer _data)
3082 PropertyData *data = _data;
3085 GDBusMessage *reply;
3088 value = data->vtable->get_property (data->connection,
3089 g_dbus_message_get_sender (data->message),
3090 g_dbus_message_get_path (data->message),
3091 data->interface_info->name,
3092 data->property_name,
3099 g_assert_no_error (error);
3101 g_variant_ref_sink (value);
3102 reply = g_dbus_message_new_method_reply (data->message);
3103 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
3104 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3105 g_variant_unref (value);
3106 g_object_unref (reply);
3110 gchar *dbus_error_name;
3112 g_assert (error != NULL);
3114 dbus_error_name = g_dbus_error_encode_gerror (error);
3115 reply = g_dbus_message_new_method_error_literal (data->message,
3118 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3119 g_free (dbus_error_name);
3120 g_error_free (error);
3121 g_object_unref (reply);
3127 /* called in thread where object was registered - no locks held */
3129 invoke_set_property_in_idle_cb (gpointer _data)
3131 PropertyData *data = _data;
3133 GDBusMessage *reply;
3139 g_variant_get (g_dbus_message_get_body (data->message),
3145 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
3146 * of the given value is wrong
3148 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
3150 reply = g_dbus_message_new_method_error (data->message,
3151 "org.freedesktop.DBus.Error.InvalidArgs",
3152 _("Error setting property `%s': Expected type `%s' but got `%s'"),
3153 data->property_info->name,
3154 data->property_info->signature,
3155 g_variant_get_type_string (value));
3159 if (!data->vtable->set_property (data->connection,
3160 g_dbus_message_get_sender (data->message),
3161 g_dbus_message_get_path (data->message),
3162 data->interface_info->name,
3163 data->property_name,
3168 gchar *dbus_error_name;
3169 g_assert (error != NULL);
3170 dbus_error_name = g_dbus_error_encode_gerror (error);
3171 reply = g_dbus_message_new_method_error_literal (data->message,
3174 g_free (dbus_error_name);
3175 g_error_free (error);
3179 reply = g_dbus_message_new_method_reply (data->message);
3183 g_assert (reply != NULL);
3184 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3185 g_object_unref (reply);
3190 /* called with lock held */
3192 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
3193 GDBusMessage *message,
3195 const GDBusInterfaceInfo *introspection_data,
3196 const GDBusInterfaceVTable *vtable,
3197 GMainContext *main_context,
3201 const char *interface_name;
3202 const char *property_name;
3203 const GDBusPropertyInfo *property_info;
3204 GSource *idle_source;
3205 PropertyData *property_data;
3206 GDBusMessage *reply;
3211 g_variant_get (g_dbus_message_get_body (message),
3216 g_variant_get (g_dbus_message_get_body (message),
3225 if (vtable == NULL || vtable->get_property == NULL)
3230 if (vtable == NULL || vtable->set_property == NULL)
3234 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
3236 property_info = NULL;
3238 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3239 property_info = g_dbus_interface_info_lookup_property (introspection_data, property_name);
3240 if (property_info == NULL)
3242 reply = g_dbus_message_new_method_error (message,
3243 "org.freedesktop.DBus.Error.InvalidArgs",
3244 _("No such property `%s'"),
3246 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3247 g_object_unref (reply);
3252 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3254 reply = g_dbus_message_new_method_error (message,
3255 "org.freedesktop.DBus.Error.InvalidArgs",
3256 _("Property `%s' is not readable"),
3258 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3259 g_object_unref (reply);
3263 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
3265 reply = g_dbus_message_new_method_error (message,
3266 "org.freedesktop.DBus.Error.InvalidArgs",
3267 _("Property `%s' is not writable"),
3269 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3270 g_object_unref (reply);
3275 /* ok, got the property info - call user code in an idle handler */
3276 property_data = g_new0 (PropertyData, 1);
3277 property_data->connection = g_object_ref (connection);
3278 property_data->message = g_object_ref (message);
3279 property_data->user_data = user_data;
3280 property_data->property_name = property_name;
3281 property_data->vtable = vtable;
3282 property_data->interface_info = introspection_data;
3283 property_data->property_info = property_info;
3285 idle_source = g_idle_source_new ();
3286 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3287 g_source_set_callback (idle_source,
3288 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
3290 (GDestroyNotify) property_data_free);
3291 g_source_attach (idle_source, main_context);
3292 g_source_unref (idle_source);
3300 /* called with lock held */
3302 handle_getset_property (GDBusConnection *connection,
3304 GDBusMessage *message,
3307 ExportedInterface *ei;
3309 const char *interface_name;
3310 const char *property_name;
3315 g_variant_get (g_dbus_message_get_body (message),
3320 g_variant_get (g_dbus_message_get_body (message),
3326 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3327 * no such interface registered
3329 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3332 GDBusMessage *reply;
3333 reply = g_dbus_message_new_method_error (message,
3334 "org.freedesktop.DBus.Error.InvalidArgs",
3335 _("No such interface `%s'"),
3337 g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3338 g_object_unref (reply);
3343 handled = validate_and_maybe_schedule_property_getset (eo->connection,
3346 ei->introspection_data,
3354 /* ---------------------------------------------------------------------------------------------------- */
3358 GDBusConnection *connection;
3359 GDBusMessage *message;
3361 const GDBusInterfaceVTable *vtable;
3362 const GDBusInterfaceInfo *interface_info;
3363 } PropertyGetAllData;
3366 property_get_all_data_free (PropertyData *data)
3368 g_object_unref (data->connection);
3369 g_object_unref (data->message);
3373 /* called in thread where object was registered - no locks held */
3375 invoke_get_all_properties_in_idle_cb (gpointer _data)
3377 PropertyGetAllData *data = _data;
3378 GVariantBuilder *builder;
3382 GDBusMessage *reply;
3387 /* TODO: Right now we never fail this call - we just omit values if
3388 * a get_property() call is failing.
3390 * We could fail the whole call if just a single get_property() call
3391 * returns an error. We need clarification in the D-Bus spec about this.
3393 builder = g_variant_builder_new (G_VARIANT_TYPE_ARRAY);
3394 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
3396 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
3399 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3402 value = data->vtable->get_property (data->connection,
3403 g_dbus_message_get_sender (data->message),
3404 g_dbus_message_get_path (data->message),
3405 data->interface_info->name,
3406 property_info->name,
3413 g_variant_ref_sink (value);
3414 g_variant_builder_add (builder,
3416 property_info->name,
3418 g_variant_unref (value);
3420 result = g_variant_builder_end (builder);
3422 builder = g_variant_builder_new (G_VARIANT_TYPE_TUPLE);
3423 g_variant_builder_add_value (builder, result); /* steals result since result is floating */
3424 packed = g_variant_builder_end (builder);
3426 reply = g_dbus_message_new_method_reply (data->message);
3427 g_dbus_message_set_body (reply, packed);
3428 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3429 g_object_unref (reply);
3434 /* called with lock held */
3436 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
3437 GDBusMessage *message,
3438 const GDBusInterfaceInfo *introspection_data,
3439 const GDBusInterfaceVTable *vtable,
3440 GMainContext *main_context,
3444 const char *interface_name;
3445 GSource *idle_source;
3446 PropertyGetAllData *property_get_all_data;
3450 g_variant_get (g_dbus_message_get_body (message),
3454 if (vtable == NULL || vtable->get_property == NULL)
3457 /* ok, got the property info - call user in an idle handler */
3458 property_get_all_data = g_new0 (PropertyGetAllData, 1);
3459 property_get_all_data->connection = g_object_ref (connection);
3460 property_get_all_data->message = g_object_ref (message);
3461 property_get_all_data->user_data = user_data;
3462 property_get_all_data->vtable = vtable;
3463 property_get_all_data->interface_info = introspection_data;
3465 idle_source = g_idle_source_new ();
3466 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3467 g_source_set_callback (idle_source,
3468 invoke_get_all_properties_in_idle_cb,
3469 property_get_all_data,
3470 (GDestroyNotify) property_get_all_data_free);
3471 g_source_attach (idle_source, main_context);
3472 g_source_unref (idle_source);
3480 /* called with lock held */
3482 handle_get_all_properties (GDBusConnection *connection,
3484 GDBusMessage *message)
3486 ExportedInterface *ei;
3488 const char *interface_name;
3492 g_variant_get (g_dbus_message_get_body (message),
3496 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3497 * no such interface registered
3499 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3502 GDBusMessage *reply;
3503 reply = g_dbus_message_new_method_error (message,
3504 "org.freedesktop.DBus.Error.InvalidArgs",
3505 _("No such interface"),
3507 g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3508 g_object_unref (reply);
3513 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
3515 ei->introspection_data,
3523 /* ---------------------------------------------------------------------------------------------------- */
3525 static const gchar introspect_header[] =
3526 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
3527 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
3528 "<!-- GDBus " PACKAGE_VERSION " -->\n"
3531 static const gchar introspect_tail[] =
3534 static const gchar introspect_standard_interfaces[] =
3535 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
3536 " <method name=\"Get\">\n"
3537 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3538 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3539 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
3541 " <method name=\"GetAll\">\n"
3542 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3543 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
3545 " <method name=\"Set\">\n"
3546 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3547 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3548 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
3550 " <signal name=\"PropertiesChanged\">\n"
3551 " <arg type=\"s\" name=\"interface_name\"/>\n"
3552 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
3553 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
3556 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
3557 " <method name=\"Introspect\">\n"
3558 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
3561 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
3562 " <method name=\"Ping\"/>\n"
3563 " <method name=\"GetMachineId\">\n"
3564 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
3569 introspect_append_header (GString *s)
3571 g_string_append (s, introspect_header);
3575 introspect_append_standard_interfaces (GString *s)
3577 g_string_append (s, introspect_standard_interfaces);
3581 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
3583 if (g_str_has_prefix (object_path, path) && strlen (object_path) >= path_len)
3589 begin = object_path + path_len;
3590 end = strchr (begin, '/');
3593 s = g_strndup (begin, end - begin);
3595 s = g_strdup (begin);
3597 if (g_hash_table_lookup (set, s) == NULL)
3598 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
3604 /* TODO: we want a nicer public interface for this */
3606 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
3611 GHashTableIter hash_iter;
3612 const gchar *object_path;
3618 CONNECTION_ENSURE_LOCK (connection);
3620 path_len = strlen (path);
3624 set = g_hash_table_new (g_str_hash, g_str_equal);
3626 g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_eo);
3627 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3628 maybe_add_path (path, path_len, object_path, set);
3630 g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_es);
3631 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3632 maybe_add_path (path, path_len, object_path, set);
3634 p = g_ptr_array_new ();
3635 keys = g_hash_table_get_keys (set);
3636 for (l = keys; l != NULL; l = l->next)
3637 g_ptr_array_add (p, l->data);
3638 g_hash_table_unref (set);
3641 g_ptr_array_add (p, NULL);
3642 ret = (gchar **) g_ptr_array_free (p, FALSE);
3647 g_dbus_connection_list_registered (GDBusConnection *connection,
3651 CONNECTION_LOCK (connection);
3652 ret = g_dbus_connection_list_registered_unlocked (connection, path);
3653 CONNECTION_UNLOCK (connection);
3657 /* called in message handler thread with lock held */
3659 handle_introspect (GDBusConnection *connection,
3661 GDBusMessage *message)
3665 GDBusMessage *reply;
3666 GHashTableIter hash_iter;
3667 ExportedInterface *ei;
3670 /* first the header with the standard interfaces */
3671 s = g_string_sized_new (sizeof (introspect_header) +
3672 sizeof (introspect_standard_interfaces) +
3673 sizeof (introspect_tail));
3674 introspect_append_header (s);
3675 introspect_append_standard_interfaces (s);
3677 /* then include the registered interfaces */
3678 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
3679 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
3680 g_dbus_interface_info_generate_xml (ei->introspection_data, 2, s);
3682 /* finally include nodes registered below us */
3683 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
3684 for (n = 0; registered != NULL && registered[n] != NULL; n++)
3685 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
3686 g_strfreev (registered);
3687 g_string_append (s, introspect_tail);
3689 reply = g_dbus_message_new_method_reply (message);
3690 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
3691 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3692 g_object_unref (reply);
3693 g_string_free (s, TRUE);
3698 /* called in thread where object was registered - no locks held */
3700 call_in_idle_cb (gpointer user_data)
3702 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
3703 GDBusInterfaceVTable *vtable;
3705 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
3706 g_assert (vtable != NULL && vtable->method_call != NULL);
3708 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
3709 g_dbus_method_invocation_get_sender (invocation),
3710 g_dbus_method_invocation_get_object_path (invocation),
3711 g_dbus_method_invocation_get_interface_name (invocation),
3712 g_dbus_method_invocation_get_method_name (invocation),
3713 g_dbus_method_invocation_get_parameters (invocation),
3714 g_object_ref (invocation),
3715 g_dbus_method_invocation_get_user_data (invocation));
3720 /* called in message handler thread with lock held */
3722 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
3723 GDBusMessage *message,
3724 const GDBusInterfaceInfo *introspection_data,
3725 const GDBusInterfaceVTable *vtable,
3726 GMainContext *main_context,
3729 GDBusMethodInvocation *invocation;
3730 const GDBusMethodInfo *method_info;
3731 GDBusMessage *reply;
3732 GVariant *parameters;
3733 GSource *idle_source;
3735 gchar *in_signature;
3739 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3740 method_info = g_dbus_interface_info_lookup_method (introspection_data, g_dbus_message_get_member (message));
3742 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
3743 * error to the caller
3745 if (method_info == NULL)
3747 reply = g_dbus_message_new_method_error (message,
3748 "org.freedesktop.DBus.Error.UnknownMethod",
3749 _("No such method `%s'"),
3750 g_dbus_message_get_member (message));
3751 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3752 g_object_unref (reply);
3757 /* Check that the incoming args are of the right type - if they are not, return
3758 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
3760 * TODO: might also be worth caching the combined signature.
3762 in_signature = _g_dbus_compute_complete_signature (method_info->in_args, FALSE);
3763 if (g_strcmp0 (g_dbus_message_get_signature (message), in_signature) != 0)
3765 reply = g_dbus_message_new_method_error (message,
3766 "org.freedesktop.DBus.Error.InvalidArgs",
3767 _("Signature of message, `%s', does not match expected signature `%s'"),
3768 g_dbus_message_get_signature (message),
3770 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3771 g_object_unref (reply);
3772 g_free (in_signature);
3776 g_free (in_signature);
3778 parameters = g_dbus_message_get_body (message);
3779 if (parameters == NULL)
3781 parameters = g_variant_new ("()");
3782 g_variant_ref_sink (parameters);
3786 g_variant_ref (parameters);
3789 /* schedule the call in idle */
3790 invocation = g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
3791 g_dbus_message_get_path (message),
3792 g_dbus_message_get_interface (message),
3793 g_dbus_message_get_member (message),
3799 g_variant_unref (parameters);
3800 g_object_set_data (G_OBJECT (invocation),
3801 "g-dbus-interface-vtable",
3804 idle_source = g_idle_source_new ();
3805 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3806 g_source_set_callback (idle_source,
3810 g_source_attach (idle_source, main_context);
3811 g_source_unref (idle_source);
3819 /* ---------------------------------------------------------------------------------------------------- */
3821 /* called in message handler thread with lock held */
3823 obj_message_func (GDBusConnection *connection,
3825 GDBusMessage *message)
3827 const gchar *interface_name;
3828 const gchar *member;
3829 const gchar *signature;
3834 interface_name = g_dbus_message_get_interface (message);
3835 member = g_dbus_message_get_member (message);
3836 signature = g_dbus_message_get_signature (message);
3838 /* see if we have an interface for handling this call */
3839 if (interface_name != NULL)
3841 ExportedInterface *ei;
3842 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3845 /* we do - invoke the handler in idle in the right thread */
3847 /* handle no vtable or handler being present */
3848 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
3851 handled = validate_and_maybe_schedule_method_call (connection,
3853 ei->introspection_data,
3861 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
3862 g_strcmp0 (member, "Introspect") == 0 &&
3863 g_strcmp0 (signature, "") == 0)
3865 handled = handle_introspect (connection, eo, message);
3868 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3869 g_strcmp0 (member, "Get") == 0 &&
3870 g_strcmp0 (signature, "ss") == 0)
3872 handled = handle_getset_property (connection, eo, message, TRUE);
3875 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3876 g_strcmp0 (member, "Set") == 0 &&
3877 g_strcmp0 (signature, "ssv") == 0)
3879 handled = handle_getset_property (connection, eo, message, FALSE);
3882 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3883 g_strcmp0 (member, "GetAll") == 0 &&
3884 g_strcmp0 (signature, "s") == 0)
3886 handled = handle_get_all_properties (connection, eo, message);
3895 * g_dbus_connection_register_object:
3896 * @connection: A #GDBusConnection.
3897 * @object_path: The object path to register at.
3898 * @introspection_data: Introspection data for the interface.
3899 * @vtable: A #GDBusInterfaceVTable to call into or %NULL.
3900 * @user_data: Data to pass to functions in @vtable.
3901 * @user_data_free_func: Function to call when the object path is unregistered.
3902 * @error: Return location for error or %NULL.
3904 * Registers callbacks for exported objects at @object_path with the
3905 * D-Bus interface that is described in @introspection_data.
3907 * Calls to functions in @vtable (and @user_data_free_func) will
3908 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
3909 * loop</link> of the thread you are calling this method from.
3911 * Note that all #GVariant values passed to functions in @vtable will match
3912 * the signature given in @introspection_data - if a remote caller passes
3913 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
3914 * is returned to the remote caller.
3916 * Additionally, if the remote caller attempts to invoke methods or
3917 * access properties not mentioned in @introspection_data the
3918 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
3919 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
3920 * are returned to the caller.
3922 * It is considered a programming error if the
3923 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
3924 * #GVariant of incorrect type.
3926 * If an existing callback is already registered at @object_path and
3927 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
3929 * GDBus automatically implements the standard D-Bus interfaces
3930 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
3931 * and org.freedesktop.Peer, so you don't have to implement those for
3932 * the objects you export. You <emphasis>can</emphasis> implement
3933 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
3934 * and setting of properties asynchronously.
3936 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
3938 * Returns: 0 if @error is set, otherwise a registration id (never 0)
3939 * that can be used with g_dbus_connection_unregister_object() .
3944 g_dbus_connection_register_object (GDBusConnection *connection,
3945 const gchar *object_path,
3946 const GDBusInterfaceInfo *introspection_data,
3947 const GDBusInterfaceVTable *vtable,
3949 GDestroyNotify user_data_free_func,
3953 ExportedInterface *ei;
3956 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3957 g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
3958 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
3959 g_return_val_if_fail (introspection_data != NULL, 0);
3960 g_return_val_if_fail (g_dbus_is_interface_name (introspection_data->name), 0);
3961 g_return_val_if_fail (error == NULL || *error == NULL, 0);
3965 CONNECTION_LOCK (connection);
3967 eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
3970 eo = g_new0 (ExportedObject, 1);
3971 eo->object_path = g_strdup (object_path);
3972 eo->connection = connection;
3973 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
3976 (GDestroyNotify) exported_interface_free);
3977 g_hash_table_insert (connection->priv->map_object_path_to_eo, eo->object_path, eo);
3980 ei = g_hash_table_lookup (eo->map_if_name_to_ei, introspection_data->name);
3986 _("An object is already exported for the interface %s at %s"),
3987 introspection_data->name,
3992 ei = g_new0 (ExportedInterface, 1);
3993 ei->id = _global_registration_id++; /* TODO: overflow etc. */
3995 ei->user_data = user_data;
3996 ei->user_data_free_func = user_data_free_func;
3997 ei->vtable = vtable;
3998 ei->introspection_data = introspection_data;
3999 ei->interface_name = g_strdup (introspection_data->name);
4000 ei->context = g_main_context_get_thread_default ();
4001 if (ei->context != NULL)
4002 g_main_context_ref (ei->context);
4004 g_hash_table_insert (eo->map_if_name_to_ei,
4005 (gpointer) ei->interface_name,
4007 g_hash_table_insert (connection->priv->map_id_to_ei,
4008 GUINT_TO_POINTER (ei->id),
4014 CONNECTION_UNLOCK (connection);
4020 * g_dbus_connection_unregister_object:
4021 * @connection: A #GDBusConnection.
4022 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
4024 * Unregisters an object.
4026 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
4031 g_dbus_connection_unregister_object (GDBusConnection *connection,
4032 guint registration_id)
4034 ExportedInterface *ei;
4038 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4042 CONNECTION_LOCK (connection);
4044 ei = g_hash_table_lookup (connection->priv->map_id_to_ei,
4045 GUINT_TO_POINTER (registration_id));
4051 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
4052 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
4053 /* unregister object path if we have no more exported interfaces */
4054 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
4055 g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_eo,
4061 CONNECTION_UNLOCK (connection);
4066 /* ---------------------------------------------------------------------------------------------------- */
4069 * g_dbus_connection_emit_signal:
4070 * @connection: A #GDBusConnection.
4071 * @destination_bus_name: The unique bus name for the destination for the signal or %NULL to emit to all listeners.
4072 * @object_path: Path of remote object.
4073 * @interface_name: D-Bus interface to emit a signal on.
4074 * @signal_name: The name of the signal to emit.
4075 * @parameters: A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
4076 * @error: Return location for error or %NULL.
4080 * This can only fail if @parameters is not compatible with the D-Bus protocol.
4082 * Returns: %TRUE unless @error is set.
4087 g_dbus_connection_emit_signal (GDBusConnection *connection,
4088 const gchar *destination_bus_name,
4089 const gchar *object_path,
4090 const gchar *interface_name,
4091 const gchar *signal_name,
4092 GVariant *parameters,
4095 GDBusMessage *message;
4101 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4102 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
4103 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
4104 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
4105 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
4106 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
4108 message = g_dbus_message_new_signal (object_path,
4112 if (destination_bus_name != NULL)
4113 g_dbus_message_set_header (message,
4114 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
4115 g_variant_new_string (destination_bus_name));
4117 if (parameters != NULL)
4118 g_dbus_message_set_body (message, parameters);
4120 ret = g_dbus_connection_send_message (connection, message, NULL, error);
4121 g_object_unref (message);
4127 add_call_flags (GDBusMessage *message,
4128 GDBusCallFlags flags)
4130 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
4131 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
4135 * g_dbus_connection_call:
4136 * @connection: A #GDBusConnection.
4137 * @bus_name: A unique or well-known bus name or %NULL if @connection is not a message bus connection.
4138 * @object_path: Path of remote object.
4139 * @interface_name: D-Bus interface to invoke method on.
4140 * @method_name: The name of the method to invoke.
4141 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4142 * @flags: Flags from the #GDBusCallFlags enumeration.
4143 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4144 * @cancellable: A #GCancellable or %NULL.
4145 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
4146 * care about the result of the method invocation.
4147 * @user_data: The data to pass to @callback.
4149 * Asynchronously invokes the @method_name method on the
4150 * @interface_name D-Bus interface on the remote object at
4151 * @object_path owned by @bus_name.
4153 * If @connection is closed then the operation will fail with
4154 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
4155 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
4156 * not compatible with the D-Bus protocol, the operation fails with
4157 * %G_IO_ERROR_INVALID_ARGUMENT.
4159 * If the @parameters #GVariant is floating, it is consumed. This allows
4160 * convenient 'inline' use of g_variant_new(), e.g.:
4162 * g_dbus_connection_call (connection,
4163 * "org.freedesktop.StringThings",
4164 * "/org/freedesktop/StringThings",
4165 * "org.freedesktop.StringThings",
4167 * g_variant_new ("(ss)",
4170 * G_DBUS_CALL_FLAGS_NONE,
4173 * (GAsyncReadyCallback) two_strings_done,
4177 * This is an asynchronous method. When the operation is finished, @callback will be invoked
4178 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
4179 * of the thread you are calling this method from. You can then call
4180 * g_dbus_connection_call_finish() to get the result of the operation.
4181 * See g_dbus_connection_call_sync() for the synchronous version of this
4187 g_dbus_connection_call (GDBusConnection *connection,
4188 const gchar *bus_name,
4189 const gchar *object_path,
4190 const gchar *interface_name,
4191 const gchar *method_name,
4192 GVariant *parameters,
4193 GDBusCallFlags flags,
4195 GCancellable *cancellable,
4196 GAsyncReadyCallback callback,
4199 GDBusMessage *message;
4201 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4202 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
4203 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
4204 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
4205 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
4206 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
4207 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
4209 message = g_dbus_message_new_method_call (bus_name,
4213 add_call_flags (message, flags);
4214 if (parameters != NULL)
4215 g_dbus_message_set_body (message, parameters);
4217 g_dbus_connection_send_message_with_reply (connection,
4220 NULL, /* volatile guint32 *out_serial */
4225 if (message != NULL)
4226 g_object_unref (message);
4230 decode_method_reply (GDBusMessage *reply,
4236 switch (g_dbus_message_get_message_type (reply))
4238 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
4239 result = g_dbus_message_get_body (reply);
4242 result = g_variant_new ("()");
4243 g_variant_ref_sink (result);
4247 g_variant_ref (result);
4251 case G_DBUS_MESSAGE_TYPE_ERROR:
4252 g_dbus_message_to_gerror (reply, error);
4256 g_assert_not_reached ();
4264 * g_dbus_connection_call_finish:
4265 * @connection: A #GDBusConnection.
4266 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
4267 * @error: Return location for error or %NULL.
4269 * Finishes an operation started with g_dbus_connection_call().
4271 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4272 * return values. Free with g_variant_unref().
4277 g_dbus_connection_call_finish (GDBusConnection *connection,
4281 GDBusMessage *reply;
4284 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4285 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
4286 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4290 reply = g_dbus_connection_send_message_with_reply_finish (connection, res, error);
4294 result = decode_method_reply (reply, error);
4296 g_object_unref (reply);
4302 /* ---------------------------------------------------------------------------------------------------- */
4305 * g_dbus_connection_call_sync:
4306 * @connection: A #GDBusConnection.
4307 * @bus_name: A unique or well-known bus name.
4308 * @object_path: Path of remote object.
4309 * @interface_name: D-Bus interface to invoke method on.
4310 * @method_name: The name of the method to invoke.
4311 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4312 * @flags: Flags from the #GDBusCallFlags enumeration.
4313 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4314 * @cancellable: A #GCancellable or %NULL.
4315 * @error: Return location for error or %NULL.
4317 * Synchronously invokes the @method_name method on the
4318 * @interface_name D-Bus interface on the remote object at
4319 * @object_path owned by @bus_name.
4321 * If @connection is closed then the operation will fail with
4322 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
4323 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
4324 * contains a value not compatible with the D-Bus protocol, the operation
4325 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
4327 * If the @parameters #GVariant is floating, it is consumed.
4328 * This allows convenient 'inline' use of g_variant_new(), e.g.:
4330 * g_dbus_connection_call_sync (connection,
4331 * "org.freedesktop.StringThings",
4332 * "/org/freedesktop/StringThings",
4333 * "org.freedesktop.StringThings",
4335 * g_variant_new ("(ss)",
4338 * G_DBUS_CALL_FLAGS_NONE,
4344 * The calling thread is blocked until a reply is received. See
4345 * g_dbus_connection_call() for the asynchronous version of
4348 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4349 * return values. Free with g_variant_unref().
4354 g_dbus_connection_call_sync (GDBusConnection *connection,
4355 const gchar *bus_name,
4356 const gchar *object_path,
4357 const gchar *interface_name,
4358 const gchar *method_name,
4359 GVariant *parameters,
4360 GDBusCallFlags flags,
4362 GCancellable *cancellable,
4365 GDBusMessage *message;
4366 GDBusMessage *reply;
4373 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4374 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
4375 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
4376 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
4377 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
4378 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
4379 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
4381 message = g_dbus_message_new_method_call (bus_name,
4385 add_call_flags (message, flags);
4386 if (parameters != NULL)
4387 g_dbus_message_set_body (message, parameters);
4389 reply = g_dbus_connection_send_message_with_reply_sync (connection,
4392 NULL, /* volatile guint32 *out_serial */
4399 result = decode_method_reply (reply, error);
4402 if (message != NULL)
4403 g_object_unref (message);
4405 g_object_unref (reply);
4410 /* ---------------------------------------------------------------------------------------------------- */
4412 struct ExportedSubtree
4416 GDBusConnection *connection;
4417 const GDBusSubtreeVTable *vtable;
4418 GDBusSubtreeFlags flags;
4420 GMainContext *context;
4422 GDestroyNotify user_data_free_func;
4426 exported_subtree_free (ExportedSubtree *es)
4428 if (es->user_data_free_func != NULL)
4429 /* TODO: push to thread-default mainloop */
4430 es->user_data_free_func (es->user_data);
4432 if (es->context != NULL)
4433 g_main_context_unref (es->context);
4435 g_free (es->object_path);
4439 /* called without lock held */
4441 handle_subtree_introspect (GDBusConnection *connection,
4442 ExportedSubtree *es,
4443 GDBusMessage *message)
4447 GDBusMessage *reply;
4450 const gchar *sender;
4451 const gchar *requested_object_path;
4452 const gchar *requested_node;
4453 GPtrArray *interfaces;
4455 gchar **subnode_paths;
4459 requested_object_path = g_dbus_message_get_path (message);
4460 sender = g_dbus_message_get_sender (message);
4461 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4463 s = g_string_new (NULL);
4464 introspect_append_header (s);
4466 /* Strictly we don't need the children in dynamic mode, but we avoid the
4467 * conditionals to preserve code clarity
4469 children = es->vtable->enumerate (es->connection,
4476 requested_node = strrchr (requested_object_path, '/') + 1;
4478 /* Assert existence of object if we are not dynamic */
4479 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4480 !_g_strv_has_string ((const gchar * const *) children, requested_node))
4485 requested_node = "/";
4488 interfaces = es->vtable->introspect (es->connection,
4493 if (interfaces != NULL)
4495 if (interfaces->len > 0)
4497 /* we're in business */
4498 introspect_append_standard_interfaces (s);
4500 for (n = 0; n < interfaces->len; n++)
4502 const GDBusInterfaceInfo *interface_info = interfaces->pdata[n];
4503 g_dbus_interface_info_generate_xml (interface_info, 2, s);
4506 g_ptr_array_unref (interfaces);
4509 /* then include <node> entries from the Subtree for the root */
4512 for (n = 0; children != NULL && children[n] != NULL; n++)
4513 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
4516 /* finally include nodes registered below us */
4517 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
4518 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
4519 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
4520 g_strfreev (subnode_paths);
4522 g_string_append (s, "</node>\n");
4524 reply = g_dbus_message_new_method_reply (message);
4525 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4526 g_dbus_connection_send_message (connection, reply, NULL, NULL);
4527 g_object_unref (reply);
4532 g_string_free (s, TRUE);
4533 g_strfreev (children);
4537 /* called without lock held */
4539 handle_subtree_method_invocation (GDBusConnection *connection,
4540 ExportedSubtree *es,
4541 GDBusMessage *message)
4544 const gchar *sender;
4545 const gchar *interface_name;
4546 const gchar *member;
4547 const gchar *signature;
4548 const gchar *requested_object_path;
4549 const gchar *requested_node;
4552 const GDBusInterfaceInfo *introspection_data;
4553 const GDBusInterfaceVTable *interface_vtable;
4554 gpointer interface_user_data;
4556 GPtrArray *interfaces;
4557 gboolean is_property_get;
4558 gboolean is_property_set;
4559 gboolean is_property_get_all;
4564 requested_object_path = g_dbus_message_get_path (message);
4565 sender = g_dbus_message_get_sender (message);
4566 interface_name = g_dbus_message_get_interface (message);
4567 member = g_dbus_message_get_member (message);
4568 signature = g_dbus_message_get_signature (message);
4569 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4571 is_property_get = FALSE;
4572 is_property_set = FALSE;
4573 is_property_get_all = FALSE;
4574 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
4576 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
4577 is_property_get = TRUE;
4578 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
4579 is_property_set = TRUE;
4580 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
4581 is_property_get_all = TRUE;
4584 children = es->vtable->enumerate (es->connection,
4591 requested_node = strrchr (requested_object_path, '/') + 1;
4593 /* If not dynamic, skip if requested node is not part of children */
4594 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4595 !_g_strv_has_string ((const gchar * const *) children, requested_node))
4600 requested_node = "/";
4603 /* get introspection data for the node */
4604 interfaces = es->vtable->introspect (es->connection,
4606 requested_object_path,
4609 g_assert (interfaces != NULL);
4610 introspection_data = NULL;
4611 for (n = 0; n < interfaces->len; n++)
4613 const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4614 if (g_strcmp0 (id_n->name, interface_name) == 0)
4615 introspection_data = id_n;
4618 /* dispatch the call if the user wants to handle it */
4619 if (introspection_data != NULL)
4621 /* figure out where to dispatch the method call */
4622 interface_user_data = NULL;
4623 interface_vtable = es->vtable->dispatch (es->connection,
4628 &interface_user_data,
4630 if (interface_vtable == NULL)
4633 CONNECTION_LOCK (connection);
4634 handled = validate_and_maybe_schedule_method_call (es->connection,
4639 interface_user_data);
4640 CONNECTION_UNLOCK (connection);
4642 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
4643 else if (is_property_get || is_property_set || is_property_get_all)
4645 if (is_property_get)
4646 g_variant_get (g_dbus_message_get_body (message), "(ss)", &interface_name, NULL);
4647 else if (is_property_set)
4648 g_variant_get (g_dbus_message_get_body (message), "(ssv)", &interface_name, NULL, NULL);
4649 else if (is_property_get_all)
4650 g_variant_get (g_dbus_message_get_body (message), "(s)", &interface_name, NULL, NULL);
4652 g_assert_not_reached ();
4654 /* see if the object supports this interface at all */
4655 for (n = 0; n < interfaces->len; n++)
4657 const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4658 if (g_strcmp0 (id_n->name, interface_name) == 0)
4659 introspection_data = id_n;
4662 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
4663 * claims it won't support the interface
4665 if (introspection_data == NULL)
4667 GDBusMessage *reply;
4668 reply = g_dbus_message_new_method_error (message,
4669 "org.freedesktop.DBus.Error.InvalidArgs",
4670 _("No such interface `%s'"),
4672 g_dbus_connection_send_message (es->connection, reply, NULL, NULL);
4673 g_object_unref (reply);
4678 /* figure out where to dispatch the property get/set/getall calls */
4679 interface_user_data = NULL;
4680 interface_vtable = es->vtable->dispatch (es->connection,
4685 &interface_user_data,
4687 if (interface_vtable == NULL)
4690 if (is_property_get || is_property_set)
4692 CONNECTION_LOCK (connection);
4693 handled = validate_and_maybe_schedule_property_getset (es->connection,
4699 interface_user_data);
4700 CONNECTION_UNLOCK (connection);
4702 else if (is_property_get_all)
4704 CONNECTION_LOCK (connection);
4705 handled = validate_and_maybe_schedule_property_get_all (es->connection,
4710 interface_user_data);
4711 CONNECTION_UNLOCK (connection);
4716 if (interfaces != NULL)
4717 g_ptr_array_unref (interfaces);
4718 g_strfreev (children);
4724 GDBusMessage *message;
4725 ExportedSubtree *es;
4726 } SubtreeDeferredData;
4729 subtree_deferred_data_free (SubtreeDeferredData *data)
4731 g_object_unref (data->message);
4735 /* called without lock held in the thread where the caller registered the subtree */
4737 process_subtree_vtable_message_in_idle_cb (gpointer _data)
4739 SubtreeDeferredData *data = _data;
4744 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
4745 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
4746 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
4747 handled = handle_subtree_introspect (data->es->connection,
4751 handled = handle_subtree_method_invocation (data->es->connection,
4757 CONNECTION_LOCK (data->es->connection);
4758 handled = handle_generic_unlocked (data->es->connection, data->message);
4759 CONNECTION_UNLOCK (data->es->connection);
4762 /* if we couldn't handle the request, just bail with the UnknownMethod error */
4765 GDBusMessage *reply;
4766 reply = g_dbus_message_new_method_error (data->message,
4767 "org.freedesktop.DBus.Error.UnknownMethod",
4768 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
4769 g_dbus_message_get_member (data->message),
4770 g_dbus_message_get_interface (data->message),
4771 g_dbus_message_get_signature (data->message));
4772 g_dbus_connection_send_message (data->es->connection, reply, NULL, NULL);
4773 g_object_unref (reply);
4779 /* called in message handler thread with lock held */
4781 subtree_message_func (GDBusConnection *connection,
4782 ExportedSubtree *es,
4783 GDBusMessage *message)
4785 GSource *idle_source;
4786 SubtreeDeferredData *data;
4788 data = g_new0 (SubtreeDeferredData, 1);
4789 data->message = g_object_ref (message);
4792 /* defer this call to an idle handler in the right thread */
4793 idle_source = g_idle_source_new ();
4794 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
4795 g_source_set_callback (idle_source,
4796 process_subtree_vtable_message_in_idle_cb,
4798 (GDestroyNotify) subtree_deferred_data_free);
4799 g_source_attach (idle_source, es->context);
4800 g_source_unref (idle_source);
4802 /* since we own the entire subtree, handlers for objects not in the subtree have been
4803 * tried already by libdbus-1 - so we just need to ensure that we're always going
4804 * to reply to the message
4810 * g_dbus_connection_register_subtree:
4811 * @connection: A #GDBusConnection.
4812 * @object_path: The object path to register the subtree at.
4813 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
4814 * @flags: Flags used to fine tune the behavior of the subtree.
4815 * @user_data: Data to pass to functions in @vtable.
4816 * @user_data_free_func: Function to call when the subtree is unregistered.
4817 * @error: Return location for error or %NULL.
4819 * Registers a whole subtree of <quote>dynamic</quote> objects.
4821 * The @enumerate and @introspection functions in @vtable are used to
4822 * convey, to remote callers, what nodes exist in the subtree rooted
4825 * When handling remote calls into any node in the subtree, first the
4826 * @enumerate function is used to check if the node exists. If the node exists
4827 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
4828 * the @introspection function is used to check if the node supports the
4829 * requested method. If so, the @dispatch function is used to determine
4830 * where to dispatch the call. The collected #GDBusInterfaceVTable and
4831 * #gpointer will be used to call into the interface vtable for processing
4834 * All calls into user-provided code will be invoked in the <link
4835 * linkend="g-main-context-push-thread-default">thread-default main
4836 * loop</link> of the thread you are calling this method from.
4838 * If an existing subtree is already registered at @object_path or
4839 * then @error is set to #G_IO_ERROR_EXISTS.
4841 * Note that it is valid to register regular objects (using
4842 * g_dbus_connection_register_object()) in a subtree registered with
4843 * g_dbus_connection_register_subtree() - if so, the subtree handler
4844 * is tried as the last resort. One way to think about a subtree
4845 * handler is to consider it a <quote>fallback handler</quote>
4846 * for object paths not registered via g_dbus_connection_register_object()
4847 * or other bindings.
4849 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
4851 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
4852 * that can be used with g_dbus_connection_unregister_subtree() .
4857 g_dbus_connection_register_subtree (GDBusConnection *connection,
4858 const gchar *object_path,
4859 const GDBusSubtreeVTable *vtable,
4860 GDBusSubtreeFlags flags,
4862 GDestroyNotify user_data_free_func,
4866 ExportedSubtree *es;
4868 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4869 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4870 g_return_val_if_fail (vtable != NULL, 0);
4871 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4875 CONNECTION_LOCK (connection);
4877 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
4883 _("A subtree is already exported for %s"),
4888 es = g_new0 (ExportedSubtree, 1);
4889 es->object_path = g_strdup (object_path);
4890 es->connection = connection;
4892 es->vtable = vtable;
4894 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
4895 es->user_data = user_data;
4896 es->user_data_free_func = user_data_free_func;
4897 es->context = g_main_context_get_thread_default ();
4898 if (es->context != NULL)
4899 g_main_context_ref (es->context);
4901 g_hash_table_insert (connection->priv->map_object_path_to_es, es->object_path, es);
4902 g_hash_table_insert (connection->priv->map_id_to_es,
4903 GUINT_TO_POINTER (es->id),
4909 CONNECTION_UNLOCK (connection);
4914 /* ---------------------------------------------------------------------------------------------------- */
4917 * g_dbus_connection_unregister_subtree:
4918 * @connection: A #GDBusConnection.
4919 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
4921 * Unregisters a subtree.
4923 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
4928 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
4929 guint registration_id)
4931 ExportedSubtree *es;
4934 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4938 CONNECTION_LOCK (connection);
4940 es = g_hash_table_lookup (connection->priv->map_id_to_es,
4941 GUINT_TO_POINTER (registration_id));
4945 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_es, GUINT_TO_POINTER (es->id)));
4946 g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_es, es->object_path));
4951 CONNECTION_UNLOCK (connection);
4956 /* ---------------------------------------------------------------------------------------------------- */
4958 /* must be called with lock held */
4960 handle_generic_ping_unlocked (GDBusConnection *connection,
4961 const gchar *object_path,
4962 GDBusMessage *message)
4964 GDBusMessage *reply;
4965 reply = g_dbus_message_new_method_reply (message);
4966 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4967 g_object_unref (reply);
4970 /* must be called with lock held */
4972 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
4973 const gchar *object_path,
4974 GDBusMessage *message)
4976 GDBusMessage *reply;
4979 if (connection->priv->machine_id == NULL)
4983 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
4984 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
4985 &connection->priv->machine_id,
4989 reply = g_dbus_message_new_method_error (message,
4990 "org.freedesktop.DBus.Error.Failed",
4991 _("Unable to load /var/lib/dbus/machine-id: %s"),
4993 g_error_free (error);
4997 g_strstrip (connection->priv->machine_id);
4998 /* TODO: validate value */
5004 reply = g_dbus_message_new_method_reply (message);
5005 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->priv->machine_id));
5007 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
5008 g_object_unref (reply);
5011 /* must be called with lock held */
5013 handle_generic_introspect_unlocked (GDBusConnection *connection,
5014 const gchar *object_path,
5015 GDBusMessage *message)
5020 GDBusMessage *reply;
5022 /* first the header */
5023 s = g_string_new (NULL);
5024 introspect_append_header (s);
5026 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
5027 for (n = 0; registered != NULL && registered[n] != NULL; n++)
5028 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
5029 g_strfreev (registered);
5030 g_string_append (s, "</node>\n");
5032 reply = g_dbus_message_new_method_reply (message);
5033 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5034 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
5035 g_object_unref (reply);
5036 g_string_free (s, TRUE);
5039 /* must be called with lock held */
5041 handle_generic_unlocked (GDBusConnection *connection,
5042 GDBusMessage *message)
5045 const gchar *interface_name;
5046 const gchar *member;
5047 const gchar *signature;
5050 CONNECTION_ENSURE_LOCK (connection);
5054 interface_name = g_dbus_message_get_interface (message);
5055 member = g_dbus_message_get_member (message);
5056 signature = g_dbus_message_get_signature (message);
5057 path = g_dbus_message_get_path (message);
5059 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5060 g_strcmp0 (member, "Introspect") == 0 &&
5061 g_strcmp0 (signature, "") == 0)
5063 handle_generic_introspect_unlocked (connection, path, message);
5066 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5067 g_strcmp0 (member, "Ping") == 0 &&
5068 g_strcmp0 (signature, "") == 0)
5070 handle_generic_ping_unlocked (connection, path, message);
5073 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5074 g_strcmp0 (member, "GetMachineId") == 0 &&
5075 g_strcmp0 (signature, "") == 0)
5077 handle_generic_get_machine_id_unlocked (connection, path, message);
5084 /* ---------------------------------------------------------------------------------------------------- */
5086 /* called in message handler thread with lock held */
5088 distribute_method_call (GDBusConnection *connection,
5089 GDBusMessage *message)
5092 ExportedSubtree *es;
5093 const gchar *object_path;
5094 const gchar *interface_name;
5095 const gchar *member;
5096 const gchar *signature;
5098 gchar *subtree_path;
5101 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
5103 interface_name = g_dbus_message_get_interface (message);
5104 member = g_dbus_message_get_member (message);
5105 signature = g_dbus_message_get_signature (message);
5106 path = g_dbus_message_get_path (message);
5107 subtree_path = g_strdup (path);
5108 needle = strrchr (subtree_path, '/');
5109 if (needle != NULL && needle != subtree_path)
5115 g_free (subtree_path);
5116 subtree_path = NULL;
5120 g_debug ("interface = `%s'", interface_name);
5121 g_debug ("member = `%s'", member);
5122 g_debug ("signature = `%s'", signature);
5123 g_debug ("path = `%s'", path);
5124 g_debug ("subtree_path = `%s'", subtree_path != NULL ? subtree_path : "N/A");
5127 object_path = g_dbus_message_get_path (message);
5128 g_assert (object_path != NULL);
5130 eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
5133 if (obj_message_func (connection, eo, message))
5137 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
5140 if (subtree_message_func (connection, es, message))
5144 if (subtree_path != NULL)
5146 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, subtree_path);
5149 if (subtree_message_func (connection, es, message))
5154 if (handle_generic_unlocked (connection, message))
5157 /* if we end up here, the message has not been not handled */
5160 g_free (subtree_path);
5163 /* ---------------------------------------------------------------------------------------------------- */
5165 static GDBusConnection **
5166 message_bus_get_singleton (GBusType bus_type,
5169 GDBusConnection **ret;
5170 const gchar *starter_bus;
5176 case G_BUS_TYPE_SESSION:
5177 ret = &the_session_bus;
5180 case G_BUS_TYPE_SYSTEM:
5181 ret = &the_system_bus;
5184 case G_BUS_TYPE_STARTER:
5185 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
5186 if (g_strcmp0 (starter_bus, "session") == 0)
5188 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
5191 else if (g_strcmp0 (starter_bus, "system") == 0)
5193 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
5198 if (starter_bus != NULL)
5202 G_IO_ERROR_INVALID_ARGUMENT,
5203 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
5204 " - unknown value `%s'"),
5209 g_set_error_literal (error,
5211 G_IO_ERROR_INVALID_ARGUMENT,
5212 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
5213 "variable is not set"));
5219 g_assert_not_reached ();
5227 static GDBusConnection *
5228 get_uninitialized_connection (GBusType bus_type,
5229 GCancellable *cancellable,
5232 GDBusConnection **singleton;
5233 GDBusConnection *ret;
5237 G_LOCK (message_bus_lock);
5238 singleton = message_bus_get_singleton (bus_type, error);
5239 if (singleton == NULL)
5242 if (*singleton == NULL)
5245 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
5246 if (address == NULL)
5248 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
5250 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
5251 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
5252 "exit-on-close", TRUE,
5257 ret = g_object_ref (*singleton);
5260 g_assert (ret != NULL);
5263 G_UNLOCK (message_bus_lock);
5269 * @bus_type: A #GBusType.
5270 * @cancellable: A #GCancellable or %NULL.
5271 * @error: Return location for error or %NULL.
5273 * Synchronously connects to the message bus specified by @bus_type.
5274 * Note that the returned object may shared with other callers,
5275 * e.g. if two separate parts of a process calls this function with
5276 * the same @bus_type, they will share the same object.
5278 * This is a synchronous failable function. See g_bus_get() and
5279 * g_bus_get_finish() for the asynchronous version.
5281 * The returned object is a singleton, that is, shared with other
5282 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5283 * event that you need a private message bus connection, use
5284 * g_dbus_address_get_for_bus_sync() and
5285 * g_dbus_connection_new_for_address().
5287 * Note that the returned #GDBusConnection object will (usually) have
5288 * the #GDBusConnection:exit-on-close property set to %TRUE.
5290 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5295 g_bus_get_sync (GBusType bus_type,
5296 GCancellable *cancellable,
5299 GDBusConnection *connection;
5301 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5303 connection = get_uninitialized_connection (bus_type, cancellable, error);
5304 if (connection == NULL)
5307 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
5309 g_object_unref (connection);
5318 bus_get_async_initable_cb (GObject *source_object,
5322 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
5326 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
5330 g_assert (error != NULL);
5331 g_simple_async_result_set_from_error (simple, error);
5332 g_error_free (error);
5333 g_object_unref (source_object);
5337 g_simple_async_result_set_op_res_gpointer (simple,
5341 g_simple_async_result_complete_in_idle (simple);
5342 g_object_unref (simple);
5347 * @bus_type: A #GBusType.
5348 * @cancellable: A #GCancellable or %NULL.
5349 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
5350 * @user_data: The data to pass to @callback.
5352 * Asynchronously connects to the message bus specified by @bus_type.
5354 * When the operation is finished, @callback will be invoked. You can
5355 * then call g_bus_get_finish() to get the result of the operation.
5357 * This is a asynchronous failable function. See g_bus_get_sync() for
5358 * the synchronous version.
5363 g_bus_get (GBusType bus_type,
5364 GCancellable *cancellable,
5365 GAsyncReadyCallback callback,
5368 GDBusConnection *connection;
5369 GSimpleAsyncResult *simple;
5372 simple = g_simple_async_result_new (NULL,
5378 connection = get_uninitialized_connection (bus_type, cancellable, &error);
5379 if (connection == NULL)
5381 g_assert (error != NULL);
5382 g_simple_async_result_set_from_error (simple, error);
5383 g_error_free (error);
5384 g_simple_async_result_complete_in_idle (simple);
5385 g_object_unref (simple);
5389 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
5392 bus_get_async_initable_cb,
5399 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
5400 * @error: Return location for error or %NULL.
5402 * Finishes an operation started with g_bus_get().
5404 * The returned object is a singleton, that is, shared with other
5405 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5406 * event that you need a private message bus connection, use
5407 * g_dbus_address_get_for_bus() and
5408 * g_dbus_connection_new_for_address().
5410 * Note that the returned #GDBusConnection object will (usually) have
5411 * the #GDBusConnection:exit-on-close property set to %TRUE.
5413 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5418 g_bus_get_finish (GAsyncResult *res,
5421 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
5423 GDBusConnection *ret;
5425 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5427 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
5431 if (g_simple_async_result_propagate_error (simple, error))
5434 object = g_simple_async_result_get_op_res_gpointer (simple);
5435 g_assert (object != NULL);
5436 ret = g_object_ref (G_DBUS_CONNECTION (object));
5442 /* ---------------------------------------------------------------------------------------------------- */
5444 #define __G_DBUS_CONNECTION_C__
5445 #include "gioaliasdef.c"