1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2009 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, write to the
17 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18 * Boston, MA 02111-1307, USA.
20 * Author: David Zeuthen <davidz@redhat.com>
26 * - would be nice to expose GDBusAuthMechanism and an extension point
28 * - need to expose an extension point for resolving D-Bus address and
29 * turning them into GIOStream objects. This will allow us to implement
30 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
32 * - see g_dbus_address_connect() in gdbusaddress.c
34 * - would be cute to use kernel-specific APIs to resolve fds for
35 * debug output when using G_DBUS_DEBUG=messages, e.g. in addition to
37 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
39 * maybe we can show more information about what fd 21 really is.
40 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
41 * Initial experiments on Linux 2.6 suggests that the symlink looks
46 * e.g. not of much use.
53 #include <glib/gi18n.h>
56 #include <gio/gunixconnection.h>
57 #include <gio/gunixfdmessage.h>
61 #include <sys/types.h>
64 #include "gdbusauth.h"
66 #include "gdbusutils.h"
67 #include "gdbusaddress.h"
68 #include "gdbusmessage.h"
69 #include "gdbusconnection.h"
70 #include "gdbuserror.h"
71 #include "gioenumtypes.h"
72 #include "gdbusintrospection.h"
73 #include "gdbusmethodinvocation.h"
74 #include "gdbusprivate.h"
75 #include "gdbusauthobserver.h"
76 #include "gio-marshal.h"
79 * SECTION:gdbusconnection
80 * @short_description: D-Bus Connections
81 * @include: gdbus/gdbus.h
84 * This class is rarely used directly in D-Bus clients. If you are
85 * writing an D-Bus client, it is often easier to use the
86 * g_bus_own_name(), g_bus_watch_name() or g_bus_watch_proxy() APIs.
89 * The #GDBusConnection type is used for D-Bus connections to remote
90 * peers such as a message buses.
92 * <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>
94 * <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>
96 * <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>
99 /* ---------------------------------------------------------------------------------------------------- */
101 G_LOCK_DEFINE_STATIC (message_bus_lock);
103 static GDBusConnection *the_session_bus = NULL;
104 static GDBusConnection *the_system_bus = NULL;
106 /* ---------------------------------------------------------------------------------------------------- */
109 _g_strv_has_string (const gchar* const * haystack,
114 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
116 if (g_strcmp0 (haystack[n], needle) == 0)
122 /* ---------------------------------------------------------------------------------------------------- */
125 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
127 // TODO: for some reason this doesn't work on Windows
128 #define CONNECTION_ENSURE_LOCK(obj) do { \
129 if (G_UNLIKELY (g_mutex_trylock((obj)->priv->lock))) \
131 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
132 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
137 #define CONNECTION_LOCK(obj) do { \
138 g_mutex_lock ((obj)->priv->lock); \
141 #define CONNECTION_UNLOCK(obj) do { \
142 g_mutex_unlock ((obj)->priv->lock); \
145 struct _GDBusConnectionPrivate
147 /* ------------------------------------------------------------------------ */
148 /* -- General object state ------------------------------------------------ */
149 /* ------------------------------------------------------------------------ */
151 /* object-wide lock */
154 /* A lock used in the init() method of the GInitable interface - see comments
155 * in initable_init() for why a separate lock is needed
159 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
160 * someone calls org.freedesktop.DBus.GetMachineId()
164 /* The underlying stream used for communication */
167 /* The object used for authentication (if any) */
170 /* Set to TRUE if the connection has been closed */
173 /* Last serial used */
176 /* The object used to send/receive message */
179 /* If connected to a message bus, this contains the unique name assigned to
180 * us by the bus (e.g. ":1.42")
182 gchar *bus_unique_name;
184 /* The GUID returned by the other side if we authenticed as a client or
185 * the GUID to use if authenticating as a server
189 /* set to TRUE exactly when initable_init() has finished running */
190 gboolean is_initialized;
192 /* If the connection could not be established during initable_init(), this GError will set */
193 GError *initialization_error;
195 /* The result of g_main_context_get_thread_default() when the object
196 * was created (the GObject _init() function) - this is used for delivery
197 * of the :closed GObject signal.
199 GMainContext *main_context_at_construction;
201 /* construct properties */
203 GDBusConnectionFlags flags;
205 /* Map used for managing method replies */
206 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
208 /* Maps used for managing signal subscription */
209 GHashTable *map_rule_to_signal_data; /* gchar* -> SignalData */
210 GHashTable *map_id_to_signal_data; /* guint -> SignalData */
211 GHashTable *map_sender_to_signal_data_array; /* gchar* -> GPtrArray* of SignalData */
213 /* Maps used for managing exported objects and subtrees */
214 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
215 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
216 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
217 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
219 /* Structure used for message filters */
222 /* Whether to exit on close */
223 gboolean exit_on_close;
225 /* Capabilities negotiated during authentication */
226 GDBusCapabilityFlags capabilities;
228 GDBusAuthObserver *authentication_observer;
229 GCredentials *crendentials;
232 typedef struct ExportedObject ExportedObject;
233 static void exported_object_free (ExportedObject *eo);
235 typedef struct ExportedSubtree ExportedSubtree;
236 static void exported_subtree_free (ExportedSubtree *es);
254 PROP_CAPABILITY_FLAGS,
255 PROP_AUTHENTICATION_OBSERVER,
258 static void distribute_signals (GDBusConnection *connection,
259 GDBusMessage *message);
261 static void distribute_method_call (GDBusConnection *connection,
262 GDBusMessage *message);
264 static gboolean handle_generic_unlocked (GDBusConnection *connection,
265 GDBusMessage *message);
268 static void purge_all_signal_subscriptions (GDBusConnection *connection);
269 static void purge_all_filters (GDBusConnection *connection);
271 #define _G_ENSURE_LOCK(name) do { \
272 if (G_UNLIKELY (G_TRYLOCK(name))) \
274 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
275 "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
279 static guint signals[LAST_SIGNAL] = { 0 };
281 static void initable_iface_init (GInitableIface *initable_iface);
282 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
284 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
285 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
286 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
290 g_dbus_connection_dispose (GObject *object)
292 GDBusConnection *connection = G_DBUS_CONNECTION (object);
294 G_LOCK (message_bus_lock);
295 //g_debug ("disposing %p", connection);
296 if (connection == the_session_bus)
298 the_session_bus = NULL;
300 else if (connection == the_system_bus)
302 the_system_bus = NULL;
304 if (connection->priv->worker != NULL)
306 _g_dbus_worker_stop (connection->priv->worker);
307 connection->priv->worker = NULL;
309 G_UNLOCK (message_bus_lock);
311 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
312 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
316 g_dbus_connection_finalize (GObject *object)
318 GDBusConnection *connection = G_DBUS_CONNECTION (object);
320 if (connection->priv->authentication_observer != NULL)
321 g_object_unref (connection->priv->authentication_observer);
323 if (connection->priv->auth != NULL)
324 g_object_unref (connection->priv->auth);
326 //g_debug ("finalizing %p", connection);
327 if (connection->priv->stream != NULL)
329 /* We don't really care if closing the stream succeeds or not */
330 g_io_stream_close_async (connection->priv->stream,
332 NULL, /* GCancellable */
333 NULL, /* GAsyncReadyCallback */
334 NULL); /* userdata */
335 g_object_unref (connection->priv->stream);
336 connection->priv->stream = NULL;
339 g_free (connection->priv->address);
341 g_free (connection->priv->guid);
342 g_free (connection->priv->bus_unique_name);
344 if (connection->priv->initialization_error != NULL)
345 g_error_free (connection->priv->initialization_error);
347 g_hash_table_unref (connection->priv->map_method_serial_to_send_message_data);
349 purge_all_signal_subscriptions (connection);
350 g_hash_table_unref (connection->priv->map_rule_to_signal_data);
351 g_hash_table_unref (connection->priv->map_id_to_signal_data);
352 g_hash_table_unref (connection->priv->map_sender_to_signal_data_array);
354 g_hash_table_unref (connection->priv->map_id_to_ei);
355 g_hash_table_unref (connection->priv->map_object_path_to_eo);
356 g_hash_table_unref (connection->priv->map_id_to_es);
357 g_hash_table_unref (connection->priv->map_object_path_to_es);
359 purge_all_filters (connection);
360 g_ptr_array_unref (connection->priv->filters);
362 if (connection->priv->main_context_at_construction != NULL)
363 g_main_context_unref (connection->priv->main_context_at_construction);
365 g_free (connection->priv->machine_id);
367 g_mutex_free (connection->priv->init_lock);
368 g_mutex_free (connection->priv->lock);
370 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize != NULL)
371 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
375 g_dbus_connection_get_property (GObject *object,
380 GDBusConnection *connection = G_DBUS_CONNECTION (object);
385 g_value_set_object (value, g_dbus_connection_get_stream (connection));
389 g_value_set_string (value, g_dbus_connection_get_guid (connection));
392 case PROP_UNIQUE_NAME:
393 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
397 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
400 case PROP_EXIT_ON_CLOSE:
401 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
404 case PROP_CAPABILITY_FLAGS:
405 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
409 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
415 g_dbus_connection_set_property (GObject *object,
420 GDBusConnection *connection = G_DBUS_CONNECTION (object);
425 connection->priv->stream = g_value_dup_object (value);
429 connection->priv->guid = g_value_dup_string (value);
433 connection->priv->address = g_value_dup_string (value);
437 connection->priv->flags = g_value_get_flags (value);
440 case PROP_EXIT_ON_CLOSE:
441 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
444 case PROP_AUTHENTICATION_OBSERVER:
445 connection->priv->authentication_observer = g_value_dup_object (value);
449 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
455 g_dbus_connection_real_closed (GDBusConnection *connection,
456 gboolean remote_peer_vanished,
459 if (remote_peer_vanished && connection->priv->exit_on_close)
461 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
467 g_dbus_connection_class_init (GDBusConnectionClass *klass)
469 GObjectClass *gobject_class;
471 g_type_class_add_private (klass, sizeof (GDBusConnectionPrivate));
473 gobject_class = G_OBJECT_CLASS (klass);
475 gobject_class->finalize = g_dbus_connection_finalize;
476 gobject_class->dispose = g_dbus_connection_dispose;
477 gobject_class->set_property = g_dbus_connection_set_property;
478 gobject_class->get_property = g_dbus_connection_get_property;
480 klass->closed = g_dbus_connection_real_closed;
483 * GDBusConnection:stream:
485 * The underlying #GIOStream used for I/O.
487 g_object_class_install_property (gobject_class,
489 g_param_spec_object ("stream",
491 _("The underlying streams used for I/O"),
495 G_PARAM_CONSTRUCT_ONLY |
496 G_PARAM_STATIC_NAME |
497 G_PARAM_STATIC_BLURB |
498 G_PARAM_STATIC_NICK));
501 * GDBusConnection:address:
503 * A D-Bus address specifying potential endpoints that can be used
504 * when establishing the connection.
506 g_object_class_install_property (gobject_class,
508 g_param_spec_string ("address",
510 _("D-Bus address specifying potential socket endpoints"),
513 G_PARAM_CONSTRUCT_ONLY |
514 G_PARAM_STATIC_NAME |
515 G_PARAM_STATIC_BLURB |
516 G_PARAM_STATIC_NICK));
519 * GDBusConnection:flags:
521 * Flags from the #GDBusConnectionFlags enumeration.
523 g_object_class_install_property (gobject_class,
525 g_param_spec_flags ("flags",
528 G_TYPE_DBUS_CONNECTION_FLAGS,
529 G_DBUS_CONNECTION_FLAGS_NONE,
531 G_PARAM_CONSTRUCT_ONLY |
532 G_PARAM_STATIC_NAME |
533 G_PARAM_STATIC_BLURB |
534 G_PARAM_STATIC_NICK));
537 * GDBusConnection:guid:
539 * The GUID of the peer performing the role of server when
542 * If you are constructing a #GDBusConnection and pass
543 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
544 * #GDBusConnection:flags property then you MUST also set this
545 * property to a valid guid.
547 * If you are constructing a #GDBusConnection and pass
548 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
549 * #GDBusConnection:flags property you will be able to read the GUID
550 * of the other peer here after the connection has been succesfully
553 g_object_class_install_property (gobject_class,
555 g_param_spec_string ("guid",
557 _("GUID of the server peer"),
561 G_PARAM_CONSTRUCT_ONLY |
562 G_PARAM_STATIC_NAME |
563 G_PARAM_STATIC_BLURB |
564 G_PARAM_STATIC_NICK));
567 * GDBusConnection:unique-name:
569 * The unique name as assigned by the message bus or %NULL if the
570 * connection is not open or not a message bus connection.
572 g_object_class_install_property (gobject_class,
574 g_param_spec_string ("unique-name",
576 _("Unique name of bus connection"),
579 G_PARAM_STATIC_NAME |
580 G_PARAM_STATIC_BLURB |
581 G_PARAM_STATIC_NICK));
584 * GDBusConnection:closed:
586 * A boolean specifying whether the connection has been closed.
588 g_object_class_install_property (gobject_class,
590 g_param_spec_boolean ("closed",
592 _("Whether the connection is closed"),
595 G_PARAM_STATIC_NAME |
596 G_PARAM_STATIC_BLURB |
597 G_PARAM_STATIC_NICK));
600 * GDBusConnection:exit-on-close:
602 * A boolean specifying whether the process will be terminated (by
603 * calling <literal>raise(SIGTERM)</literal>) if the connection
604 * is closed by the remote peer.
606 g_object_class_install_property (gobject_class,
608 g_param_spec_boolean ("exit-on-close",
610 _("Whether the process is terminated when the connection is closed"),
614 G_PARAM_STATIC_NAME |
615 G_PARAM_STATIC_BLURB |
616 G_PARAM_STATIC_NICK));
619 * GDBusConnection:capabilities:
621 * Flags from the #GDBusCapabilityFlags enumeration
622 * representing connection features negotiated with the other peer.
624 g_object_class_install_property (gobject_class,
625 PROP_CAPABILITY_FLAGS,
626 g_param_spec_flags ("capabilities",
629 G_TYPE_DBUS_CAPABILITY_FLAGS,
630 G_DBUS_CAPABILITY_FLAGS_NONE,
632 G_PARAM_STATIC_NAME |
633 G_PARAM_STATIC_BLURB |
634 G_PARAM_STATIC_NICK));
637 * GDBusConnection:authentication-observer:
639 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
641 g_object_class_install_property (gobject_class,
642 PROP_AUTHENTICATION_OBSERVER,
643 g_param_spec_object ("authentication-observer",
644 _("Authentication Observer"),
645 _("Object used to assist in the authentication process"),
646 G_TYPE_DBUS_AUTH_OBSERVER,
648 G_PARAM_CONSTRUCT_ONLY |
649 G_PARAM_STATIC_NAME |
650 G_PARAM_STATIC_BLURB |
651 G_PARAM_STATIC_NICK));
654 * GDBusConnection::closed:
655 * @connection: The #GDBusConnection emitting the signal.
656 * @remote_peer_vanished: %TRUE if @connection is closed because the
657 * remote peer closed its end of the connection.
658 * @error: A #GError with more details about the event or %NULL.
660 * Emitted when the connection is closed.
662 * The cause of this event can be
665 * If g_dbus_connection_close() is called. In this case
666 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
669 * If the remote peer closes the connection. In this case
670 * @remote_peer_vanished is set to %TRUE and @error is set.
673 * If the remote peer sends invalid or malformed data. In this
674 * case @remote_peer_vanished is set to %FALSE and @error
679 * Upon receiving this signal, you should give up your reference to
680 * @connection. You are guaranteed that this signal is emitted only
683 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
684 G_TYPE_DBUS_CONNECTION,
686 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
689 _gio_marshal_VOID__BOOLEAN_BOXED,
697 g_dbus_connection_init (GDBusConnection *connection)
699 connection->priv = G_TYPE_INSTANCE_GET_PRIVATE (connection, G_TYPE_DBUS_CONNECTION, GDBusConnectionPrivate);
701 connection->priv->lock = g_mutex_new ();
702 connection->priv->init_lock = g_mutex_new ();
704 connection->priv->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
706 connection->priv->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
708 connection->priv->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
710 connection->priv->map_sender_to_signal_data_array = g_hash_table_new_full (g_str_hash,
715 connection->priv->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
718 (GDestroyNotify) exported_object_free);
720 connection->priv->map_id_to_ei = g_hash_table_new (g_direct_hash,
723 connection->priv->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
726 (GDestroyNotify) exported_subtree_free);
728 connection->priv->map_id_to_es = g_hash_table_new (g_direct_hash,
731 connection->priv->main_context_at_construction = g_main_context_get_thread_default ();
732 if (connection->priv->main_context_at_construction != NULL)
733 g_main_context_ref (connection->priv->main_context_at_construction);
735 connection->priv->filters = g_ptr_array_new ();
739 g_dbus_connection_get_stream (GDBusConnection *connection)
741 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
742 return connection->priv->stream;
747 * g_dbus_connection_is_closed:
748 * @connection: A #GDBusConnection.
750 * Gets whether @connection is closed.
752 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
755 g_dbus_connection_is_closed (GDBusConnection *connection)
757 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
758 return connection->priv->closed;
762 * g_dbus_connection_get_capabilities:
763 * @connection: A #GDBusConnection.
765 * Gets the capabilities negotiated with the remote peer
767 * Returns: One or more flags from the #GDBusCapabilityFlags enumeration.
770 g_dbus_connection_get_capabilities (GDBusConnection *connection)
772 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
773 return connection->priv->capabilities;
777 /* ---------------------------------------------------------------------------------------------------- */
781 GDBusConnection *connection;
783 gboolean remote_peer_vanished;
787 emit_closed_data_free (EmitClosedData *data)
789 g_object_unref (data->connection);
790 if (data->error != NULL)
791 g_error_free (data->error);
796 emit_closed_in_idle (gpointer user_data)
798 EmitClosedData *data = user_data;
801 g_object_notify (G_OBJECT (data->connection), "closed");
802 g_signal_emit (data->connection,
803 signals[CLOSED_SIGNAL],
805 data->remote_peer_vanished,
811 /* Can be called from any thread, must hold lock */
813 set_closed_unlocked (GDBusConnection *connection,
814 gboolean remote_peer_vanished,
817 GSource *idle_source;
818 EmitClosedData *data;
820 CONNECTION_ENSURE_LOCK (connection);
822 g_assert (!connection->priv->closed);
824 connection->priv->closed = TRUE;
826 data = g_new0 (EmitClosedData, 1);
827 data->connection = g_object_ref (connection);
828 data->remote_peer_vanished = remote_peer_vanished;
829 data->error = error != NULL ? g_error_copy (error) : NULL;
831 idle_source = g_idle_source_new ();
832 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
833 g_source_set_callback (idle_source,
836 (GDestroyNotify) emit_closed_data_free);
837 g_source_attach (idle_source, connection->priv->main_context_at_construction);
838 g_source_unref (idle_source);
841 /* ---------------------------------------------------------------------------------------------------- */
844 * g_dbus_connection_close:
845 * @connection: A #GDBusConnection.
847 * Closes @connection. Note that this never causes the process to
848 * exit (this might only happen if the other end of a shared message
849 * bus connection disconnects).
851 * If @connection is already closed, this method does nothing.
854 g_dbus_connection_close (GDBusConnection *connection)
856 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
858 CONNECTION_LOCK (connection);
859 if (!connection->priv->closed)
861 GError *error = NULL;
863 /* TODO: do this async */
864 //g_debug ("closing connection %p's stream %p", connection, connection->priv->stream);
865 if (!g_io_stream_close (connection->priv->stream, NULL, &error))
867 g_warning ("Error closing stream: %s", error->message);
868 g_error_free (error);
871 set_closed_unlocked (connection, FALSE, NULL);
873 CONNECTION_UNLOCK (connection);
876 /* ---------------------------------------------------------------------------------------------------- */
879 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
880 GDBusMessage *message,
881 volatile guint32 *out_serial,
886 guint32 serial_to_use;
889 CONNECTION_ENSURE_LOCK (connection);
891 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
892 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
894 /* TODO: check all necessary headers are present */
899 if (out_serial != NULL)
902 if (connection->priv->closed)
904 g_set_error_literal (error,
907 _("The connection is closed"));
911 blob = g_dbus_message_to_blob (message,
917 serial_to_use = ++connection->priv->last_serial; /* TODO: handle overflow */
922 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
925 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
928 g_assert_not_reached ();
933 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
934 blob_size, serial_to_use, connection);
935 g_printerr ("----\n");
936 hexdump (blob, blob_size);
937 g_printerr ("----\n");
940 /* TODO: use connection->priv->auth to encode the blob */
942 if (out_serial != NULL)
944 *out_serial = serial_to_use;
946 g_dbus_message_set_serial (message, serial_to_use);
948 _g_dbus_worker_send_message (connection->priv->worker,
952 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
963 * g_dbus_connection_send_message:
964 * @connection: A #GDBusConnection.
965 * @message: A #GDBusMessage
966 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
967 * @error: Return location for error or %NULL.
969 * Asynchronously sends @message to the peer represented by @connection.
971 * If @out_serial is not %NULL, then the serial number assigned to
972 * @message by @connection will be written to this location prior to
973 * submitting the message to the underlying transport.
975 * If @connection is closed then the operation will fail with
976 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
977 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
978 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
980 * See <xref linkend="gdbus-server"/> and <xref
981 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
982 * low-level API to send and receive UNIX file descriptors.
984 * Returns: %TRUE if the message was well-formed and queued for
985 * transmission, %FALSE if @error is set.
988 g_dbus_connection_send_message (GDBusConnection *connection,
989 GDBusMessage *message,
990 volatile guint32 *out_serial,
995 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
996 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
997 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
999 CONNECTION_LOCK (connection);
1000 ret = g_dbus_connection_send_message_unlocked (connection, message, out_serial, error);
1001 CONNECTION_UNLOCK (connection);
1005 /* ---------------------------------------------------------------------------------------------------- */
1009 volatile gint ref_count;
1010 GDBusConnection *connection;
1012 GSimpleAsyncResult *simple;
1014 GMainContext *main_context;
1016 GCancellable *cancellable;
1018 gulong cancellable_handler_id;
1020 GSource *timeout_source;
1025 static SendMessageData *
1026 send_message_data_ref (SendMessageData *data)
1028 g_atomic_int_inc (&data->ref_count);
1033 send_message_data_unref (SendMessageData *data)
1035 if (g_atomic_int_dec_and_test (&data->ref_count))
1037 g_assert (data->timeout_source == NULL);
1038 g_assert (data->simple == NULL);
1039 g_assert (data->cancellable_handler_id == 0);
1040 g_object_unref (data->connection);
1041 if (data->cancellable != NULL)
1042 g_object_unref (data->cancellable);
1043 if (data->main_context != NULL)
1044 g_main_context_unref (data->main_context);
1049 /* ---------------------------------------------------------------------------------------------------- */
1051 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1053 send_message_with_reply_deliver (SendMessageData *data)
1055 CONNECTION_ENSURE_LOCK (data->connection);
1057 g_assert (!data->delivered);
1059 data->delivered = TRUE;
1061 g_simple_async_result_complete_in_idle (data->simple);
1062 g_object_unref (data->simple);
1063 data->simple = NULL;
1065 if (data->timeout_source != NULL)
1067 g_source_destroy (data->timeout_source);
1068 data->timeout_source = NULL;
1070 if (data->cancellable_handler_id > 0)
1072 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1073 data->cancellable_handler_id = 0;
1076 g_warn_if_fail (g_hash_table_remove (data->connection->priv->map_method_serial_to_send_message_data,
1077 GUINT_TO_POINTER (data->serial)));
1079 send_message_data_unref (data);
1082 /* ---------------------------------------------------------------------------------------------------- */
1084 /* must hold lock */
1086 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1087 GDBusMessage *reply)
1089 if (data->delivered)
1092 g_simple_async_result_set_op_res_gpointer (data->simple,
1093 g_object_ref (reply),
1096 send_message_with_reply_deliver (data);
1102 /* ---------------------------------------------------------------------------------------------------- */
1105 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1107 SendMessageData *data = user_data;
1109 CONNECTION_LOCK (data->connection);
1110 if (data->delivered)
1113 g_simple_async_result_set_error (data->simple,
1115 G_IO_ERROR_CANCELLED,
1116 _("Operation was cancelled"));
1118 send_message_with_reply_deliver (data);
1121 CONNECTION_UNLOCK (data->connection);
1125 /* Can be called from any thread with or without lock held */
1127 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1130 SendMessageData *data = user_data;
1131 GSource *idle_source;
1133 /* postpone cancellation to idle handler since we may be called directly
1134 * via g_cancellable_connect() (e.g. holding lock)
1136 idle_source = g_idle_source_new ();
1137 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1138 g_source_set_callback (idle_source,
1139 send_message_with_reply_cancelled_idle_cb,
1140 send_message_data_ref (data),
1141 (GDestroyNotify) send_message_data_unref);
1142 g_source_attach (idle_source, data->main_context);
1143 g_source_unref (idle_source);
1146 /* ---------------------------------------------------------------------------------------------------- */
1149 send_message_with_reply_timeout_cb (gpointer user_data)
1151 SendMessageData *data = user_data;
1153 CONNECTION_LOCK (data->connection);
1154 if (data->delivered)
1157 g_simple_async_result_set_error (data->simple,
1159 G_IO_ERROR_TIMED_OUT,
1160 _("Timeout was reached"));
1162 send_message_with_reply_deliver (data);
1165 CONNECTION_UNLOCK (data->connection);
1170 /* ---------------------------------------------------------------------------------------------------- */
1173 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1174 GDBusMessage *message,
1176 volatile guint32 *out_serial,
1177 GCancellable *cancellable,
1178 GAsyncReadyCallback callback,
1181 GSimpleAsyncResult *simple;
1182 SendMessageData *data;
1184 volatile guint32 serial;
1188 if (out_serial == NULL)
1189 out_serial = &serial;
1191 if (timeout_msec == -1)
1192 timeout_msec = 30 * 1000; /* TODO: check 30 secs is the default timeout */
1194 simple = g_simple_async_result_new (G_OBJECT (connection),
1197 g_dbus_connection_send_message_with_reply);
1199 if (g_cancellable_is_cancelled (cancellable))
1201 g_simple_async_result_set_error (simple,
1203 G_IO_ERROR_CANCELLED,
1204 _("Operation was cancelled"));
1205 g_simple_async_result_complete_in_idle (simple);
1206 g_object_unref (simple);
1210 if (connection->priv->closed)
1212 g_simple_async_result_set_error (simple,
1215 _("The connection is closed"));
1216 g_simple_async_result_complete_in_idle (simple);
1217 g_object_unref (simple);
1222 if (!g_dbus_connection_send_message_unlocked (connection, message, out_serial, &error))
1224 g_simple_async_result_set_from_error (simple, error);
1225 g_simple_async_result_complete_in_idle (simple);
1226 g_object_unref (simple);
1230 data = g_new0 (SendMessageData, 1);
1231 data->ref_count = 1;
1232 data->connection = g_object_ref (connection);
1233 data->simple = simple;
1234 data->serial = *out_serial;
1235 data->main_context = g_main_context_get_thread_default ();
1236 if (data->main_context != NULL)
1237 g_main_context_ref (data->main_context);
1239 if (cancellable != NULL)
1241 data->cancellable = g_object_ref (cancellable);
1242 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1243 G_CALLBACK (send_message_with_reply_cancelled_cb),
1244 send_message_data_ref (data),
1245 (GDestroyNotify) send_message_data_unref);
1246 g_object_set_data_full (G_OBJECT (simple),
1248 g_object_ref (cancellable),
1249 (GDestroyNotify) g_object_unref);
1252 data->timeout_source = g_timeout_source_new (timeout_msec);
1253 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1254 g_source_set_callback (data->timeout_source,
1255 send_message_with_reply_timeout_cb,
1256 send_message_data_ref (data),
1257 (GDestroyNotify) send_message_data_unref);
1258 g_source_attach (data->timeout_source, data->main_context);
1259 g_source_unref (data->timeout_source);
1261 g_hash_table_insert (connection->priv->map_method_serial_to_send_message_data,
1262 GUINT_TO_POINTER (*out_serial),
1270 * g_dbus_connection_send_message_with_reply:
1271 * @connection: A #GDBusConnection.
1272 * @message: A #GDBusMessage.
1273 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1274 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1275 * @cancellable: A #GCancellable or %NULL.
1276 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1277 * care about the result.
1278 * @user_data: The data to pass to @callback.
1280 * Asynchronously sends @message to the peer represented by @connection.
1282 * If @out_serial is not %NULL, then the serial number assigned to
1283 * @message by @connection will be written to this location prior to
1284 * submitting the message to the underlying transport.
1286 * If @connection is closed then the operation will fail with
1287 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1288 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1289 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1291 * This is an asynchronous method. When the operation is finished, @callback will be invoked
1292 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
1293 * of the thread you are calling this method from. You can then call
1294 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1295 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
1297 * See <xref linkend="gdbus-server"/> and <xref
1298 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1299 * low-level API to send and receive UNIX file descriptors.
1302 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
1303 GDBusMessage *message,
1305 volatile guint32 *out_serial,
1306 GCancellable *cancellable,
1307 GAsyncReadyCallback callback,
1310 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1311 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1312 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
1314 CONNECTION_LOCK (connection);
1315 g_dbus_connection_send_message_with_reply_unlocked (connection,
1322 CONNECTION_UNLOCK (connection);
1326 * g_dbus_connection_send_message_with_reply_finish:
1327 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
1328 * @error: Return location for error or %NULL.
1330 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
1332 * Note that @error is only set if a local in-process error
1333 * occured. That is to say that the returned #GDBusMessage object may
1334 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1335 * g_dbus_message_to_gerror() to transcode this to a #GError.
1337 * See <xref linkend="gdbus-server"/> and <xref
1338 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1339 * low-level API to send and receive UNIX file descriptors.
1341 * Returns: A #GDBusMessage or %NULL if @error is set.
1344 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
1348 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1349 GDBusMessage *reply;
1350 GCancellable *cancellable;
1352 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1353 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1357 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
1359 if (g_simple_async_result_propagate_error (simple, error))
1362 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
1363 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
1364 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
1366 g_object_unref (reply);
1368 g_set_error_literal (error,
1370 G_IO_ERROR_CANCELLED,
1371 _("Operation was cancelled"));
1377 /* ---------------------------------------------------------------------------------------------------- */
1382 GMainContext *context;
1384 } SendMessageSyncData;
1387 send_message_with_reply_sync_cb (GDBusConnection *connection,
1391 SendMessageSyncData *data = user_data;
1392 data->res = g_object_ref (res);
1393 g_main_loop_quit (data->loop);
1397 * g_dbus_connection_send_message_with_reply_sync:
1398 * @connection: A #GDBusConnection.
1399 * @message: A #GDBusMessage.
1400 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1401 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1402 * @cancellable: A #GCancellable or %NULL.
1403 * @error: Return location for error or %NULL.
1405 * Synchronously sends @message to the peer represented by @connection
1406 * and blocks the calling thread until a reply is received or the
1407 * timeout is reached. See g_dbus_connection_send_message_with_reply()
1408 * for the asynchronous version of this method.
1410 * If @out_serial is not %NULL, then the serial number assigned to
1411 * @message by @connection will be written to this location prior to
1412 * submitting the message to the underlying transport.
1414 * If @connection is closed then the operation will fail with
1415 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1416 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1417 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1419 * Note that @error is only set if a local in-process error
1420 * occured. That is to say that the returned #GDBusMessage object may
1421 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1422 * g_dbus_message_to_gerror() to transcode this to a #GError.
1424 * See <xref linkend="gdbus-server"/> and <xref
1425 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1426 * low-level API to send and receive UNIX file descriptors.
1428 * Returns: A #GDBusMessage that is the reply to @message or %NULL if @error is set.
1431 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
1432 GDBusMessage *message,
1434 volatile guint32 *out_serial,
1435 GCancellable *cancellable,
1438 SendMessageSyncData *data;
1439 GDBusMessage *reply;
1441 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1442 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
1443 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1444 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1446 data = g_new0 (SendMessageSyncData, 1);
1447 data->context = g_main_context_new ();
1448 data->loop = g_main_loop_new (data->context, FALSE);
1450 g_main_context_push_thread_default (data->context);
1452 g_dbus_connection_send_message_with_reply (connection,
1457 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
1459 g_main_loop_run (data->loop);
1460 reply = g_dbus_connection_send_message_with_reply_finish (connection,
1464 g_main_context_pop_thread_default (data->context);
1466 g_main_context_unref (data->context);
1467 g_main_loop_unref (data->loop);
1468 g_object_unref (data->res);
1474 /* ---------------------------------------------------------------------------------------------------- */
1478 GDBusMessageFilterFunction func;
1485 GDBusMessageFilterFunction filter_function;
1487 GDestroyNotify user_data_free_func;
1490 /* Called in worker's thread - we must not block */
1492 on_worker_message_received (GDBusWorker *worker,
1493 GDBusMessage *message,
1496 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1497 FilterCallback *filters;
1498 gboolean consumed_by_filter;
1502 //g_debug ("in on_worker_message_received");
1504 g_object_ref (connection);
1506 /* First collect the set of callback functions */
1507 CONNECTION_LOCK (connection);
1508 num_filters = connection->priv->filters->len;
1509 filters = g_new0 (FilterCallback, num_filters);
1510 for (n = 0; n < num_filters; n++)
1512 FilterData *data = connection->priv->filters->pdata[n];
1513 filters[n].func = data->filter_function;
1514 filters[n].user_data = data->user_data;
1516 CONNECTION_UNLOCK (connection);
1518 /* the call the filters in order (without holding the lock) */
1519 consumed_by_filter = FALSE;
1520 for (n = 0; n < num_filters; n++)
1522 consumed_by_filter = filters[n].func (connection,
1524 filters[n].user_data);
1525 if (consumed_by_filter)
1529 /* Standard dispatch unless the filter ate the message */
1530 if (!consumed_by_filter)
1532 GDBusMessageType message_type;
1534 message_type = g_dbus_message_get_type (message);
1535 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
1537 guint32 reply_serial;
1538 SendMessageData *send_message_data;
1540 reply_serial = g_dbus_message_get_reply_serial (message);
1541 CONNECTION_LOCK (connection);
1542 send_message_data = g_hash_table_lookup (connection->priv->map_method_serial_to_send_message_data,
1543 GUINT_TO_POINTER (reply_serial));
1544 if (send_message_data != NULL)
1546 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
1547 send_message_data_deliver_reply_unlocked (send_message_data, message);
1551 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
1553 CONNECTION_UNLOCK (connection);
1555 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
1557 CONNECTION_LOCK (connection);
1558 distribute_signals (connection, message);
1559 CONNECTION_UNLOCK (connection);
1561 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
1563 CONNECTION_LOCK (connection);
1564 distribute_method_call (connection, message);
1565 CONNECTION_UNLOCK (connection);
1569 g_object_unref (connection);
1573 /* Called in worker's thread - we must not block */
1575 on_worker_closed (GDBusWorker *worker,
1576 gboolean remote_peer_vanished,
1580 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1582 //g_debug ("in on_worker_closed: %s", error->message);
1584 CONNECTION_LOCK (connection);
1585 if (!connection->priv->closed)
1586 set_closed_unlocked (connection, remote_peer_vanished, error);
1587 CONNECTION_UNLOCK (connection);
1590 /* ---------------------------------------------------------------------------------------------------- */
1592 /* Determines the biggest set of capabilities we can support on this connection */
1593 static GDBusCapabilityFlags
1594 get_offered_capabilities_max (GDBusConnection *connection)
1596 GDBusCapabilityFlags ret;
1597 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
1599 if (G_IS_UNIX_CONNECTION (connection->priv->stream))
1601 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
1609 initable_init (GInitable *initable,
1610 GCancellable *cancellable,
1613 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
1616 /* This method needs to be idempotent to work with the singleton
1617 * pattern. See the docs for g_initable_init(). We implement this by
1620 * Unfortunately we can't use the main lock since the on_worker_*()
1621 * callbacks above needs the lock during initialization (for message
1622 * bus connections we do a synchronous Hello() call on the bus).
1624 g_mutex_lock (connection->priv->init_lock);
1628 if (connection->priv->is_initialized)
1630 if (connection->priv->stream != NULL)
1633 g_assert (connection->priv->initialization_error != NULL);
1636 g_assert (connection->priv->initialization_error == NULL);
1638 /* The user can pass multiple (but mutally exclusive) construct
1641 * - stream (of type GIOStream)
1642 * - address (of type gchar*)
1644 * At the end of the day we end up with a non-NULL GIOStream
1645 * object in connection->priv->stream.
1647 if (connection->priv->address != NULL)
1649 g_assert (connection->priv->stream == NULL);
1651 if ((connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
1652 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
1654 g_set_error_literal (error,
1656 G_IO_ERROR_INVALID_ARGUMENT,
1657 _("Unsupported flags encountered when constructing a client-side connection"));
1661 connection->priv->stream = g_dbus_address_get_stream_sync (connection->priv->address,
1662 NULL, /* TODO: out_guid */
1664 &connection->priv->initialization_error);
1665 if (connection->priv->stream == NULL)
1668 else if (connection->priv->stream != NULL)
1674 g_assert_not_reached ();
1677 /* Authenticate the connection */
1678 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
1680 g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
1681 g_assert (connection->priv->guid != NULL);
1682 connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1683 if (!_g_dbus_auth_run_server (connection->priv->auth,
1684 connection->priv->authentication_observer,
1685 connection->priv->guid,
1686 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
1687 get_offered_capabilities_max (connection),
1688 &connection->priv->capabilities,
1689 &connection->priv->crendentials,
1691 &connection->priv->initialization_error))
1694 else if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
1696 g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
1697 g_assert (connection->priv->guid == NULL);
1698 connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1699 connection->priv->guid = _g_dbus_auth_run_client (connection->priv->auth,
1700 get_offered_capabilities_max (connection),
1701 &connection->priv->capabilities,
1703 &connection->priv->initialization_error);
1704 if (connection->priv->guid == NULL)
1708 if (connection->priv->authentication_observer != NULL)
1710 g_object_unref (connection->priv->authentication_observer);
1711 connection->priv->authentication_observer = NULL;
1714 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->priv->stream)
1716 //g_debug ("haz unix fd passing powers: %d", connection->priv->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
1720 * https://bugzilla.gnome.org/show_bug.cgi?id=616458
1724 if (G_IS_SOCKET_CONNECTION (connection->priv->stream))
1726 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->priv->stream)), FALSE);
1729 connection->priv->worker = _g_dbus_worker_new (connection->priv->stream,
1730 connection->priv->capabilities,
1731 on_worker_message_received,
1735 /* if a bus connection, invoke org.freedesktop.DBus.Hello - this is how we're getting a name */
1736 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
1738 GVariant *hello_result;
1741 hello_result = g_dbus_connection_invoke_method_sync (connection,
1742 "org.freedesktop.DBus", /* name */
1743 "/org/freedesktop/DBus", /* path */
1744 "org.freedesktop.DBus", /* interface */
1746 NULL, /* parameters */
1747 G_DBUS_INVOKE_METHOD_FLAGS_NONE,
1749 NULL, /* TODO: cancellable */
1750 &connection->priv->initialization_error);
1751 if (hello_result == NULL)
1754 g_variant_get (hello_result, "(s)", &s);
1755 connection->priv->bus_unique_name = g_strdup (s);
1756 g_variant_unref (hello_result);
1757 //g_debug ("unique name is `%s'", connection->priv->bus_unique_name);
1760 connection->priv->is_initialized = TRUE;
1766 g_assert (connection->priv->initialization_error != NULL);
1767 g_propagate_error (error, g_error_copy (connection->priv->initialization_error));
1770 g_mutex_unlock (connection->priv->init_lock);
1776 initable_iface_init (GInitableIface *initable_iface)
1778 initable_iface->init = initable_init;
1781 /* ---------------------------------------------------------------------------------------------------- */
1784 async_init_thread (GSimpleAsyncResult *res,
1786 GCancellable *cancellable)
1788 GError *error = NULL;
1790 if (!g_initable_init (G_INITABLE (object), cancellable, &error))
1792 g_simple_async_result_set_from_error (res, error);
1793 g_error_free (error);
1798 async_initable_init_async (GAsyncInitable *initable,
1800 GCancellable *cancellable,
1801 GAsyncReadyCallback callback,
1804 GSimpleAsyncResult *res;
1806 g_return_if_fail (G_IS_INITABLE (initable));
1808 res = g_simple_async_result_new (G_OBJECT (initable), callback, user_data,
1809 async_initable_init_async);
1810 g_simple_async_result_run_in_thread (res, async_init_thread,
1811 io_priority, cancellable);
1812 g_object_unref (res);
1816 async_initable_init_finish (GAsyncInitable *initable,
1820 return TRUE; /* Errors handled by base impl */
1824 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
1826 /* We basically just want to use GIO's default implementation - though that one is
1827 * unfortunately broken, see #615111. So we copy-paste a fixed-up version.
1829 async_initable_iface->init_async = async_initable_init_async;
1830 async_initable_iface->init_finish = async_initable_init_finish;
1833 /* ---------------------------------------------------------------------------------------------------- */
1836 * g_dbus_connection_new:
1837 * @stream: A #GIOStream.
1838 * @guid: The GUID to use if a authenticating as a server or %NULL.
1839 * @flags: Flags describing how to make the connection.
1840 * @authentication_observer: A #GDBusAuthObserver or %NULL.
1841 * @cancellable: A #GCancellable or %NULL.
1842 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
1843 * @user_data: The data to pass to @callback.
1845 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
1846 * with the end represented by @stream.
1848 * If %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER is set in @flags,
1849 * @auth_observer (if not %NULL) is used to assist in the client
1850 * authentication process.
1852 * When the operation is finished, @callback will be invoked. You can
1853 * then call g_dbus_connection_new_finish() to get the result of the
1856 * This is a asynchronous failable constructor. See
1857 * g_dbus_connection_new_sync() for the synchronous
1861 g_dbus_connection_new (GIOStream *stream,
1863 GDBusConnectionFlags flags,
1864 GDBusAuthObserver *authentication_observer,
1865 GCancellable *cancellable,
1866 GAsyncReadyCallback callback,
1869 g_return_if_fail (G_IS_IO_STREAM (stream));
1870 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
1878 "authentication-observer", authentication_observer,
1883 * g_dbus_connection_new_finish:
1884 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
1885 * @error: Return location for error or %NULL.
1887 * Finishes an operation started with g_dbus_connection_new().
1889 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
1892 g_dbus_connection_new_finish (GAsyncResult *res,
1896 GObject *source_object;
1898 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
1899 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1901 source_object = g_async_result_get_source_object (res);
1902 g_assert (source_object != NULL);
1903 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
1906 g_object_unref (source_object);
1908 return G_DBUS_CONNECTION (object);
1914 * g_dbus_connection_new_sync:
1915 * @stream: A #GIOStream.
1916 * @guid: The GUID to use if a authenticating as a server or %NULL.
1917 * @flags: Flags describing how to make the connection.
1918 * @authentication_observer: A #GDBusAuthObserver or %NULL.
1919 * @cancellable: A #GCancellable or %NULL.
1920 * @error: Return location for error or %NULL.
1922 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
1923 * with the end represented by @stream.
1925 * If %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER is set in @flags,
1926 * @auth_observer (if not %NULL) is used to assist in the client
1927 * authentication process.
1929 * This is a synchronous failable constructor. See
1930 * g_dbus_connection_new() for the asynchronous version.
1932 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
1935 g_dbus_connection_new_sync (GIOStream *stream,
1937 GDBusConnectionFlags flags,
1938 GDBusAuthObserver *authentication_observer,
1939 GCancellable *cancellable,
1942 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
1943 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1944 return g_initable_new (G_TYPE_DBUS_CONNECTION,
1950 "authentication-observer", authentication_observer,
1954 /* ---------------------------------------------------------------------------------------------------- */
1957 * g_dbus_connection_new_for_address:
1958 * @address: A D-Bus address.
1959 * @flags: Flags describing how to make the connection.
1960 * @cancellable: A #GCancellable or %NULL.
1961 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
1962 * @user_data: The data to pass to @callback.
1964 * Asynchronously connects and sets up a D-Bus client connection for
1965 * exchanging D-Bus messages with an endpoint specified by @address
1966 * which must be in the D-Bus address format.
1968 * This constructor can only be used to initiate client-side
1969 * connections - use g_dbus_connection_new() if you need to act as the
1970 * server. In particular, @flags cannot contain the
1971 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
1972 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
1974 * When the operation is finished, @callback will be invoked. You can
1975 * then call g_dbus_connection_new_finish() to get the result of the
1978 * This is a asynchronous failable constructor. See
1979 * g_dbus_connection_new_for_address_sync() for the synchronous
1983 g_dbus_connection_new_for_address (const gchar *address,
1984 GDBusConnectionFlags flags,
1985 GCancellable *cancellable,
1986 GAsyncReadyCallback callback,
1989 g_return_if_fail (address != NULL);
1990 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2001 * g_dbus_connection_new_for_address_finish:
2002 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2003 * @error: Return location for error or %NULL.
2005 * Finishes an operation started with g_dbus_connection_new_for_address().
2007 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2010 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2014 GObject *source_object;
2016 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2017 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2019 source_object = g_async_result_get_source_object (res);
2020 g_assert (source_object != NULL);
2021 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2024 g_object_unref (source_object);
2026 return G_DBUS_CONNECTION (object);
2032 * g_dbus_connection_new_for_address_sync:
2033 * @address: A D-Bus address.
2034 * @flags: Flags describing how to make the connection.
2035 * @cancellable: A #GCancellable or %NULL.
2036 * @error: Return location for error or %NULL.
2038 * Synchronously connects and sets up a D-Bus client connection for
2039 * exchanging D-Bus messages with an endpoint specified by @address
2040 * which must be in the D-Bus address format.
2042 * This constructor can only be used to initiate client-side
2043 * connections - use g_dbus_connection_new_sync() if you need to act
2044 * as the server. In particular, @flags cannot contain the
2045 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2046 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2048 * This is a synchronous failable constructor. See
2049 * g_dbus_connection_new_for_address() for the asynchronous version.
2051 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2054 g_dbus_connection_new_for_address_sync (const gchar *address,
2055 GDBusConnectionFlags flags,
2056 GCancellable *cancellable,
2059 g_return_val_if_fail (address != NULL, NULL);
2060 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2061 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2069 /* ---------------------------------------------------------------------------------------------------- */
2072 * g_dbus_connection_set_exit_on_close:
2073 * @connection: A #GDBusConnection.
2074 * @exit_on_close: Whether the process should be terminated
2075 * when @connection is closed by the remote peer.
2077 * Sets whether the process should be terminated when @connection is
2078 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2082 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2083 gboolean exit_on_close)
2085 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2086 connection->priv->exit_on_close = exit_on_close;
2090 * g_dbus_connection_get_exit_on_close:
2091 * @connection: A #GDBusConnection.
2093 * Gets whether the process is terminated when @connection is
2094 * closed by the remote peer. See
2095 * #GDBusConnection:exit-on-close for more details.
2097 * Returns: Whether the process is terminated when @connection is
2098 * closed by the remote peer.
2101 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2103 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2104 return connection->priv->exit_on_close;
2108 * g_dbus_connection_get_guid:
2109 * @connection: A #GDBusConnection.
2111 * The GUID of the peer performing the role of server when
2112 * authenticating. See #GDBusConnection:guid for more details.
2114 * Returns: The GUID. Do not free this string, it is owned by
2118 g_dbus_connection_get_guid (GDBusConnection *connection)
2120 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2121 return connection->priv->guid;
2125 * g_dbus_connection_get_unique_name:
2126 * @connection: A #GDBusConnection.
2128 * Gets the unique name of @connection as assigned by the message
2129 * bus. This can also be used to figure out if @connection is a
2130 * message bus connection.
2132 * Returns: The unique name or %NULL if @connection is not a message
2133 * bus connection. Do not free this string, it is owned by
2137 g_dbus_connection_get_unique_name (GDBusConnection *connection)
2139 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2140 return connection->priv->bus_unique_name;
2144 * g_dbus_connection_get_peer_credentials:
2145 * @connection: A #GDBusConnection.
2147 * Gets the credentials of the authenticated peer. This will always
2148 * return %NULL unless @connection acted as a server
2149 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
2150 * when set up and the client passed credentials as part of the
2151 * authentication process.
2153 * In a message bus setup, the message bus is always the server and
2154 * each application is a client. So this method will always return
2155 * %NULL for message bus clients.
2157 * Returns: A #GCredentials or %NULL if not available. Do not free
2158 * this object, it is owned by @connection.
2161 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
2163 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2164 return connection->priv->crendentials;
2167 /* ---------------------------------------------------------------------------------------------------- */
2169 static guint _global_filter_id = 1;
2172 * g_dbus_connection_add_filter:
2173 * @connection: A #GDBusConnection.
2174 * @filter_function: A filter function.
2175 * @user_data: User data to pass to @filter_function.
2176 * @user_data_free_func: Function to free @user_data with when filter
2177 * is removed or %NULL.
2179 * Adds a message filter. Filters are handlers that are run on all
2180 * incoming messages, prior to standard dispatch. Filters are run in
2181 * the order that they were added. The same handler can be added as a
2182 * filter more than once, in which case it will be run more than once.
2183 * Filters added during a filter callback won't be run on the message
2186 * Note that filters are run in a dedicated message handling thread so
2187 * they can't block and, generally, can't do anything but signal a
2188 * worker thread. Also note that filters are rarely needed - use API
2189 * such as g_dbus_connection_send_message_with_reply(),
2190 * g_dbus_connection_signal_subscribe() or
2191 * g_dbus_connection_invoke_method() instead.
2193 * Returns: A filter identifier that can be used with
2194 * g_dbus_connection_remove_filter().
2197 g_dbus_connection_add_filter (GDBusConnection *connection,
2198 GDBusMessageFilterFunction filter_function,
2200 GDestroyNotify user_data_free_func)
2204 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2205 g_return_val_if_fail (filter_function != NULL, 0);
2207 CONNECTION_LOCK (connection);
2208 data = g_new0 (FilterData, 1);
2209 data->id = _global_filter_id++; /* TODO: overflow etc. */
2210 data->filter_function = filter_function;
2211 data->user_data = user_data;
2212 data->user_data_free_func = user_data_free_func;
2213 g_ptr_array_add (connection->priv->filters, data);
2214 CONNECTION_UNLOCK (connection);
2219 /* only called from finalize(), removes all filters */
2221 purge_all_filters (GDBusConnection *connection)
2224 for (n = 0; n < connection->priv->filters->len; n++)
2226 FilterData *data = connection->priv->filters->pdata[n];
2227 if (data->user_data_free_func != NULL)
2228 data->user_data_free_func (data->user_data);
2234 g_dbus_connection_remove_filter (GDBusConnection *connection,
2238 FilterData *to_destroy;
2240 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2242 CONNECTION_LOCK (connection);
2244 for (n = 0; n < connection->priv->filters->len; n++)
2246 FilterData *data = connection->priv->filters->pdata[n];
2247 if (data->id == filter_id)
2249 g_ptr_array_remove_index (connection->priv->filters, n);
2254 CONNECTION_UNLOCK (connection);
2256 /* do free without holding lock */
2257 if (to_destroy != NULL)
2259 if (to_destroy->user_data_free_func != NULL)
2260 to_destroy->user_data_free_func (to_destroy->user_data);
2261 g_free (to_destroy);
2265 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
2269 /* ---------------------------------------------------------------------------------------------------- */
2275 gchar *interface_name;
2279 GArray *subscribers;
2284 GDBusSignalCallback callback;
2286 GDestroyNotify user_data_free_func;
2288 GMainContext *context;
2292 signal_data_free (SignalData *data)
2294 g_free (data->rule);
2295 g_free (data->sender);
2296 g_free (data->interface_name);
2297 g_free (data->member);
2298 g_free (data->object_path);
2299 g_free (data->arg0);
2300 g_array_free (data->subscribers, TRUE);
2305 args_to_rule (const gchar *sender,
2306 const gchar *interface_name,
2307 const gchar *member,
2308 const gchar *object_path,
2313 rule = g_string_new ("type='signal'");
2315 g_string_append_printf (rule, ",sender='%s'", sender);
2316 if (interface_name != NULL)
2317 g_string_append_printf (rule, ",interface='%s'", interface_name);
2319 g_string_append_printf (rule, ",member='%s'", member);
2320 if (object_path != NULL)
2321 g_string_append_printf (rule, ",path='%s'", object_path);
2323 g_string_append_printf (rule, ",arg0='%s'", arg0);
2325 return g_string_free (rule, FALSE);
2328 static guint _global_subscriber_id = 1;
2329 static guint _global_registration_id = 1;
2330 static guint _global_subtree_registration_id = 1;
2332 /* ---------------------------------------------------------------------------------------------------- */
2334 /* must hold lock when calling */
2336 add_match_rule (GDBusConnection *connection,
2337 const gchar *match_rule)
2340 GDBusMessage *message;
2342 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2343 "/org/freedesktop/DBus", /* path */
2344 "org.freedesktop.DBus", /* interface */
2346 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2349 if (!g_dbus_connection_send_message_unlocked (connection,
2354 g_critical ("Error while sending AddMatch() message: %s", error->message);
2355 g_error_free (error);
2357 g_object_unref (message);
2360 /* ---------------------------------------------------------------------------------------------------- */
2362 /* must hold lock when calling */
2364 remove_match_rule (GDBusConnection *connection,
2365 const gchar *match_rule)
2368 GDBusMessage *message;
2370 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2371 "/org/freedesktop/DBus", /* path */
2372 "org.freedesktop.DBus", /* interface */
2374 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2377 if (!g_dbus_connection_send_message_unlocked (connection,
2382 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
2383 g_error_free (error);
2385 g_object_unref (message);
2388 /* ---------------------------------------------------------------------------------------------------- */
2391 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
2393 return g_strcmp0 (signal_data->sender, "org.freedesktop.DBus") == 0 &&
2394 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
2395 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
2396 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
2397 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
2400 /* ---------------------------------------------------------------------------------------------------- */
2403 * g_dbus_connection_signal_subscribe:
2404 * @connection: A #GDBusConnection.
2405 * @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.
2406 * @interface_name: D-Bus interface name to match on or %NULL to match on all interfaces.
2407 * @member: D-Bus signal name to match on or %NULL to match on all signals.
2408 * @object_path: Object path to match on or %NULL to match on all object paths.
2409 * @arg0: Contents of first string argument to match on or %NULL to match on all kinds of arguments.
2410 * @callback: Callback to invoke when there is a signal matching the requested data.
2411 * @user_data: User data to pass to @callback.
2412 * @user_data_free_func: Function to free @user_data with when subscription is removed or %NULL.
2414 * Subscribes to signals on @connection and invokes @callback with a
2415 * whenever the signal is received. Note that @callback
2416 * will be invoked in the <link
2417 * linkend="g-main-context-push-thread-default">thread-default main
2418 * loop</link> of the thread you are calling this method from.
2420 * It is considered a programming error to use this function if @connection is closed.
2422 * Note that if @sender is not <literal>org.freedesktop.DBus</literal> (for listening to signals from the
2423 * message bus daemon), then it needs to be a unique bus name or %NULL (for listening to signals from any
2424 * name) - you cannot pass a name like <literal>com.example.MyApp</literal>.
2425 * Use e.g. g_bus_watch_name() to find the unique name for the owner of the name you are interested in. Also note
2426 * that this function does not remove a subscription if @sender vanishes from the bus. You have to manually
2427 * call g_dbus_connection_signal_unsubscribe() to remove a subscription.
2429 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
2432 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
2433 const gchar *sender,
2434 const gchar *interface_name,
2435 const gchar *member,
2436 const gchar *object_path,
2438 GDBusSignalCallback callback,
2440 GDestroyNotify user_data_free_func)
2443 SignalData *signal_data;
2444 SignalSubscriber subscriber;
2445 GPtrArray *signal_data_array;
2447 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
2448 * an OOM condition. We might want to change that but that would involve making
2449 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
2450 * handle that. And there's really no sensible way of handling this short of retrying
2451 * to add the match rule... and then there's the little thing that, hey, maybe there's
2452 * a reason the bus in an OOM condition.
2454 * Doable, but not really sure it's worth it...
2457 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2458 g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
2459 g_return_val_if_fail (sender == NULL || ((strcmp (sender, "org.freedesktop.DBus") == 0 || sender[0] == ':') &&
2460 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
2461 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
2462 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
2463 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
2464 g_return_val_if_fail (callback != NULL, 0);
2466 CONNECTION_LOCK (connection);
2468 rule = args_to_rule (sender, interface_name, member, object_path, arg0);
2473 subscriber.callback = callback;
2474 subscriber.user_data = user_data;
2475 subscriber.user_data_free_func = user_data_free_func;
2476 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
2477 subscriber.context = g_main_context_get_thread_default ();
2478 if (subscriber.context != NULL)
2479 g_main_context_ref (subscriber.context);
2481 /* see if we've already have this rule */
2482 signal_data = g_hash_table_lookup (connection->priv->map_rule_to_signal_data, rule);
2483 if (signal_data != NULL)
2485 g_array_append_val (signal_data->subscribers, subscriber);
2490 signal_data = g_new0 (SignalData, 1);
2491 signal_data->rule = rule;
2492 signal_data->sender = g_strdup (sender);
2493 signal_data->interface_name = g_strdup (interface_name);
2494 signal_data->member = g_strdup (member);
2495 signal_data->object_path = g_strdup (object_path);
2496 signal_data->arg0 = g_strdup (arg0);
2497 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2498 g_array_append_val (signal_data->subscribers, subscriber);
2500 g_hash_table_insert (connection->priv->map_rule_to_signal_data,
2504 /* Add the match rule to the bus...
2506 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
2507 * always send such messages to to us.
2509 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2511 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2513 add_match_rule (connection, signal_data->rule);
2518 g_hash_table_insert (connection->priv->map_id_to_signal_data,
2519 GUINT_TO_POINTER (subscriber.id),
2522 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array,
2523 signal_data->sender);
2524 if (signal_data_array == NULL)
2526 signal_data_array = g_ptr_array_new ();
2527 g_hash_table_insert (connection->priv->map_sender_to_signal_data_array,
2528 g_strdup (signal_data->sender),
2531 g_ptr_array_add (signal_data_array, signal_data);
2533 CONNECTION_UNLOCK (connection);
2535 return subscriber.id;
2538 /* ---------------------------------------------------------------------------------------------------- */
2540 /* must hold lock when calling this */
2542 unsubscribe_id_internal (GDBusConnection *connection,
2543 guint subscription_id,
2544 GArray *out_removed_subscribers)
2546 SignalData *signal_data;
2547 GPtrArray *signal_data_array;
2550 signal_data = g_hash_table_lookup (connection->priv->map_id_to_signal_data,
2551 GUINT_TO_POINTER (subscription_id));
2552 if (signal_data == NULL)
2554 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
2558 for (n = 0; n < signal_data->subscribers->len; n++)
2560 SignalSubscriber *subscriber;
2562 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
2563 if (subscriber->id != subscription_id)
2566 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_signal_data,
2567 GUINT_TO_POINTER (subscription_id)));
2568 g_array_append_val (out_removed_subscribers, *subscriber);
2569 g_array_remove_index (signal_data->subscribers, n);
2571 if (signal_data->subscribers->len == 0)
2572 g_warn_if_fail (g_hash_table_remove (connection->priv->map_rule_to_signal_data, signal_data->rule));
2574 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array,
2575 signal_data->sender);
2576 g_warn_if_fail (signal_data_array != NULL);
2577 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
2579 if (signal_data_array->len == 0)
2581 g_warn_if_fail (g_hash_table_remove (connection->priv->map_sender_to_signal_data_array, signal_data->sender));
2583 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
2584 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2586 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2588 remove_match_rule (connection, signal_data->rule);
2592 signal_data_free (signal_data);
2598 g_assert_not_reached ();
2605 * g_dbus_connection_signal_unsubscribe:
2606 * @connection: A #GDBusConnection.
2607 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
2609 * Unsubscribes from signals.
2612 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
2613 guint subscription_id)
2615 GArray *subscribers;
2618 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2620 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2622 CONNECTION_LOCK (connection);
2623 unsubscribe_id_internal (connection,
2626 CONNECTION_UNLOCK (connection);
2629 g_assert (subscribers->len == 0 || subscribers->len == 1);
2631 /* call GDestroyNotify without lock held */
2632 for (n = 0; n < subscribers->len; n++)
2634 SignalSubscriber *subscriber;
2635 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
2636 if (subscriber->user_data_free_func != NULL)
2637 subscriber->user_data_free_func (subscriber->user_data);
2638 if (subscriber->context != NULL)
2639 g_main_context_unref (subscriber->context);
2642 g_array_free (subscribers, TRUE);
2645 /* ---------------------------------------------------------------------------------------------------- */
2649 guint subscription_id;
2650 GDBusSignalCallback callback;
2652 GDBusMessage *message;
2653 GDBusConnection *connection;
2654 const gchar *sender;
2656 const gchar *interface;
2657 const gchar *member;
2660 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
2664 emit_signal_instance_in_idle_cb (gpointer data)
2666 SignalInstance *signal_instance = data;
2667 GVariant *parameters;
2668 gboolean has_subscription;
2670 parameters = g_dbus_message_get_body (signal_instance->message);
2671 if (parameters == NULL)
2673 parameters = g_variant_new ("()");
2674 g_variant_ref_sink (parameters);
2678 g_variant_ref_sink (parameters);
2682 g_debug ("in emit_signal_instance_in_idle_cb (sender=%s path=%s interface=%s member=%s params=%s)",
2683 signal_instance->sender,
2684 signal_instance->path,
2685 signal_instance->interface,
2686 signal_instance->member,
2687 g_variant_print (parameters, TRUE));
2690 /* Careful here, don't do the callback if we no longer has the subscription */
2691 CONNECTION_LOCK (signal_instance->connection);
2692 has_subscription = FALSE;
2693 if (g_hash_table_lookup (signal_instance->connection->priv->map_id_to_signal_data,
2694 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
2695 has_subscription = TRUE;
2696 CONNECTION_UNLOCK (signal_instance->connection);
2698 if (has_subscription)
2700 signal_instance->callback (signal_instance->connection,
2701 signal_instance->sender,
2702 signal_instance->path,
2703 signal_instance->interface,
2704 signal_instance->member,
2706 signal_instance->user_data);
2708 if (parameters != NULL)
2709 g_variant_unref (parameters);
2715 signal_instance_free (SignalInstance *signal_instance)
2717 g_object_unref (signal_instance->message);
2718 g_object_unref (signal_instance->connection);
2719 g_free (signal_instance);
2722 /* called in message handler thread WITH lock held */
2724 schedule_callbacks (GDBusConnection *connection,
2725 GPtrArray *signal_data_array,
2726 GDBusMessage *message,
2727 const gchar *sender)
2730 const gchar *interface;
2731 const gchar *member;
2740 interface = g_dbus_message_get_interface (message);
2741 member = g_dbus_message_get_member (message);
2742 path = g_dbus_message_get_path (message);
2743 arg0 = g_dbus_message_get_arg0 (message);
2746 g_debug ("sender = `%s'", sender);
2747 g_debug ("interface = `%s'", interface);
2748 g_debug ("member = `%s'", member);
2749 g_debug ("path = `%s'", path);
2750 g_debug ("arg0 = `%s'", arg0);
2753 /* TODO: if this is slow, then we can change signal_data_array into
2754 * map_object_path_to_signal_data_array or something.
2756 for (n = 0; n < signal_data_array->len; n++)
2758 SignalData *signal_data = signal_data_array->pdata[n];
2760 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
2763 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
2766 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
2769 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
2772 for (m = 0; m < signal_data->subscribers->len; m++)
2774 SignalSubscriber *subscriber;
2775 GSource *idle_source;
2776 SignalInstance *signal_instance;
2778 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
2780 signal_instance = g_new0 (SignalInstance, 1);
2781 signal_instance->subscription_id = subscriber->id;
2782 signal_instance->callback = subscriber->callback;
2783 signal_instance->user_data = subscriber->user_data;
2784 signal_instance->message = g_object_ref (message);
2785 signal_instance->connection = g_object_ref (connection);
2786 signal_instance->sender = sender;
2787 signal_instance->path = path;
2788 signal_instance->interface = interface;
2789 signal_instance->member = member;
2791 idle_source = g_idle_source_new ();
2792 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
2793 g_source_set_callback (idle_source,
2794 emit_signal_instance_in_idle_cb,
2796 (GDestroyNotify) signal_instance_free);
2797 g_source_attach (idle_source, subscriber->context);
2798 g_source_unref (idle_source);
2803 /* called in message handler thread with lock held */
2805 distribute_signals (GDBusConnection *connection,
2806 GDBusMessage *message)
2808 GPtrArray *signal_data_array;
2809 const gchar *sender;
2811 sender = g_dbus_message_get_sender (message);
2813 /* collect subcsribers that match on sender */
2816 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array, sender);
2817 if (signal_data_array != NULL) {
2818 schedule_callbacks (connection, signal_data_array, message, sender);
2822 /* collect subcsribers not matching on sender */
2823 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array, "");
2824 if (signal_data_array != NULL)
2826 schedule_callbacks (connection, signal_data_array, message, sender);
2830 /* ---------------------------------------------------------------------------------------------------- */
2832 /* only called from finalize(), removes all subscriptions */
2834 purge_all_signal_subscriptions (GDBusConnection *connection)
2836 GHashTableIter iter;
2839 GArray *subscribers;
2842 ids = g_array_new (FALSE, FALSE, sizeof (guint));
2843 g_hash_table_iter_init (&iter, connection->priv->map_id_to_signal_data);
2844 while (g_hash_table_iter_next (&iter, &key, NULL))
2846 guint subscription_id = GPOINTER_TO_UINT (key);
2847 g_array_append_val (ids, subscription_id);
2850 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2851 for (n = 0; n < ids->len; n++)
2853 guint subscription_id = g_array_index (ids, guint, n);
2854 unsubscribe_id_internal (connection,
2858 g_array_free (ids, TRUE);
2860 /* call GDestroyNotify without lock held */
2861 for (n = 0; n < subscribers->len; n++)
2863 SignalSubscriber *subscriber;
2864 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
2865 if (subscriber->user_data_free_func != NULL)
2866 subscriber->user_data_free_func (subscriber->user_data);
2867 if (subscriber->context != NULL)
2868 g_main_context_unref (subscriber->context);
2871 g_array_free (subscribers, TRUE);
2874 /* ---------------------------------------------------------------------------------------------------- */
2876 struct ExportedObject
2879 GDBusConnection *connection;
2881 /* maps gchar* -> ExportedInterface* */
2882 GHashTable *map_if_name_to_ei;
2885 /* only called with lock held */
2887 exported_object_free (ExportedObject *eo)
2889 g_free (eo->object_path);
2890 g_hash_table_unref (eo->map_if_name_to_ei);
2899 gchar *interface_name;
2900 const GDBusInterfaceVTable *vtable;
2901 const GDBusInterfaceInfo *introspection_data;
2903 GMainContext *context;
2905 GDestroyNotify user_data_free_func;
2906 } ExportedInterface;
2908 /* called with lock held */
2910 exported_interface_free (ExportedInterface *ei)
2912 if (ei->user_data_free_func != NULL)
2914 /* TODO: push to thread-default mainloop */
2915 ei->user_data_free_func (ei->user_data);
2917 if (ei->context != NULL)
2919 g_main_context_unref (ei->context);
2921 g_free (ei->interface_name);
2925 /* ---------------------------------------------------------------------------------------------------- */
2929 GDBusConnection *connection;
2930 GDBusMessage *message;
2932 const char *property_name;
2933 const GDBusInterfaceVTable *vtable;
2934 const GDBusInterfaceInfo *interface_info;
2935 const GDBusPropertyInfo *property_info;
2939 property_data_free (PropertyData *data)
2941 g_object_unref (data->connection);
2942 g_object_unref (data->message);
2946 /* called in thread where object was registered - no locks held */
2948 invoke_get_property_in_idle_cb (gpointer _data)
2950 PropertyData *data = _data;
2953 GDBusMessage *reply;
2956 value = data->vtable->get_property (data->connection,
2957 g_dbus_message_get_sender (data->message),
2958 g_dbus_message_get_path (data->message),
2959 data->interface_info->name,
2960 data->property_name,
2967 g_assert_no_error (error);
2969 g_variant_ref_sink (value);
2970 reply = g_dbus_message_new_method_reply (data->message);
2971 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
2972 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
2973 g_variant_unref (value);
2974 g_object_unref (reply);
2978 gchar *dbus_error_name;
2980 g_assert (error != NULL);
2982 dbus_error_name = g_dbus_error_encode_gerror (error);
2983 reply = g_dbus_message_new_method_error_literal (data->message,
2986 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
2987 g_free (dbus_error_name);
2988 g_error_free (error);
2989 g_object_unref (reply);
2995 /* called in thread where object was registered - no locks held */
2997 invoke_set_property_in_idle_cb (gpointer _data)
2999 PropertyData *data = _data;
3001 GDBusMessage *reply;
3007 g_variant_get (g_dbus_message_get_body (data->message),
3013 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
3014 * of the given value is wrong
3016 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
3018 reply = g_dbus_message_new_method_error (data->message,
3019 "org.freedesktop.DBus.Error.InvalidArgs",
3020 _("Error setting property `%s': Expected type `%s' but got `%s'"),
3021 data->property_info->name,
3022 data->property_info->signature,
3023 g_variant_get_type_string (value));
3027 if (!data->vtable->set_property (data->connection,
3028 g_dbus_message_get_sender (data->message),
3029 g_dbus_message_get_path (data->message),
3030 data->interface_info->name,
3031 data->property_name,
3036 gchar *dbus_error_name;
3037 g_assert (error != NULL);
3038 dbus_error_name = g_dbus_error_encode_gerror (error);
3039 reply = g_dbus_message_new_method_error_literal (data->message,
3042 g_free (dbus_error_name);
3043 g_error_free (error);
3047 reply = g_dbus_message_new_method_reply (data->message);
3051 g_assert (reply != NULL);
3052 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3053 g_object_unref (reply);
3058 /* called with lock held */
3060 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
3061 GDBusMessage *message,
3063 const GDBusInterfaceInfo *introspection_data,
3064 const GDBusInterfaceVTable *vtable,
3065 GMainContext *main_context,
3069 const char *interface_name;
3070 const char *property_name;
3071 const GDBusPropertyInfo *property_info;
3072 GSource *idle_source;
3073 PropertyData *property_data;
3074 GDBusMessage *reply;
3079 g_variant_get (g_dbus_message_get_body (message),
3084 g_variant_get (g_dbus_message_get_body (message),
3093 if (vtable == NULL || vtable->get_property == NULL)
3098 if (vtable == NULL || vtable->set_property == NULL)
3102 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
3104 property_info = NULL;
3106 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3107 property_info = g_dbus_interface_info_lookup_property (introspection_data, property_name);
3108 if (property_info == NULL)
3110 reply = g_dbus_message_new_method_error (message,
3111 "org.freedesktop.DBus.Error.InvalidArgs",
3112 _("No such property `%s'"),
3114 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3115 g_object_unref (reply);
3120 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3122 reply = g_dbus_message_new_method_error (message,
3123 "org.freedesktop.DBus.Error.InvalidArgs",
3124 _("Property `%s' is not readable"),
3126 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3127 g_object_unref (reply);
3131 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
3133 reply = g_dbus_message_new_method_error (message,
3134 "org.freedesktop.DBus.Error.InvalidArgs",
3135 _("Property `%s' is not writable"),
3137 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3138 g_object_unref (reply);
3143 /* ok, got the property info - call user code in an idle handler */
3144 property_data = g_new0 (PropertyData, 1);
3145 property_data->connection = g_object_ref (connection);
3146 property_data->message = g_object_ref (message);
3147 property_data->user_data = user_data;
3148 property_data->property_name = property_name;
3149 property_data->vtable = vtable;
3150 property_data->interface_info = introspection_data;
3151 property_data->property_info = property_info;
3153 idle_source = g_idle_source_new ();
3154 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3155 g_source_set_callback (idle_source,
3156 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
3158 (GDestroyNotify) property_data_free);
3159 g_source_attach (idle_source, main_context);
3160 g_source_unref (idle_source);
3168 /* called with lock held */
3170 handle_getset_property (GDBusConnection *connection,
3172 GDBusMessage *message,
3175 ExportedInterface *ei;
3177 const char *interface_name;
3178 const char *property_name;
3183 g_variant_get (g_dbus_message_get_body (message),
3188 g_variant_get (g_dbus_message_get_body (message),
3194 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3195 * no such interface registered
3197 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3200 GDBusMessage *reply;
3201 reply = g_dbus_message_new_method_error (message,
3202 "org.freedesktop.DBus.Error.InvalidArgs",
3203 _("No such interface `%s'"),
3205 g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3206 g_object_unref (reply);
3211 handled = validate_and_maybe_schedule_property_getset (eo->connection,
3214 ei->introspection_data,
3222 /* ---------------------------------------------------------------------------------------------------- */
3226 GDBusConnection *connection;
3227 GDBusMessage *message;
3229 const GDBusInterfaceVTable *vtable;
3230 const GDBusInterfaceInfo *interface_info;
3231 } PropertyGetAllData;
3234 property_get_all_data_free (PropertyData *data)
3236 g_object_unref (data->connection);
3237 g_object_unref (data->message);
3241 /* called in thread where object was registered - no locks held */
3243 invoke_get_all_properties_in_idle_cb (gpointer _data)
3245 PropertyGetAllData *data = _data;
3246 GVariantBuilder *builder;
3250 GDBusMessage *reply;
3255 /* TODO: Right now we never fail this call - we just omit values if
3256 * a get_property() call is failing.
3258 * We could fail the whole call if just a single get_property() call
3259 * returns an error. We need clarification in the D-Bus spec about this.
3261 builder = g_variant_builder_new (G_VARIANT_TYPE_ARRAY);
3262 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
3264 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
3267 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3270 value = data->vtable->get_property (data->connection,
3271 g_dbus_message_get_sender (data->message),
3272 g_dbus_message_get_path (data->message),
3273 data->interface_info->name,
3274 property_info->name,
3281 g_variant_ref_sink (value);
3282 g_variant_builder_add (builder,
3284 property_info->name,
3286 g_variant_unref (value);
3288 result = g_variant_builder_end (builder);
3290 builder = g_variant_builder_new (G_VARIANT_TYPE_TUPLE);
3291 g_variant_builder_add_value (builder, result); /* steals result since result is floating */
3292 packed = g_variant_builder_end (builder);
3294 reply = g_dbus_message_new_method_reply (data->message);
3295 g_dbus_message_set_body (reply, packed);
3296 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3297 g_object_unref (reply);
3302 /* called with lock held */
3304 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
3305 GDBusMessage *message,
3306 const GDBusInterfaceInfo *introspection_data,
3307 const GDBusInterfaceVTable *vtable,
3308 GMainContext *main_context,
3312 const char *interface_name;
3313 GSource *idle_source;
3314 PropertyGetAllData *property_get_all_data;
3318 g_variant_get (g_dbus_message_get_body (message),
3322 if (vtable == NULL || vtable->get_property == NULL)
3325 /* ok, got the property info - call user in an idle handler */
3326 property_get_all_data = g_new0 (PropertyGetAllData, 1);
3327 property_get_all_data->connection = g_object_ref (connection);
3328 property_get_all_data->message = g_object_ref (message);
3329 property_get_all_data->user_data = user_data;
3330 property_get_all_data->vtable = vtable;
3331 property_get_all_data->interface_info = introspection_data;
3333 idle_source = g_idle_source_new ();
3334 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3335 g_source_set_callback (idle_source,
3336 invoke_get_all_properties_in_idle_cb,
3337 property_get_all_data,
3338 (GDestroyNotify) property_get_all_data_free);
3339 g_source_attach (idle_source, main_context);
3340 g_source_unref (idle_source);
3348 /* called with lock held */
3350 handle_get_all_properties (GDBusConnection *connection,
3352 GDBusMessage *message)
3354 ExportedInterface *ei;
3356 const char *interface_name;
3360 g_variant_get (g_dbus_message_get_body (message),
3364 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3365 * no such interface registered
3367 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3370 GDBusMessage *reply;
3371 reply = g_dbus_message_new_method_error (message,
3372 "org.freedesktop.DBus.Error.InvalidArgs",
3373 _("No such interface"),
3375 g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3376 g_object_unref (reply);
3381 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
3383 ei->introspection_data,
3391 /* ---------------------------------------------------------------------------------------------------- */
3394 introspect_append_header (GString *s)
3397 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n\"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
3398 "<!-- GDBus 0.1 -->\n"
3403 introspect_append_standard_interfaces (GString *s)
3406 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
3407 " <method name=\"Get\">\n"
3408 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3409 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3410 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
3412 " <method name=\"GetAll\">\n"
3413 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3414 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
3416 " <method name=\"Set\">\n"
3417 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3418 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3419 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
3421 " <signal name=\"PropertiesChanged\">\n"
3422 " <arg type=\"s\" name=\"interface_name\"/>\n"
3423 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
3426 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
3427 " <method name=\"Introspect\">\n"
3428 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
3431 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
3432 " <method name=\"Ping\"/>\n"
3433 " <method name=\"GetMachineId\">\n"
3434 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
3440 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
3442 if (g_str_has_prefix (object_path, path) && strlen (object_path) >= path_len)
3448 begin = object_path + path_len;
3449 end = strchr (begin, '/');
3453 s = g_strndup (begin, end - begin);
3457 s = g_strdup (begin);
3460 if (g_hash_table_lookup (set, s) == NULL)
3462 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
3471 /* TODO: we want a nicer public interface for this */
3473 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
3478 GHashTableIter hash_iter;
3479 const gchar *object_path;
3485 CONNECTION_ENSURE_LOCK (connection);
3487 path_len = strlen (path);
3491 set = g_hash_table_new (g_str_hash, g_str_equal);
3493 g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_eo);
3494 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3495 maybe_add_path (path, path_len, object_path, set);
3497 g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_es);
3498 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3499 maybe_add_path (path, path_len, object_path, set);
3501 p = g_ptr_array_new ();
3502 keys = g_hash_table_get_keys (set);
3503 for (l = keys; l != NULL; l = l->next)
3505 g_ptr_array_add (p, l->data);
3507 g_hash_table_unref (set);
3510 g_ptr_array_add (p, NULL);
3511 ret = (gchar **) g_ptr_array_free (p, FALSE);
3516 g_dbus_connection_list_registered (GDBusConnection *connection,
3520 CONNECTION_LOCK (connection);
3521 ret = g_dbus_connection_list_registered_unlocked (connection, path);
3522 CONNECTION_UNLOCK (connection);
3526 /* called in message handler thread with lock held */
3528 handle_introspect (GDBusConnection *connection,
3530 GDBusMessage *message)
3534 GDBusMessage *reply;
3535 GHashTableIter hash_iter;
3536 ExportedInterface *ei;
3539 /* first the header with the standard interfaces */
3540 s = g_string_new (NULL);
3541 introspect_append_header (s);
3542 introspect_append_standard_interfaces (s);
3544 /* then include the registered interfaces */
3545 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
3546 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
3548 g_dbus_interface_info_generate_xml (ei->introspection_data, 2, s);
3551 /* finally include nodes registered below us */
3552 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
3553 for (n = 0; registered != NULL && registered[n] != NULL; n++)
3555 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
3557 g_strfreev (registered);
3558 g_string_append (s, "</node>\n");
3560 reply = g_dbus_message_new_method_reply (message);
3561 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
3562 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3563 g_object_unref (reply);
3564 g_string_free (s, TRUE);
3569 /* called in thread where object was registered - no locks held */
3571 invoke_method_in_idle_cb (gpointer user_data)
3573 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
3574 GDBusInterfaceVTable *vtable;
3576 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
3577 g_assert (vtable != NULL && vtable->method_call != NULL);
3579 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
3580 g_dbus_method_invocation_get_sender (invocation),
3581 g_dbus_method_invocation_get_object_path (invocation),
3582 g_dbus_method_invocation_get_interface_name (invocation),
3583 g_dbus_method_invocation_get_method_name (invocation),
3584 g_dbus_method_invocation_get_parameters (invocation),
3585 g_object_ref (invocation),
3586 g_dbus_method_invocation_get_user_data (invocation));
3591 /* called in message handler thread with lock held */
3593 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
3594 GDBusMessage *message,
3595 const GDBusInterfaceInfo *introspection_data,
3596 const GDBusInterfaceVTable *vtable,
3597 GMainContext *main_context,
3600 GDBusMethodInvocation *invocation;
3601 const GDBusMethodInfo *method_info;
3602 GDBusMessage *reply;
3603 GVariant *parameters;
3604 GSource *idle_source;
3606 gchar *in_signature;
3610 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3611 method_info = g_dbus_interface_info_lookup_method (introspection_data, g_dbus_message_get_member (message));
3613 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
3614 * error to the caller
3616 if (method_info == NULL)
3618 reply = g_dbus_message_new_method_error (message,
3619 "org.freedesktop.DBus.Error.UnknownMethod",
3620 _("No such method `%s'"),
3621 g_dbus_message_get_member (message));
3622 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3623 g_object_unref (reply);
3628 /* Check that the incoming args are of the right type - if they are not, return
3629 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
3631 * TODO: might also be worth caching the combined signature.
3633 in_signature = _g_dbus_compute_complete_signature (method_info->in_args, FALSE);
3634 if (g_strcmp0 (g_dbus_message_get_signature (message), in_signature) != 0)
3636 reply = g_dbus_message_new_method_error (message,
3637 "org.freedesktop.DBus.Error.InvalidArgs",
3638 _("Signature of message, `%s', does not match expected signature `%s'"),
3639 g_dbus_message_get_signature (message),
3641 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3642 g_object_unref (reply);
3643 g_free (in_signature);
3647 g_free (in_signature);
3649 parameters = g_dbus_message_get_body (message);
3650 if (parameters == NULL)
3652 parameters = g_variant_new ("()");
3653 g_variant_ref_sink (parameters);
3657 g_variant_ref (parameters);
3660 /* schedule the call in idle */
3661 invocation = g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
3662 g_dbus_message_get_path (message),
3663 g_dbus_message_get_interface (message),
3664 g_dbus_message_get_member (message),
3670 g_variant_unref (parameters);
3671 g_object_set_data (G_OBJECT (invocation),
3672 "g-dbus-interface-vtable",
3675 idle_source = g_idle_source_new ();
3676 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3677 g_source_set_callback (idle_source,
3678 invoke_method_in_idle_cb,
3681 g_source_attach (idle_source, main_context);
3682 g_source_unref (idle_source);
3691 /* ---------------------------------------------------------------------------------------------------- */
3693 /* called in message handler thread with lock held */
3695 obj_message_func (GDBusConnection *connection,
3697 GDBusMessage *message)
3699 const gchar *interface_name;
3700 const gchar *member;
3701 const gchar *signature;
3706 interface_name = g_dbus_message_get_interface (message);
3707 member = g_dbus_message_get_member (message);
3708 signature = g_dbus_message_get_signature (message);
3710 /* see if we have an interface for handling this call */
3711 if (interface_name != NULL)
3713 ExportedInterface *ei;
3714 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3717 /* we do - invoke the handler in idle in the right thread */
3719 /* handle no vtable or handler being present */
3720 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
3723 handled = validate_and_maybe_schedule_method_call (connection,
3725 ei->introspection_data,
3733 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
3734 g_strcmp0 (member, "Introspect") == 0 &&
3735 g_strcmp0 (signature, "") == 0)
3737 handled = handle_introspect (connection, eo, message);
3740 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3741 g_strcmp0 (member, "Get") == 0 &&
3742 g_strcmp0 (signature, "ss") == 0)
3744 handled = handle_getset_property (connection, eo, message, TRUE);
3747 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3748 g_strcmp0 (member, "Set") == 0 &&
3749 g_strcmp0 (signature, "ssv") == 0)
3751 handled = handle_getset_property (connection, eo, message, FALSE);
3754 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3755 g_strcmp0 (member, "GetAll") == 0 &&
3756 g_strcmp0 (signature, "s") == 0)
3758 handled = handle_get_all_properties (connection, eo, message);
3767 * g_dbus_connection_register_object:
3768 * @connection: A #GDBusConnection.
3769 * @object_path: The object path to register at.
3770 * @interface_name: The D-Bus interface to register.
3771 * @introspection_data: Introspection data for the interface.
3772 * @vtable: A #GDBusInterfaceVTable to call into or %NULL.
3773 * @user_data: Data to pass to functions in @vtable.
3774 * @user_data_free_func: Function to call when the object path is unregistered.
3775 * @error: Return location for error or %NULL.
3777 * Registers callbacks for exported objects at @object_path with the
3778 * D-Bus interface @interface_name.
3780 * Calls to functions in @vtable (and @user_data_free_func) will
3781 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
3782 * loop</link> of the thread you are calling this method from.
3784 * Note that all #GVariant values passed to functions in @vtable will match
3785 * the signature given in @introspection_data - if a remote caller passes
3786 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
3787 * is returned to the remote caller.
3789 * Additionally, if the remote caller attempts to invoke methods or
3790 * access properties not mentioned in @introspection_data the
3791 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
3792 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
3793 * are returned to the caller.
3795 * It is considered a programming error if the
3796 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
3797 * #GVariant of incorrect type.
3799 * If an existing callback is already registered at @object_path and
3800 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
3802 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
3804 * Returns: 0 if @error is set, otherwise a registration id (never 0)
3805 * that can be used with g_dbus_connection_unregister_object() .
3808 g_dbus_connection_register_object (GDBusConnection *connection,
3809 const gchar *object_path,
3810 const gchar *interface_name,
3811 const GDBusInterfaceInfo *introspection_data,
3812 const GDBusInterfaceVTable *vtable,
3814 GDestroyNotify user_data_free_func,
3818 ExportedInterface *ei;
3821 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3822 g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
3823 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
3824 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3825 g_return_val_if_fail (introspection_data != NULL, 0);
3826 g_return_val_if_fail (error == NULL || *error == NULL, 0);
3830 CONNECTION_LOCK (connection);
3832 eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
3835 eo = g_new0 (ExportedObject, 1);
3836 eo->object_path = g_strdup (object_path);
3837 eo->connection = connection;
3838 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
3841 (GDestroyNotify) exported_interface_free);
3842 g_hash_table_insert (connection->priv->map_object_path_to_eo, eo->object_path, eo);
3845 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3851 _("An object is already exported for the interface %s at %s"),
3857 ei = g_new0 (ExportedInterface, 1);
3858 ei->id = _global_registration_id++; /* TODO: overflow etc. */
3860 ei->user_data = user_data;
3861 ei->user_data_free_func = user_data_free_func;
3862 ei->vtable = vtable;
3863 ei->introspection_data = introspection_data;
3864 ei->interface_name = g_strdup (interface_name);
3865 ei->context = g_main_context_get_thread_default ();
3866 if (ei->context != NULL)
3867 g_main_context_ref (ei->context);
3869 g_hash_table_insert (eo->map_if_name_to_ei,
3870 (gpointer) ei->interface_name,
3872 g_hash_table_insert (connection->priv->map_id_to_ei,
3873 GUINT_TO_POINTER (ei->id),
3879 CONNECTION_UNLOCK (connection);
3885 * g_dbus_connection_unregister_object:
3886 * @connection: A #GDBusConnection.
3887 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
3889 * Unregisters an object.
3891 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
3894 g_dbus_connection_unregister_object (GDBusConnection *connection,
3895 guint registration_id)
3897 ExportedInterface *ei;
3901 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3905 CONNECTION_LOCK (connection);
3907 ei = g_hash_table_lookup (connection->priv->map_id_to_ei,
3908 GUINT_TO_POINTER (registration_id));
3916 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
3917 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
3918 /* unregister object path if we have no more exported interfaces */
3919 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
3921 g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_eo,
3928 CONNECTION_UNLOCK (connection);
3933 /* ---------------------------------------------------------------------------------------------------- */
3936 * g_dbus_connection_emit_signal:
3937 * @connection: A #GDBusConnection.
3938 * @destination_bus_name: The unique bus name for the destination for the signal or %NULL to emit to all listeners.
3939 * @object_path: Path of remote object.
3940 * @interface_name: D-Bus interface to emit a signal on.
3941 * @signal_name: The name of the signal to emit.
3942 * @parameters: A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
3943 * @error: Return location for error or %NULL.
3947 * This can only fail if @parameters is not compatible with the D-Bus protocol.
3949 * Returns: %TRUE unless @error is set.
3952 g_dbus_connection_emit_signal (GDBusConnection *connection,
3953 const gchar *destination_bus_name,
3954 const gchar *object_path,
3955 const gchar *interface_name,
3956 const gchar *signal_name,
3957 GVariant *parameters,
3960 GDBusMessage *message;
3966 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3967 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
3968 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
3969 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
3970 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
3971 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
3973 message = g_dbus_message_new_signal (object_path,
3977 if (destination_bus_name != NULL)
3979 g_dbus_message_set_header (message,
3980 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
3981 g_variant_new_string (destination_bus_name));
3984 if (parameters != NULL)
3985 g_dbus_message_set_body (message, parameters);
3987 ret = g_dbus_connection_send_message (connection, message, NULL, error);
3988 g_object_unref (message);
3994 add_invoke_method_flags (GDBusMessage *message,
3995 GDBusInvokeMethodFlags flags)
3997 if (flags & G_DBUS_INVOKE_METHOD_FLAGS_NO_AUTO_START)
3998 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
4002 * g_dbus_connection_invoke_method:
4003 * @connection: A #GDBusConnection.
4004 * @bus_name: A unique or well-known bus name or %NULL if @connection is not a message bus connection.
4005 * @object_path: Path of remote object.
4006 * @interface_name: D-Bus interface to invoke method on.
4007 * @method_name: The name of the method to invoke.
4008 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4009 * @flags: Flags from the #GDBusInvokeMethodFlags enumeration.
4010 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4011 * @cancellable: A #GCancellable or %NULL.
4012 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
4013 * care about the result of the method invocation.
4014 * @user_data: The data to pass to @callback.
4016 * Asynchronously invokes the @method_name method on the
4017 * @interface_name D-Bus interface on the remote object at
4018 * @object_path owned by @bus_name.
4020 * If @connection is closed then the operation will fail with
4021 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
4022 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
4023 * not compatible with the D-Bus protocol, the operation fails with
4024 * %G_IO_ERROR_INVALID_ARGUMENT.
4026 * This is an asynchronous method. When the operation is finished, @callback will be invoked
4027 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
4028 * of the thread you are calling this method from. You can then call
4029 * g_dbus_connection_invoke_method_finish() to get the result of the operation.
4030 * See g_dbus_connection_invoke_method_sync() for the synchronous version of this
4034 g_dbus_connection_invoke_method (GDBusConnection *connection,
4035 const gchar *bus_name,
4036 const gchar *object_path,
4037 const gchar *interface_name,
4038 const gchar *method_name,
4039 GVariant *parameters,
4040 GDBusInvokeMethodFlags flags,
4042 GCancellable *cancellable,
4043 GAsyncReadyCallback callback,
4046 GDBusMessage *message;
4048 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4049 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
4050 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
4051 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
4052 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
4053 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
4054 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
4056 message = g_dbus_message_new_method_call (bus_name,
4060 add_invoke_method_flags (message, flags);
4061 if (parameters != NULL)
4062 g_dbus_message_set_body (message, parameters);
4064 g_dbus_connection_send_message_with_reply (connection,
4067 NULL, /* volatile guint32 *out_serial */
4072 if (message != NULL)
4073 g_object_unref (message);
4077 decode_method_reply (GDBusMessage *reply, GError **error)
4082 switch (g_dbus_message_get_type (reply))
4084 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
4085 result = g_dbus_message_get_body (reply);
4088 result = g_variant_new ("()");
4089 g_variant_ref_sink (result);
4093 g_variant_ref (result);
4096 case G_DBUS_MESSAGE_TYPE_ERROR:
4097 g_dbus_message_to_gerror (reply, error);
4101 g_assert_not_reached ();
4109 * g_dbus_connection_invoke_method_finish:
4110 * @connection: A #GDBusConnection.
4111 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_invoke_method().
4112 * @error: Return location for error or %NULL.
4114 * Finishes an operation started with g_dbus_connection_invoke_method().
4116 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4117 * return values. Free with g_variant_unref().
4120 g_dbus_connection_invoke_method_finish (GDBusConnection *connection,
4124 GDBusMessage *reply;
4127 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4128 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
4129 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4133 reply = g_dbus_connection_send_message_with_reply_finish (connection, res, error);
4137 result = decode_method_reply (reply, error);
4139 g_object_unref (reply);
4145 /* ---------------------------------------------------------------------------------------------------- */
4148 * g_dbus_connection_invoke_method_sync:
4149 * @connection: A #GDBusConnection.
4150 * @bus_name: A unique or well-known bus name.
4151 * @object_path: Path of remote object.
4152 * @interface_name: D-Bus interface to invoke method on.
4153 * @method_name: The name of the method to invoke.
4154 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4155 * @flags: Flags from the #GDBusInvokeMethodFlags enumeration.
4156 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4157 * @cancellable: A #GCancellable or %NULL.
4158 * @error: Return location for error or %NULL.
4160 * Synchronously invokes the @method_name method on the
4161 * @interface_name D-Bus interface on the remote object at
4162 * @object_path owned by @bus_name.
4164 * If @connection is closed then the operation will fail with
4165 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
4166 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
4167 * contains a value not compatible with the D-Bus protocol, the operation
4168 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
4170 * The calling thread is blocked until a reply is received. See
4171 * g_dbus_connection_invoke_method() for the asynchronous version of
4174 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4175 * return values. Free with g_variant_unref().
4178 g_dbus_connection_invoke_method_sync (GDBusConnection *connection,
4179 const gchar *bus_name,
4180 const gchar *object_path,
4181 const gchar *interface_name,
4182 const gchar *method_name,
4183 GVariant *parameters,
4184 GDBusInvokeMethodFlags flags,
4186 GCancellable *cancellable,
4189 GDBusMessage *message;
4190 GDBusMessage *reply;
4197 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4198 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
4199 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
4200 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
4201 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
4202 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
4203 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
4205 message = g_dbus_message_new_method_call (bus_name,
4209 add_invoke_method_flags (message, flags);
4210 if (parameters != NULL)
4211 g_dbus_message_set_body (message, parameters);
4213 reply = g_dbus_connection_send_message_with_reply_sync (connection,
4216 NULL, /* volatile guint32 *out_serial */
4223 result = decode_method_reply (reply, error);
4226 if (message != NULL)
4227 g_object_unref (message);
4229 g_object_unref (reply);
4234 /* ---------------------------------------------------------------------------------------------------- */
4236 struct ExportedSubtree
4240 GDBusConnection *connection;
4241 const GDBusSubtreeVTable *vtable;
4242 GDBusSubtreeFlags flags;
4244 GMainContext *context;
4246 GDestroyNotify user_data_free_func;
4250 exported_subtree_free (ExportedSubtree *es)
4252 if (es->user_data_free_func != NULL)
4254 /* TODO: push to thread-default mainloop */
4255 es->user_data_free_func (es->user_data);
4257 if (es->context != NULL)
4259 g_main_context_unref (es->context);
4261 g_free (es->object_path);
4265 /* called without lock held */
4267 handle_subtree_introspect (GDBusConnection *connection,
4268 ExportedSubtree *es,
4269 GDBusMessage *message)
4273 GDBusMessage *reply;
4276 const gchar *sender;
4277 const gchar *requested_object_path;
4278 const gchar *requested_node;
4279 GPtrArray *interfaces;
4281 gchar **subnode_paths;
4285 requested_object_path = g_dbus_message_get_path (message);
4286 sender = g_dbus_message_get_sender (message);
4287 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4289 s = g_string_new (NULL);
4290 introspect_append_header (s);
4292 /* Strictly we don't need the children in dynamic mode, but we avoid the
4293 * conditionals to preserve code clarity
4295 children = es->vtable->enumerate (es->connection,
4302 requested_node = strrchr (requested_object_path, '/') + 1;
4304 /* Assert existence of object if we are not dynamic */
4305 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4306 !_g_strv_has_string ((const gchar * const *) children, requested_node))
4311 requested_node = "/";
4314 interfaces = es->vtable->introspect (es->connection,
4319 if (interfaces != NULL)
4321 if (interfaces->len > 0)
4323 /* we're in business */
4324 introspect_append_standard_interfaces (s);
4326 for (n = 0; n < interfaces->len; n++)
4328 const GDBusInterfaceInfo *interface_info = interfaces->pdata[n];
4329 g_dbus_interface_info_generate_xml (interface_info, 2, s);
4332 g_ptr_array_unref (interfaces);
4335 /* then include <node> entries from the Subtree for the root */
4338 for (n = 0; children != NULL && children[n] != NULL; n++)
4340 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
4344 /* finally include nodes registered below us */
4345 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
4346 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
4348 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
4350 g_strfreev (subnode_paths);
4352 g_string_append (s, "</node>\n");
4354 reply = g_dbus_message_new_method_reply (message);
4355 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4356 g_dbus_connection_send_message (connection, reply, NULL, NULL);
4357 g_object_unref (reply);
4362 g_string_free (s, TRUE);
4363 g_strfreev (children);
4367 /* called without lock held */
4369 handle_subtree_method_invocation (GDBusConnection *connection,
4370 ExportedSubtree *es,
4371 GDBusMessage *message)
4374 const gchar *sender;
4375 const gchar *interface_name;
4376 const gchar *member;
4377 const gchar *signature;
4378 const gchar *requested_object_path;
4379 const gchar *requested_node;
4382 const GDBusInterfaceInfo *introspection_data;
4383 const GDBusInterfaceVTable *interface_vtable;
4384 gpointer interface_user_data;
4386 GPtrArray *interfaces;
4387 gboolean is_property_get;
4388 gboolean is_property_set;
4389 gboolean is_property_get_all;
4394 requested_object_path = g_dbus_message_get_path (message);
4395 sender = g_dbus_message_get_sender (message);
4396 interface_name = g_dbus_message_get_interface (message);
4397 member = g_dbus_message_get_member (message);
4398 signature = g_dbus_message_get_signature (message);
4399 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4401 is_property_get = FALSE;
4402 is_property_set = FALSE;
4403 is_property_get_all = FALSE;
4404 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
4406 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
4408 is_property_get = TRUE;
4410 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
4412 is_property_set = TRUE;
4414 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
4416 is_property_get_all = TRUE;
4420 children = es->vtable->enumerate (es->connection,
4427 requested_node = strrchr (requested_object_path, '/') + 1;
4429 /* If not dynamic, skip if requested node is not part of children */
4430 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4431 !_g_strv_has_string ((const gchar * const *) children, requested_node))
4436 requested_node = "/";
4439 /* get introspection data for the node */
4440 interfaces = es->vtable->introspect (es->connection,
4442 requested_object_path,
4445 g_assert (interfaces != NULL);
4446 introspection_data = NULL;
4447 for (n = 0; n < interfaces->len; n++)
4449 const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4450 if (g_strcmp0 (id_n->name, interface_name) == 0)
4452 introspection_data = id_n;
4456 /* dispatch the call if the user wants to handle it */
4457 if (introspection_data != NULL)
4459 /* figure out where to dispatch the method call */
4460 interface_user_data = NULL;
4461 interface_vtable = es->vtable->dispatch (es->connection,
4466 &interface_user_data,
4468 if (interface_vtable == NULL)
4471 CONNECTION_LOCK (connection);
4472 handled = validate_and_maybe_schedule_method_call (es->connection,
4477 interface_user_data);
4478 CONNECTION_UNLOCK (connection);
4480 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
4481 else if (is_property_get || is_property_set || is_property_get_all)
4483 if (is_property_get)
4484 g_variant_get (g_dbus_message_get_body (message), "(ss)", &interface_name, NULL);
4485 else if (is_property_set)
4486 g_variant_get (g_dbus_message_get_body (message), "(ssv)", &interface_name, NULL, NULL);
4487 else if (is_property_get_all)
4488 g_variant_get (g_dbus_message_get_body (message), "(s)", &interface_name, NULL, NULL);
4490 g_assert_not_reached ();
4492 /* see if the object supports this interface at all */
4493 for (n = 0; n < interfaces->len; n++)
4495 const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4496 if (g_strcmp0 (id_n->name, interface_name) == 0)
4498 introspection_data = id_n;
4502 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
4503 * claims it won't support the interface
4505 if (introspection_data == NULL)
4507 GDBusMessage *reply;
4508 reply = g_dbus_message_new_method_error (message,
4509 "org.freedesktop.DBus.Error.InvalidArgs",
4510 _("No such interface `%s'"),
4512 g_dbus_connection_send_message (es->connection, reply, NULL, NULL);
4513 g_object_unref (reply);
4518 /* figure out where to dispatch the property get/set/getall calls */
4519 interface_user_data = NULL;
4520 interface_vtable = es->vtable->dispatch (es->connection,
4525 &interface_user_data,
4527 if (interface_vtable == NULL)
4530 if (is_property_get || is_property_set)
4532 CONNECTION_LOCK (connection);
4533 handled = validate_and_maybe_schedule_property_getset (es->connection,
4539 interface_user_data);
4540 CONNECTION_UNLOCK (connection);
4542 else if (is_property_get_all)
4544 CONNECTION_LOCK (connection);
4545 handled = validate_and_maybe_schedule_property_get_all (es->connection,
4550 interface_user_data);
4551 CONNECTION_UNLOCK (connection);
4556 if (interfaces != NULL)
4557 g_ptr_array_unref (interfaces);
4558 g_strfreev (children);
4564 GDBusMessage *message;
4565 ExportedSubtree *es;
4566 } SubtreeDeferredData;
4569 subtree_deferred_data_free (SubtreeDeferredData *data)
4571 g_object_unref (data->message);
4575 /* called without lock held in the thread where the caller registered the subtree */
4577 process_subtree_vtable_message_in_idle_cb (gpointer _data)
4579 SubtreeDeferredData *data = _data;
4584 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
4585 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
4586 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
4588 handled = handle_subtree_introspect (data->es->connection,
4594 handled = handle_subtree_method_invocation (data->es->connection,
4602 CONNECTION_LOCK (data->es->connection);
4603 handled = handle_generic_unlocked (data->es->connection, data->message);
4604 CONNECTION_UNLOCK (data->es->connection);
4607 /* if we couldn't handle the request, just bail with the UnknownMethod error */
4610 GDBusMessage *reply;
4611 reply = g_dbus_message_new_method_error (data->message,
4612 "org.freedesktop.DBus.Error.UnknownMethod",
4613 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
4614 g_dbus_message_get_member (data->message),
4615 g_dbus_message_get_interface (data->message),
4616 g_dbus_message_get_signature (data->message));
4617 g_dbus_connection_send_message (data->es->connection, reply, NULL, NULL);
4618 g_object_unref (reply);
4624 /* called in message handler thread with lock held */
4626 subtree_message_func (GDBusConnection *connection,
4627 ExportedSubtree *es,
4628 GDBusMessage *message)
4630 GSource *idle_source;
4631 SubtreeDeferredData *data;
4633 data = g_new0 (SubtreeDeferredData, 1);
4634 data->message = g_object_ref (message);
4637 /* defer this call to an idle handler in the right thread */
4638 idle_source = g_idle_source_new ();
4639 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
4640 g_source_set_callback (idle_source,
4641 process_subtree_vtable_message_in_idle_cb,
4643 (GDestroyNotify) subtree_deferred_data_free);
4644 g_source_attach (idle_source, es->context);
4645 g_source_unref (idle_source);
4647 /* since we own the entire subtree, handlers for objects not in the subtree have been
4648 * tried already by libdbus-1 - so we just need to ensure that we're always going
4649 * to reply to the message
4655 * g_dbus_connection_register_subtree:
4656 * @connection: A #GDBusConnection.
4657 * @object_path: The object path to register the subtree at.
4658 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
4659 * @flags: Flags used to fine tune the behavior of the subtree.
4660 * @user_data: Data to pass to functions in @vtable.
4661 * @user_data_free_func: Function to call when the subtree is unregistered.
4662 * @error: Return location for error or %NULL.
4664 * Registers a whole subtree of <quote>dynamic</quote> objects.
4666 * The @enumerate and @introspection functions in @vtable are used to
4667 * convey, to remote callers, what nodes exist in the subtree rooted
4670 * When handling remote calls into any node in the subtree, first the
4671 * @enumerate function is used to check if the node exists. If the node exists
4672 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
4673 * the @introspection function is used to check if the node supports the
4674 * requested method. If so, the @dispatch function is used to determine
4675 * where to dispatch the call. The collected #GDBusInterfaceVTable and
4676 * #gpointer will be used to call into the interface vtable for processing
4679 * All calls into user-provided code will be invoked in the <link
4680 * linkend="g-main-context-push-thread-default">thread-default main
4681 * loop</link> of the thread you are calling this method from.
4683 * If an existing subtree is already registered at @object_path or
4684 * then @error is set to #G_IO_ERROR_EXISTS.
4686 * Note that it is valid to register regular objects (using
4687 * g_dbus_connection_register_object()) in a subtree registered with
4688 * g_dbus_connection_register_subtree() - if so, the subtree handler
4689 * is tried as the last resort. One way to think about a subtree
4690 * handler is to consider it a <quote>fallback handler</quote>
4691 * for object paths not registered via g_dbus_connection_register_object()
4692 * or other bindings.
4694 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
4696 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
4697 * that can be used with g_dbus_connection_unregister_subtree() .
4700 g_dbus_connection_register_subtree (GDBusConnection *connection,
4701 const gchar *object_path,
4702 const GDBusSubtreeVTable *vtable,
4703 GDBusSubtreeFlags flags,
4705 GDestroyNotify user_data_free_func,
4709 ExportedSubtree *es;
4711 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4712 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4713 g_return_val_if_fail (vtable != NULL, 0);
4714 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4718 CONNECTION_LOCK (connection);
4720 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
4726 _("A subtree is already exported for %s"),
4731 es = g_new0 (ExportedSubtree, 1);
4732 es->object_path = g_strdup (object_path);
4733 es->connection = connection;
4735 es->vtable = vtable;
4737 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
4738 es->user_data = user_data;
4739 es->user_data_free_func = user_data_free_func;
4740 es->context = g_main_context_get_thread_default ();
4741 if (es->context != NULL)
4742 g_main_context_ref (es->context);
4744 g_hash_table_insert (connection->priv->map_object_path_to_es, es->object_path, es);
4745 g_hash_table_insert (connection->priv->map_id_to_es,
4746 GUINT_TO_POINTER (es->id),
4752 CONNECTION_UNLOCK (connection);
4757 /* ---------------------------------------------------------------------------------------------------- */
4760 * g_dbus_connection_unregister_subtree:
4761 * @connection: A #GDBusConnection.
4762 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
4764 * Unregisters a subtree.
4766 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
4769 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
4770 guint registration_id)
4772 ExportedSubtree *es;
4775 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4779 CONNECTION_LOCK (connection);
4781 es = g_hash_table_lookup (connection->priv->map_id_to_es,
4782 GUINT_TO_POINTER (registration_id));
4788 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_es, GUINT_TO_POINTER (es->id)));
4789 g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_es, es->object_path));
4794 CONNECTION_UNLOCK (connection);
4799 /* ---------------------------------------------------------------------------------------------------- */
4801 /* must be called with lock held */
4803 handle_generic_ping_unlocked (GDBusConnection *connection,
4804 const gchar *object_path,
4805 GDBusMessage *message)
4807 GDBusMessage *reply;
4808 reply = g_dbus_message_new_method_reply (message);
4809 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4810 g_object_unref (reply);
4813 /* must be called with lock held */
4815 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
4816 const gchar *object_path,
4817 GDBusMessage *message)
4819 GDBusMessage *reply;
4822 if (connection->priv->machine_id == NULL)
4826 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
4827 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
4828 &connection->priv->machine_id,
4832 reply = g_dbus_message_new_method_error (message,
4833 "org.freedesktop.DBus.Error.Failed",
4834 _("Unable to load /var/lib/dbus/machine-id: %s"),
4836 g_error_free (error);
4840 g_strstrip (connection->priv->machine_id);
4841 /* TODO: validate value */
4847 reply = g_dbus_message_new_method_reply (message);
4848 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->priv->machine_id));
4850 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4851 g_object_unref (reply);
4854 /* must be called with lock held */
4856 handle_generic_introspect_unlocked (GDBusConnection *connection,
4857 const gchar *object_path,
4858 GDBusMessage *message)
4863 GDBusMessage *reply;
4865 /* first the header */
4866 s = g_string_new (NULL);
4867 introspect_append_header (s);
4869 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
4870 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4872 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4874 g_strfreev (registered);
4875 g_string_append (s, "</node>\n");
4877 reply = g_dbus_message_new_method_reply (message);
4878 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4879 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4880 g_object_unref (reply);
4881 g_string_free (s, TRUE);
4884 /* must be called with lock held */
4886 handle_generic_unlocked (GDBusConnection *connection,
4887 GDBusMessage *message)
4890 const gchar *interface_name;
4891 const gchar *member;
4892 const gchar *signature;
4895 CONNECTION_ENSURE_LOCK (connection);
4899 interface_name = g_dbus_message_get_interface (message);
4900 member = g_dbus_message_get_member (message);
4901 signature = g_dbus_message_get_signature (message);
4902 path = g_dbus_message_get_path (message);
4904 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4905 g_strcmp0 (member, "Introspect") == 0 &&
4906 g_strcmp0 (signature, "") == 0)
4908 handle_generic_introspect_unlocked (connection, path, message);
4911 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
4912 g_strcmp0 (member, "Ping") == 0 &&
4913 g_strcmp0 (signature, "") == 0)
4915 handle_generic_ping_unlocked (connection, path, message);
4918 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
4919 g_strcmp0 (member, "GetMachineId") == 0 &&
4920 g_strcmp0 (signature, "") == 0)
4922 handle_generic_get_machine_id_unlocked (connection, path, message);
4929 /* ---------------------------------------------------------------------------------------------------- */
4931 /* called in message handler thread with lock held */
4933 distribute_method_call (GDBusConnection *connection,
4934 GDBusMessage *message)
4937 ExportedSubtree *es;
4938 const gchar *object_path;
4939 const gchar *interface_name;
4940 const gchar *member;
4941 const gchar *signature;
4943 gchar *subtree_path;
4946 g_assert (g_dbus_message_get_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
4948 interface_name = g_dbus_message_get_interface (message);
4949 member = g_dbus_message_get_member (message);
4950 signature = g_dbus_message_get_signature (message);
4951 path = g_dbus_message_get_path (message);
4952 subtree_path = g_strdup (path);
4953 needle = strrchr (subtree_path, '/');
4954 if (needle != NULL && needle != subtree_path)
4960 g_free (subtree_path);
4961 subtree_path = NULL;
4965 g_debug ("interface = `%s'", interface_name);
4966 g_debug ("member = `%s'", member);
4967 g_debug ("signature = `%s'", signature);
4968 g_debug ("path = `%s'", path);
4969 g_debug ("subtree_path = `%s'", subtree_path != NULL ? subtree_path : "N/A");
4972 object_path = g_dbus_message_get_path (message);
4973 g_assert (object_path != NULL);
4975 eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
4978 if (obj_message_func (connection, eo, message))
4982 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
4985 if (subtree_message_func (connection, es, message))
4989 if (subtree_path != NULL)
4991 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, subtree_path);
4994 if (subtree_message_func (connection, es, message))
4999 if (handle_generic_unlocked (connection, message))
5002 /* if we end up here, the message has not been not handled */
5005 g_free (subtree_path);
5008 /* ---------------------------------------------------------------------------------------------------- */
5010 static GDBusConnection **
5011 message_bus_get_singleton (GBusType bus_type,
5014 GDBusConnection **ret;
5015 const gchar *starter_bus;
5022 g_assert_not_reached ();
5025 case G_BUS_TYPE_SESSION:
5026 ret = &the_session_bus;
5029 case G_BUS_TYPE_SYSTEM:
5030 ret = &the_system_bus;
5033 case G_BUS_TYPE_STARTER:
5034 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
5035 if (g_strcmp0 (starter_bus, "session") == 0)
5037 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
5040 else if (g_strcmp0 (starter_bus, "system") == 0)
5042 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
5047 if (starter_bus != NULL)
5051 G_IO_ERROR_INVALID_ARGUMENT,
5052 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
5053 " - unknown value `%s'"),
5058 g_set_error_literal (error,
5060 G_IO_ERROR_INVALID_ARGUMENT,
5061 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
5062 "variable is not set"));
5071 static GDBusConnection *
5072 get_uninitialized_connection (GBusType bus_type,
5073 GCancellable *cancellable,
5076 GDBusConnection **singleton;
5077 GDBusConnection *ret;
5081 G_LOCK (message_bus_lock);
5082 singleton = message_bus_get_singleton (bus_type, error);
5083 if (singleton == NULL)
5086 if (*singleton == NULL)
5089 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
5090 if (address == NULL)
5092 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
5094 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
5095 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
5096 "exit-on-close", TRUE,
5101 ret = g_object_ref (*singleton);
5104 g_assert (ret != NULL);
5107 G_UNLOCK (message_bus_lock);
5113 * @bus_type: A #GBusType.
5114 * @cancellable: A #GCancellable or %NULL.
5115 * @error: Return location for error or %NULL.
5117 * Synchronously connects to the message bus specified by @bus_type.
5118 * Note that the returned object may shared with other callers,
5119 * e.g. if two separate parts of a process calls this function with
5120 * the same @bus_type, they will share the same object.
5122 * This is a synchronous failable function. See g_bus_get() and
5123 * g_bus_get_finish() for the asynchronous version.
5125 * The returned object is a singleton, that is, shared with other
5126 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5127 * event that you need a private message bus connection, use
5128 * g_dbus_address_get_for_bus() and
5129 * g_dbus_connection_new_for_address().
5131 * Note that the returned #GDBusConnection object will (usually) have
5132 * the #GDBusConnection:exit-on-close property set to %TRUE.
5134 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5137 g_bus_get_sync (GBusType bus_type,
5138 GCancellable *cancellable,
5141 GDBusConnection *connection;
5143 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5145 connection = get_uninitialized_connection (bus_type, cancellable, error);
5146 if (connection == NULL)
5149 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
5151 g_object_unref (connection);
5160 bus_get_async_initable_cb (GObject *source_object,
5164 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
5168 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
5172 g_assert (error != NULL);
5173 g_simple_async_result_set_from_error (simple, error);
5174 g_error_free (error);
5175 g_object_unref (source_object);
5179 g_simple_async_result_set_op_res_gpointer (simple,
5183 g_simple_async_result_complete_in_idle (simple);
5184 g_object_unref (simple);
5189 * @bus_type: A #GBusType.
5190 * @cancellable: A #GCancellable or %NULL.
5191 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
5192 * @user_data: The data to pass to @callback.
5194 * Asynchronously connects to the message bus specified by @bus_type.
5196 * When the operation is finished, @callback will be invoked. You can
5197 * then call g_bus_get_finish() to get the result of the operation.
5199 * This is a asynchronous failable function. See g_bus_get_sync() for
5200 * the synchronous version.
5203 g_bus_get (GBusType bus_type,
5204 GCancellable *cancellable,
5205 GAsyncReadyCallback callback,
5208 GDBusConnection *connection;
5209 GSimpleAsyncResult *simple;
5212 simple = g_simple_async_result_new (NULL,
5218 connection = get_uninitialized_connection (bus_type, cancellable, &error);
5219 if (connection == NULL)
5221 g_assert (error != NULL);
5222 g_simple_async_result_set_from_error (simple, error);
5223 g_error_free (error);
5224 g_simple_async_result_complete_in_idle (simple);
5225 g_object_unref (simple);
5229 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
5232 bus_get_async_initable_cb,
5239 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
5240 * @error: Return location for error or %NULL.
5242 * Finishes an operation started with g_bus_get().
5244 * The returned object is a singleton, that is, shared with other
5245 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5246 * event that you need a private message bus connection, use
5247 * g_dbus_address_get_for_bus() and
5248 * g_dbus_connection_new_for_address().
5250 * Note that the returned #GDBusConnection object will (usually) have
5251 * the #GDBusConnection:exit-on-close property set to %TRUE.
5253 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5256 g_bus_get_finish (GAsyncResult *res,
5259 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
5261 GDBusConnection *ret;
5263 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5265 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
5269 if (g_simple_async_result_propagate_error (simple, error))
5272 object = g_simple_async_result_get_op_res_gpointer (simple);
5273 g_assert (object != NULL);
5274 ret = g_object_ref (G_DBUS_CONNECTION (object));
5280 /* ---------------------------------------------------------------------------------------------------- */