1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, write to the
17 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18 * Boston, MA 02111-1307, USA.
20 * Author: David Zeuthen <davidz@redhat.com>
26 * - would be nice to expose GDBusAuthMechanism and an extension point
28 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
29 * the mechanism VFuncs need to be able to set an error.
31 * - Need to document other mechanisms/sources for determining the D-Bus
32 * address of a well-known bus.
34 * - e.g. on Win32 we need code like from here
36 * http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
38 * that was never copied over here because it originally was copy-paste
39 * from the GPLv2 / AFL 2.1 libdbus sources.
41 * - on OS X we need to look in launchd for the address
43 * https://bugs.freedesktop.org/show_bug.cgi?id=14259
45 * - on X11 we need to look in a X11 property on the X server
46 * - (we can also just use dbus-launch(1) from the D-Bus
49 * - (ideally) this requires D-Bus spec work because none of
50 * this has never really been specced out properly (excect
53 * - Related to the above, we also need to be able to launch a message bus
54 * instance.... Since we don't want to write our own bus daemon we should
55 * launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
57 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
58 * to specify where the nonce is stored. This will allow people to use
59 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
60 * to easily acheive secure RPC via nonce-tcp.
62 * - need to expose an extension point for resolving D-Bus address and
63 * turning them into GIOStream objects. This will allow us to implement
64 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
66 * - see g_dbus_address_connect() in gdbusaddress.c
68 * - would be cute to use kernel-specific APIs to resolve fds for
69 * debug output when using G_DBUS_DEBUG=message, e.g. in addition to
71 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
73 * maybe we can show more information about what fd 21 really is.
74 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
75 * Initial experiments on Linux 2.6 suggests that the symlink looks
80 * e.g. not of much use.
82 * - GDBus High-Level docs
83 * - Proxy: properties, signals...
84 * - Connection: IOStream based, ::close, connection setup steps
85 * mainloop integration, threading
86 * - Differences from libdbus (extend "Migrating from")
87 * - the message handling thread
88 * - Using GVariant instead of GValue
89 * - Explain why the high-level API is a good thing and what
90 * kind of pitfalls it avoids
91 * - Export objects before claiming names
92 * - Talk about auto-starting services (cf. GBusNameWatcherFlags)
99 #include <sys/types.h>
104 #include "gdbusauth.h"
105 #include "gdbusutils.h"
106 #include "gdbusaddress.h"
107 #include "gdbusmessage.h"
108 #include "gdbusconnection.h"
109 #include "gdbuserror.h"
110 #include "gioenumtypes.h"
111 #include "gdbusintrospection.h"
112 #include "gdbusmethodinvocation.h"
113 #include "gdbusprivate.h"
114 #include "gdbusauthobserver.h"
115 #include "gio-marshal.h"
116 #include "ginitable.h"
117 #include "gasyncinitable.h"
118 #include "giostream.h"
119 #include "gasyncresult.h"
120 #include "gsimpleasyncresult.h"
123 #include "gunixconnection.h"
124 #include "gunixfdmessage.h"
127 #include "glibintl.h"
130 * SECTION:gdbusconnection
131 * @short_description: D-Bus Connections
132 * @include: gio/gio.h
134 * The #GDBusConnection type is used for D-Bus connections to remote
135 * peers such as a message buses. It is a low-level API that offers a
136 * lot of flexibility. For instance, it lets you establish a connection
137 * over any transport that can by represented as an #GIOStream.
139 * This class is rarely used directly in D-Bus clients. If you are writing
140 * an D-Bus client, it is often easier to use the g_bus_own_name(),
141 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
143 * <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>
145 * <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>
147 * <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>
149 * <example id="gdbus-export"><title>Exporting a GObject</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-export.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
152 /* ---------------------------------------------------------------------------------------------------- */
154 typedef struct _GDBusConnectionClass GDBusConnectionClass;
157 * GDBusConnectionClass:
158 * @closed: Signal class handler for the #GDBusConnection::closed signal.
160 * Class structure for #GDBusConnection.
164 struct _GDBusConnectionClass
167 GObjectClass parent_class;
171 void (*closed) (GDBusConnection *connection,
172 gboolean remote_peer_vanished,
176 G_LOCK_DEFINE_STATIC (message_bus_lock);
178 static GDBusConnection *the_session_bus = NULL;
179 static GDBusConnection *the_system_bus = NULL;
181 /* ---------------------------------------------------------------------------------------------------- */
184 _g_strv_has_string (const gchar* const *haystack,
189 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
191 if (g_strcmp0 (haystack[n], needle) == 0)
197 /* ---------------------------------------------------------------------------------------------------- */
200 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
202 // TODO: for some reason this doesn't work on Windows
203 #define CONNECTION_ENSURE_LOCK(obj) do { \
204 if (G_UNLIKELY (g_mutex_trylock((obj)->lock))) \
206 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
207 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
212 #define CONNECTION_LOCK(obj) do { \
213 g_mutex_lock ((obj)->lock); \
216 #define CONNECTION_UNLOCK(obj) do { \
217 g_mutex_unlock ((obj)->lock); \
223 * The #GDBusConnection structure contains only private data and
224 * should only be accessed using the provided API.
228 struct _GDBusConnection
231 GObject parent_instance;
233 /* ------------------------------------------------------------------------ */
234 /* -- General object state ------------------------------------------------ */
235 /* ------------------------------------------------------------------------ */
237 /* object-wide lock */
240 /* A lock used in the init() method of the GInitable interface - see comments
241 * in initable_init() for why a separate lock is needed
245 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
246 * someone calls org.freedesktop.DBus.GetMachineId()
250 /* The underlying stream used for communication */
253 /* The object used for authentication (if any) */
256 /* Set to TRUE if the connection has been closed */
259 /* Last serial used */
262 /* The object used to send/receive message */
265 /* If connected to a message bus, this contains the unique name assigned to
266 * us by the bus (e.g. ":1.42")
268 gchar *bus_unique_name;
270 /* The GUID returned by the other side if we authenticed as a client or
271 * the GUID to use if authenticating as a server
275 /* set to TRUE exactly when initable_init() has finished running */
276 gboolean is_initialized;
278 /* If the connection could not be established during initable_init(), this GError will set */
279 GError *initialization_error;
281 /* The result of g_main_context_get_thread_default() when the object
282 * was created (the GObject _init() function) - this is used for delivery
283 * of the :closed GObject signal.
285 GMainContext *main_context_at_construction;
287 /* construct properties */
289 GDBusConnectionFlags flags;
291 /* Map used for managing method replies */
292 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
294 /* Maps used for managing signal subscription */
295 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
296 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
297 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
299 /* Maps used for managing exported objects and subtrees */
300 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
301 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
302 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
303 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
305 /* Structure used for message filters */
308 /* Whether to exit on close */
309 gboolean exit_on_close;
311 /* Capabilities negotiated during authentication */
312 GDBusCapabilityFlags capabilities;
314 GDBusAuthObserver *authentication_observer;
315 GCredentials *credentials;
317 /* set to TRUE when finalizing */
321 typedef struct ExportedObject ExportedObject;
322 static void exported_object_free (ExportedObject *eo);
324 typedef struct ExportedSubtree ExportedSubtree;
325 static void exported_subtree_free (ExportedSubtree *es);
343 PROP_CAPABILITY_FLAGS,
344 PROP_AUTHENTICATION_OBSERVER,
347 static void distribute_signals (GDBusConnection *connection,
348 GDBusMessage *message);
350 static void distribute_method_call (GDBusConnection *connection,
351 GDBusMessage *message);
353 static gboolean handle_generic_unlocked (GDBusConnection *connection,
354 GDBusMessage *message);
357 static void purge_all_signal_subscriptions (GDBusConnection *connection);
358 static void purge_all_filters (GDBusConnection *connection);
360 #define _G_ENSURE_LOCK(name) do { \
361 if (G_UNLIKELY (G_TRYLOCK(name))) \
363 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
364 "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
368 static guint signals[LAST_SIGNAL] = { 0 };
370 static void initable_iface_init (GInitableIface *initable_iface);
371 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
373 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
374 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
375 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
378 static GHashTable *alive_connections = NULL;
381 g_dbus_connection_dispose (GObject *object)
383 GDBusConnection *connection = G_DBUS_CONNECTION (object);
385 G_LOCK (message_bus_lock);
386 if (connection == the_session_bus)
388 the_session_bus = NULL;
390 else if (connection == the_system_bus)
392 the_system_bus = NULL;
394 CONNECTION_LOCK (connection);
395 if (connection->worker != NULL)
397 _g_dbus_worker_stop (connection->worker);
398 connection->worker = NULL;
399 if (alive_connections != NULL)
400 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
404 if (alive_connections != NULL)
405 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
407 CONNECTION_UNLOCK (connection);
408 G_UNLOCK (message_bus_lock);
410 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
411 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
415 g_dbus_connection_finalize (GObject *object)
417 GDBusConnection *connection = G_DBUS_CONNECTION (object);
419 connection->finalizing = TRUE;
421 purge_all_signal_subscriptions (connection);
423 purge_all_filters (connection);
424 g_ptr_array_unref (connection->filters);
426 if (connection->authentication_observer != NULL)
427 g_object_unref (connection->authentication_observer);
429 if (connection->auth != NULL)
430 g_object_unref (connection->auth);
432 if (connection->credentials)
433 g_object_unref (connection->credentials);
435 if (connection->stream != NULL)
437 /* We don't really care if closing the stream succeeds or not */
438 g_io_stream_close_async (connection->stream,
440 NULL, /* GCancellable */
441 NULL, /* GAsyncReadyCallback */
442 NULL); /* userdata */
443 g_object_unref (connection->stream);
444 connection->stream = NULL;
447 g_free (connection->address);
449 g_free (connection->guid);
450 g_free (connection->bus_unique_name);
452 if (connection->initialization_error != NULL)
453 g_error_free (connection->initialization_error);
455 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
457 g_hash_table_unref (connection->map_rule_to_signal_data);
458 g_hash_table_unref (connection->map_id_to_signal_data);
459 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
461 g_hash_table_unref (connection->map_id_to_ei);
462 g_hash_table_unref (connection->map_object_path_to_eo);
463 g_hash_table_unref (connection->map_id_to_es);
464 g_hash_table_unref (connection->map_object_path_to_es);
466 if (connection->main_context_at_construction != NULL)
467 g_main_context_unref (connection->main_context_at_construction);
469 g_free (connection->machine_id);
471 g_mutex_free (connection->init_lock);
472 g_mutex_free (connection->lock);
474 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
478 g_dbus_connection_get_property (GObject *object,
483 GDBusConnection *connection = G_DBUS_CONNECTION (object);
488 g_value_set_object (value, g_dbus_connection_get_stream (connection));
492 g_value_set_string (value, g_dbus_connection_get_guid (connection));
495 case PROP_UNIQUE_NAME:
496 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
500 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
503 case PROP_EXIT_ON_CLOSE:
504 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
507 case PROP_CAPABILITY_FLAGS:
508 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
512 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
518 g_dbus_connection_set_property (GObject *object,
523 GDBusConnection *connection = G_DBUS_CONNECTION (object);
528 connection->stream = g_value_dup_object (value);
532 connection->guid = g_value_dup_string (value);
536 connection->address = g_value_dup_string (value);
540 connection->flags = g_value_get_flags (value);
543 case PROP_EXIT_ON_CLOSE:
544 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
547 case PROP_AUTHENTICATION_OBSERVER:
548 connection->authentication_observer = g_value_dup_object (value);
552 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
558 g_dbus_connection_real_closed (GDBusConnection *connection,
559 gboolean remote_peer_vanished,
562 if (remote_peer_vanished && connection->exit_on_close)
566 g_print ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
569 g_quark_to_string (error->domain), error->code);
573 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
580 g_dbus_connection_class_init (GDBusConnectionClass *klass)
582 GObjectClass *gobject_class;
584 gobject_class = G_OBJECT_CLASS (klass);
586 gobject_class->finalize = g_dbus_connection_finalize;
587 gobject_class->dispose = g_dbus_connection_dispose;
588 gobject_class->set_property = g_dbus_connection_set_property;
589 gobject_class->get_property = g_dbus_connection_get_property;
591 klass->closed = g_dbus_connection_real_closed;
594 * GDBusConnection:stream:
596 * The underlying #GIOStream used for I/O.
600 g_object_class_install_property (gobject_class,
602 g_param_spec_object ("stream",
604 P_("The underlying streams used for I/O"),
608 G_PARAM_CONSTRUCT_ONLY |
609 G_PARAM_STATIC_NAME |
610 G_PARAM_STATIC_BLURB |
611 G_PARAM_STATIC_NICK));
614 * GDBusConnection:address:
616 * A D-Bus address specifying potential endpoints that can be used
617 * when establishing the connection.
621 g_object_class_install_property (gobject_class,
623 g_param_spec_string ("address",
625 P_("D-Bus address specifying potential socket endpoints"),
628 G_PARAM_CONSTRUCT_ONLY |
629 G_PARAM_STATIC_NAME |
630 G_PARAM_STATIC_BLURB |
631 G_PARAM_STATIC_NICK));
634 * GDBusConnection:flags:
636 * Flags from the #GDBusConnectionFlags enumeration.
640 g_object_class_install_property (gobject_class,
642 g_param_spec_flags ("flags",
645 G_TYPE_DBUS_CONNECTION_FLAGS,
646 G_DBUS_CONNECTION_FLAGS_NONE,
648 G_PARAM_CONSTRUCT_ONLY |
649 G_PARAM_STATIC_NAME |
650 G_PARAM_STATIC_BLURB |
651 G_PARAM_STATIC_NICK));
654 * GDBusConnection:guid:
656 * The GUID of the peer performing the role of server when
659 * If you are constructing a #GDBusConnection and pass
660 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
661 * #GDBusConnection:flags property then you MUST also set this
662 * property to a valid guid.
664 * If you are constructing a #GDBusConnection and pass
665 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
666 * #GDBusConnection:flags property you will be able to read the GUID
667 * of the other peer here after the connection has been successfully
672 g_object_class_install_property (gobject_class,
674 g_param_spec_string ("guid",
676 P_("GUID of the server peer"),
680 G_PARAM_CONSTRUCT_ONLY |
681 G_PARAM_STATIC_NAME |
682 G_PARAM_STATIC_BLURB |
683 G_PARAM_STATIC_NICK));
686 * GDBusConnection:unique-name:
688 * The unique name as assigned by the message bus or %NULL if the
689 * connection is not open or not a message bus connection.
693 g_object_class_install_property (gobject_class,
695 g_param_spec_string ("unique-name",
697 P_("Unique name of bus connection"),
700 G_PARAM_STATIC_NAME |
701 G_PARAM_STATIC_BLURB |
702 G_PARAM_STATIC_NICK));
705 * GDBusConnection:closed:
707 * A boolean specifying whether the connection has been closed.
711 g_object_class_install_property (gobject_class,
713 g_param_spec_boolean ("closed",
715 P_("Whether the connection is closed"),
718 G_PARAM_STATIC_NAME |
719 G_PARAM_STATIC_BLURB |
720 G_PARAM_STATIC_NICK));
723 * GDBusConnection:exit-on-close:
725 * A boolean specifying whether the process will be terminated (by
726 * calling <literal>raise(SIGTERM)</literal>) if the connection
727 * is closed by the remote peer.
731 g_object_class_install_property (gobject_class,
733 g_param_spec_boolean ("exit-on-close",
735 P_("Whether the process is terminated when the connection is closed"),
739 G_PARAM_STATIC_NAME |
740 G_PARAM_STATIC_BLURB |
741 G_PARAM_STATIC_NICK));
744 * GDBusConnection:capabilities:
746 * Flags from the #GDBusCapabilityFlags enumeration
747 * representing connection features negotiated with the other peer.
751 g_object_class_install_property (gobject_class,
752 PROP_CAPABILITY_FLAGS,
753 g_param_spec_flags ("capabilities",
756 G_TYPE_DBUS_CAPABILITY_FLAGS,
757 G_DBUS_CAPABILITY_FLAGS_NONE,
759 G_PARAM_STATIC_NAME |
760 G_PARAM_STATIC_BLURB |
761 G_PARAM_STATIC_NICK));
764 * GDBusConnection:authentication-observer:
766 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
770 g_object_class_install_property (gobject_class,
771 PROP_AUTHENTICATION_OBSERVER,
772 g_param_spec_object ("authentication-observer",
773 P_("Authentication Observer"),
774 P_("Object used to assist in the authentication process"),
775 G_TYPE_DBUS_AUTH_OBSERVER,
777 G_PARAM_CONSTRUCT_ONLY |
778 G_PARAM_STATIC_NAME |
779 G_PARAM_STATIC_BLURB |
780 G_PARAM_STATIC_NICK));
783 * GDBusConnection::closed:
784 * @connection: The #GDBusConnection emitting the signal.
785 * @remote_peer_vanished: %TRUE if @connection is closed because the
786 * remote peer closed its end of the connection.
787 * @error: A #GError with more details about the event or %NULL.
789 * Emitted when the connection is closed.
791 * The cause of this event can be
794 * If g_dbus_connection_close() is called. In this case
795 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
798 * If the remote peer closes the connection. In this case
799 * @remote_peer_vanished is set to %TRUE and @error is set.
802 * If the remote peer sends invalid or malformed data. In this
803 * case @remote_peer_vanished is set to %FALSE and @error
808 * Upon receiving this signal, you should give up your reference to
809 * @connection. You are guaranteed that this signal is emitted only
814 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
815 G_TYPE_DBUS_CONNECTION,
817 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
820 _gio_marshal_VOID__BOOLEAN_BOXED,
828 g_dbus_connection_init (GDBusConnection *connection)
830 connection->lock = g_mutex_new ();
831 connection->init_lock = g_mutex_new ();
833 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
835 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
837 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
839 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
842 (GDestroyNotify) g_ptr_array_unref);
844 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
847 (GDestroyNotify) exported_object_free);
849 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
852 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
855 (GDestroyNotify) exported_subtree_free);
857 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
860 connection->main_context_at_construction = g_main_context_get_thread_default ();
861 if (connection->main_context_at_construction != NULL)
862 g_main_context_ref (connection->main_context_at_construction);
864 connection->filters = g_ptr_array_new ();
868 * g_dbus_connection_get_stream:
869 * @connection: a #GDBusConnection
871 * Gets the underlying stream used for IO.
873 * Returns: the stream used for IO
878 g_dbus_connection_get_stream (GDBusConnection *connection)
880 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
881 return connection->stream;
885 * g_dbus_connection_start_message_processing:
886 * @connection: A #GDBusConnection.
888 * If @connection was created with
889 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
890 * starts processing messages. Does nothing on if @connection wasn't
891 * created with this flag or if the method has already been called.
896 g_dbus_connection_start_message_processing (GDBusConnection *connection)
898 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
899 _g_dbus_worker_unfreeze (connection->worker);
903 * g_dbus_connection_is_closed:
904 * @connection: A #GDBusConnection.
906 * Gets whether @connection is closed.
908 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
913 g_dbus_connection_is_closed (GDBusConnection *connection)
915 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
916 return connection->closed;
920 * g_dbus_connection_get_capabilities:
921 * @connection: A #GDBusConnection.
923 * Gets the capabilities negotiated with the remote peer
925 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
930 g_dbus_connection_get_capabilities (GDBusConnection *connection)
932 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
933 return connection->capabilities;
936 /* ---------------------------------------------------------------------------------------------------- */
939 flush_in_thread_func (GSimpleAsyncResult *res,
941 GCancellable *cancellable)
946 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
950 g_simple_async_result_set_from_error (res, error);
951 g_error_free (error);
956 * g_dbus_connection_flush:
957 * @connection: A #GDBusConnection.
958 * @cancellable: A #GCancellable or %NULL.
959 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
960 * care about the result.
961 * @user_data: The data to pass to @callback.
963 * Asynchronously flushes @connection, that is, writes all queued
964 * outgoing message to the transport and then flushes the transport
965 * (using g_output_stream_flush_async()). This is useful in programs
966 * that wants to emit a D-Bus signal and then exit
967 * immediately. Without flushing the connection, there is no guarantee
968 * that the message has been sent to the networking buffers in the OS
971 * This is an asynchronous method. When the operation is finished,
972 * @callback will be invoked in the <link
973 * linkend="g-main-context-push-thread-default">thread-default main
974 * loop</link> of the thread you are calling this method from. You can
975 * then call g_dbus_connection_flush_finish() to get the result of the
976 * operation. See g_dbus_connection_flush_sync() for the synchronous
982 g_dbus_connection_flush (GDBusConnection *connection,
983 GCancellable *cancellable,
984 GAsyncReadyCallback callback,
987 GSimpleAsyncResult *simple;
989 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
991 simple = g_simple_async_result_new (G_OBJECT (connection),
994 g_dbus_connection_flush);
995 g_simple_async_result_run_in_thread (simple,
996 flush_in_thread_func,
999 g_object_unref (simple);
1003 * g_dbus_connection_flush_finish:
1004 * @connection: A #GDBusConnection.
1005 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_flush().
1006 * @error: Return location for error or %NULL.
1008 * Finishes an operation started with g_dbus_connection_flush().
1010 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1015 g_dbus_connection_flush_finish (GDBusConnection *connection,
1019 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1024 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1025 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1026 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1028 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1030 if (g_simple_async_result_propagate_error (simple, error))
1040 * g_dbus_connection_flush_sync:
1041 * @connection: A #GDBusConnection.
1042 * @cancellable: A #GCancellable or %NULL.
1043 * @error: Return location for error or %NULL.
1045 * Synchronously flushes @connection. The calling thread is blocked
1046 * until this is done. See g_dbus_connection_flush() for the
1047 * asynchronous version of this method and more details about what it
1050 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1055 g_dbus_connection_flush_sync (GDBusConnection *connection,
1056 GCancellable *cancellable,
1061 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1062 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1066 if (connection->closed)
1068 g_set_error_literal (error,
1071 _("The connection is closed"));
1075 ret = _g_dbus_worker_flush_sync (connection->worker,
1083 /* ---------------------------------------------------------------------------------------------------- */
1087 GDBusConnection *connection;
1089 gboolean remote_peer_vanished;
1093 emit_closed_data_free (EmitClosedData *data)
1095 g_object_unref (data->connection);
1096 if (data->error != NULL)
1097 g_error_free (data->error);
1102 emit_closed_in_idle (gpointer user_data)
1104 EmitClosedData *data = user_data;
1107 g_object_notify (G_OBJECT (data->connection), "closed");
1108 g_signal_emit (data->connection,
1109 signals[CLOSED_SIGNAL],
1111 data->remote_peer_vanished,
1117 /* Can be called from any thread, must hold lock */
1119 set_closed_unlocked (GDBusConnection *connection,
1120 gboolean remote_peer_vanished,
1123 GSource *idle_source;
1124 EmitClosedData *data;
1126 CONNECTION_ENSURE_LOCK (connection);
1128 g_assert (!connection->closed);
1130 connection->closed = TRUE;
1132 data = g_new0 (EmitClosedData, 1);
1133 data->connection = g_object_ref (connection);
1134 data->remote_peer_vanished = remote_peer_vanished;
1135 data->error = error != NULL ? g_error_copy (error) : NULL;
1137 idle_source = g_idle_source_new ();
1138 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1139 g_source_set_callback (idle_source,
1140 emit_closed_in_idle,
1142 (GDestroyNotify) emit_closed_data_free);
1143 g_source_attach (idle_source, connection->main_context_at_construction);
1144 g_source_unref (idle_source);
1147 /* ---------------------------------------------------------------------------------------------------- */
1150 close_in_thread_func (GSimpleAsyncResult *res,
1152 GCancellable *cancellable)
1157 if (!g_dbus_connection_close_sync (G_DBUS_CONNECTION (object),
1161 g_simple_async_result_set_from_error (res, error);
1162 g_error_free (error);
1167 * g_dbus_connection_close:
1168 * @connection: A #GDBusConnection.
1169 * @cancellable: A #GCancellable or %NULL.
1170 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1171 * care about the result.
1172 * @user_data: The data to pass to @callback.
1174 * Closes @connection. Note that this never causes the process to
1175 * exit (this might only happen if the other end of a shared message
1176 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1178 * Once the connection is closed, operations such as sending a message
1179 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1180 * will not automatically flush the connection so queued messages may
1181 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1183 * If @connection is already closed, this method fails with
1184 * %G_IO_ERROR_CLOSED.
1186 * When @connection has been closed, the #GDBusConnection::closed
1187 * signal is emitted in the <link
1188 * linkend="g-main-context-push-thread-default">thread-default main
1189 * loop</link> of the thread that @connection was constructed in.
1191 * This is an asynchronous method. When the operation is finished,
1192 * @callback will be invoked in the <link
1193 * linkend="g-main-context-push-thread-default">thread-default main
1194 * loop</link> of the thread you are calling this method from. You can
1195 * then call g_dbus_connection_close_finish() to get the result of the
1196 * operation. See g_dbus_connection_close_sync() for the synchronous
1202 g_dbus_connection_close (GDBusConnection *connection,
1203 GCancellable *cancellable,
1204 GAsyncReadyCallback callback,
1207 GSimpleAsyncResult *simple;
1209 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1211 simple = g_simple_async_result_new (G_OBJECT (connection),
1214 g_dbus_connection_close);
1215 g_simple_async_result_run_in_thread (simple,
1216 close_in_thread_func,
1219 g_object_unref (simple);
1223 * g_dbus_connection_close_finish:
1224 * @connection: A #GDBusConnection.
1225 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_close().
1226 * @error: Return location for error or %NULL.
1228 * Finishes an operation started with g_dbus_connection_close().
1230 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1235 g_dbus_connection_close_finish (GDBusConnection *connection,
1239 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1244 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1245 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1246 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1248 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1250 if (g_simple_async_result_propagate_error (simple, error))
1260 * g_dbus_connection_close_sync:
1261 * @connection: A #GDBusConnection.
1262 * @cancellable: A #GCancellable or %NULL.
1263 * @error: Return location for error or %NULL.
1265 * Synchronously closees @connection. The calling thread is blocked
1266 * until this is done. See g_dbus_connection_close() for the
1267 * asynchronous version of this method and more details about what it
1270 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1275 g_dbus_connection_close_sync (GDBusConnection *connection,
1276 GCancellable *cancellable,
1281 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1282 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1286 CONNECTION_LOCK (connection);
1287 if (!connection->closed)
1289 ret = g_io_stream_close (connection->stream,
1293 set_closed_unlocked (connection, FALSE, NULL);
1297 g_set_error_literal (error,
1300 _("The connection is closed"));
1302 CONNECTION_UNLOCK (connection);
1307 /* ---------------------------------------------------------------------------------------------------- */
1310 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1311 GDBusMessage *message,
1312 GDBusSendMessageFlags flags,
1313 volatile guint32 *out_serial,
1318 guint32 serial_to_use;
1321 CONNECTION_ENSURE_LOCK (connection);
1323 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1324 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1326 /* TODO: check all necessary headers are present */
1331 if (out_serial != NULL)
1334 if (connection->closed)
1336 g_set_error_literal (error,
1339 _("The connection is closed"));
1343 blob = g_dbus_message_to_blob (message,
1345 connection->capabilities,
1350 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1351 serial_to_use = g_dbus_message_get_serial (message);
1353 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1358 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1361 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1364 g_assert_not_reached ();
1369 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1370 blob_size, serial_to_use, connection);
1371 g_printerr ("----\n");
1372 hexdump (blob, blob_size);
1373 g_printerr ("----\n");
1376 /* TODO: use connection->auth to encode the blob */
1378 if (out_serial != NULL)
1379 *out_serial = serial_to_use;
1381 g_dbus_message_set_serial (message, serial_to_use);
1383 g_dbus_message_lock (message);
1384 _g_dbus_worker_send_message (connection->worker,
1388 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1399 * g_dbus_connection_send_message:
1400 * @connection: A #GDBusConnection.
1401 * @message: A #GDBusMessage
1402 * @flags: Flags affecting how the message is sent.
1403 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1404 * @error: Return location for error or %NULL.
1406 * Asynchronously sends @message to the peer represented by @connection.
1408 * Unless @flags contain the
1409 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1410 * will be assigned by @connection and set on @message via
1411 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1412 * serial number used will be written to this location prior to
1413 * submitting the message to the underlying transport.
1415 * If @connection is closed then the operation will fail with
1416 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1417 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1419 * See <xref linkend="gdbus-server"/> and <xref
1420 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1421 * low-level API to send and receive UNIX file descriptors.
1423 * Note that @message must be unlocked, unless @flags contain the
1424 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1426 * Returns: %TRUE if the message was well-formed and queued for
1427 * transmission, %FALSE if @error is set.
1432 g_dbus_connection_send_message (GDBusConnection *connection,
1433 GDBusMessage *message,
1434 GDBusSendMessageFlags flags,
1435 volatile guint32 *out_serial,
1440 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1441 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1442 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1443 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1445 CONNECTION_LOCK (connection);
1446 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1447 CONNECTION_UNLOCK (connection);
1451 /* ---------------------------------------------------------------------------------------------------- */
1455 volatile gint ref_count;
1456 GDBusConnection *connection;
1458 GSimpleAsyncResult *simple;
1460 GMainContext *main_context;
1462 GCancellable *cancellable;
1464 gulong cancellable_handler_id;
1466 GSource *timeout_source;
1471 static SendMessageData *
1472 send_message_data_ref (SendMessageData *data)
1474 g_atomic_int_inc (&data->ref_count);
1479 send_message_data_unref (SendMessageData *data)
1481 if (g_atomic_int_dec_and_test (&data->ref_count))
1483 g_assert (data->timeout_source == NULL);
1484 g_assert (data->simple == NULL);
1485 g_assert (data->cancellable_handler_id == 0);
1486 g_object_unref (data->connection);
1487 if (data->cancellable != NULL)
1488 g_object_unref (data->cancellable);
1489 if (data->main_context != NULL)
1490 g_main_context_unref (data->main_context);
1495 /* ---------------------------------------------------------------------------------------------------- */
1497 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1499 send_message_with_reply_deliver (SendMessageData *data)
1501 CONNECTION_ENSURE_LOCK (data->connection);
1503 g_assert (!data->delivered);
1505 data->delivered = TRUE;
1507 g_simple_async_result_complete_in_idle (data->simple);
1508 g_object_unref (data->simple);
1509 data->simple = NULL;
1511 if (data->timeout_source != NULL)
1513 g_source_destroy (data->timeout_source);
1514 data->timeout_source = NULL;
1516 if (data->cancellable_handler_id > 0)
1518 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1519 data->cancellable_handler_id = 0;
1522 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
1523 GUINT_TO_POINTER (data->serial)));
1525 send_message_data_unref (data);
1528 /* ---------------------------------------------------------------------------------------------------- */
1530 /* must hold lock */
1532 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1533 GDBusMessage *reply)
1535 if (data->delivered)
1538 g_simple_async_result_set_op_res_gpointer (data->simple,
1539 g_object_ref (reply),
1542 send_message_with_reply_deliver (data);
1548 /* ---------------------------------------------------------------------------------------------------- */
1551 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1553 SendMessageData *data = user_data;
1555 CONNECTION_LOCK (data->connection);
1556 if (data->delivered)
1559 g_simple_async_result_set_error (data->simple,
1561 G_IO_ERROR_CANCELLED,
1562 _("Operation was cancelled"));
1564 send_message_with_reply_deliver (data);
1567 CONNECTION_UNLOCK (data->connection);
1571 /* Can be called from any thread with or without lock held */
1573 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1576 SendMessageData *data = user_data;
1577 GSource *idle_source;
1579 /* postpone cancellation to idle handler since we may be called directly
1580 * via g_cancellable_connect() (e.g. holding lock)
1582 idle_source = g_idle_source_new ();
1583 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1584 g_source_set_callback (idle_source,
1585 send_message_with_reply_cancelled_idle_cb,
1586 send_message_data_ref (data),
1587 (GDestroyNotify) send_message_data_unref);
1588 g_source_attach (idle_source, data->main_context);
1589 g_source_unref (idle_source);
1592 /* ---------------------------------------------------------------------------------------------------- */
1595 send_message_with_reply_timeout_cb (gpointer user_data)
1597 SendMessageData *data = user_data;
1599 CONNECTION_LOCK (data->connection);
1600 if (data->delivered)
1603 g_simple_async_result_set_error (data->simple,
1605 G_IO_ERROR_TIMED_OUT,
1606 _("Timeout was reached"));
1608 send_message_with_reply_deliver (data);
1611 CONNECTION_UNLOCK (data->connection);
1616 /* ---------------------------------------------------------------------------------------------------- */
1619 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1620 GDBusMessage *message,
1621 GDBusSendMessageFlags flags,
1623 volatile guint32 *out_serial,
1624 GCancellable *cancellable,
1625 GAsyncReadyCallback callback,
1628 GSimpleAsyncResult *simple;
1629 SendMessageData *data;
1631 volatile guint32 serial;
1635 if (out_serial == NULL)
1636 out_serial = &serial;
1638 if (timeout_msec == -1)
1639 timeout_msec = 25 * 1000;
1641 simple = g_simple_async_result_new (G_OBJECT (connection),
1644 g_dbus_connection_send_message_with_reply);
1646 if (g_cancellable_is_cancelled (cancellable))
1648 g_simple_async_result_set_error (simple,
1650 G_IO_ERROR_CANCELLED,
1651 _("Operation was cancelled"));
1652 g_simple_async_result_complete_in_idle (simple);
1653 g_object_unref (simple);
1657 if (connection->closed)
1659 g_simple_async_result_set_error (simple,
1662 _("The connection is closed"));
1663 g_simple_async_result_complete_in_idle (simple);
1664 g_object_unref (simple);
1669 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1671 g_simple_async_result_set_from_error (simple, error);
1672 g_simple_async_result_complete_in_idle (simple);
1673 g_object_unref (simple);
1677 data = g_new0 (SendMessageData, 1);
1678 data->ref_count = 1;
1679 data->connection = g_object_ref (connection);
1680 data->simple = simple;
1681 data->serial = *out_serial;
1682 data->main_context = g_main_context_get_thread_default ();
1683 if (data->main_context != NULL)
1684 g_main_context_ref (data->main_context);
1686 if (cancellable != NULL)
1688 data->cancellable = g_object_ref (cancellable);
1689 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1690 G_CALLBACK (send_message_with_reply_cancelled_cb),
1691 send_message_data_ref (data),
1692 (GDestroyNotify) send_message_data_unref);
1693 g_object_set_data_full (G_OBJECT (simple),
1695 g_object_ref (cancellable),
1696 (GDestroyNotify) g_object_unref);
1699 data->timeout_source = g_timeout_source_new (timeout_msec);
1700 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1701 g_source_set_callback (data->timeout_source,
1702 send_message_with_reply_timeout_cb,
1703 send_message_data_ref (data),
1704 (GDestroyNotify) send_message_data_unref);
1705 g_source_attach (data->timeout_source, data->main_context);
1706 g_source_unref (data->timeout_source);
1708 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
1709 GUINT_TO_POINTER (*out_serial),
1717 * g_dbus_connection_send_message_with_reply:
1718 * @connection: A #GDBusConnection.
1719 * @message: A #GDBusMessage.
1720 * @flags: Flags affecting how the message is sent.
1721 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1722 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1723 * @cancellable: A #GCancellable or %NULL.
1724 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1725 * care about the result.
1726 * @user_data: The data to pass to @callback.
1728 * Asynchronously sends @message to the peer represented by @connection.
1730 * Unless @flags contain the
1731 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1732 * will be assigned by @connection and set on @message via
1733 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1734 * serial number used will be written to this location prior to
1735 * submitting the message to the underlying transport.
1737 * If @connection is closed then the operation will fail with
1738 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1739 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1740 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1742 * This is an asynchronous method. When the operation is finished, @callback will be invoked
1743 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
1744 * of the thread you are calling this method from. You can then call
1745 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1746 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
1748 * Note that @message must be unlocked, unless @flags contain the
1749 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1751 * See <xref linkend="gdbus-server"/> and <xref
1752 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1753 * low-level API to send and receive UNIX file descriptors.
1758 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
1759 GDBusMessage *message,
1760 GDBusSendMessageFlags flags,
1762 volatile guint32 *out_serial,
1763 GCancellable *cancellable,
1764 GAsyncReadyCallback callback,
1767 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1768 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1769 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
1770 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
1772 CONNECTION_LOCK (connection);
1773 g_dbus_connection_send_message_with_reply_unlocked (connection,
1781 CONNECTION_UNLOCK (connection);
1785 * g_dbus_connection_send_message_with_reply_finish:
1786 * @connection: a #GDBusConnection
1787 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
1788 * @error: Return location for error or %NULL.
1790 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
1792 * Note that @error is only set if a local in-process error
1793 * occured. That is to say that the returned #GDBusMessage object may
1794 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1795 * g_dbus_message_to_gerror() to transcode this to a #GError.
1797 * See <xref linkend="gdbus-server"/> and <xref
1798 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1799 * low-level API to send and receive UNIX file descriptors.
1801 * Returns: A locked #GDBusMessage or %NULL if @error is set.
1806 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
1810 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1811 GDBusMessage *reply;
1812 GCancellable *cancellable;
1814 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1815 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1819 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
1821 if (g_simple_async_result_propagate_error (simple, error))
1824 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
1825 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
1826 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
1828 g_object_unref (reply);
1830 g_set_error_literal (error,
1832 G_IO_ERROR_CANCELLED,
1833 _("Operation was cancelled"));
1839 /* ---------------------------------------------------------------------------------------------------- */
1844 GMainContext *context;
1846 } SendMessageSyncData;
1849 send_message_with_reply_sync_cb (GDBusConnection *connection,
1853 SendMessageSyncData *data = user_data;
1854 data->res = g_object_ref (res);
1855 g_main_loop_quit (data->loop);
1859 * g_dbus_connection_send_message_with_reply_sync:
1860 * @connection: A #GDBusConnection.
1861 * @message: A #GDBusMessage.
1862 * @flags: Flags affecting how the message is sent.
1863 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1864 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1865 * @cancellable: A #GCancellable or %NULL.
1866 * @error: Return location for error or %NULL.
1868 * Synchronously sends @message to the peer represented by @connection
1869 * and blocks the calling thread until a reply is received or the
1870 * timeout is reached. See g_dbus_connection_send_message_with_reply()
1871 * for the asynchronous version of this method.
1873 * Unless @flags contain the
1874 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1875 * will be assigned by @connection and set on @message via
1876 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1877 * serial number used will be written to this location prior to
1878 * submitting the message to the underlying transport.
1880 * If @connection is closed then the operation will fail with
1881 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1882 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1883 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1885 * Note that @error is only set if a local in-process error
1886 * occured. That is to say that the returned #GDBusMessage object may
1887 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1888 * g_dbus_message_to_gerror() to transcode this to a #GError.
1890 * See <xref linkend="gdbus-server"/> and <xref
1891 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1892 * low-level API to send and receive UNIX file descriptors.
1894 * Note that @message must be unlocked, unless @flags contain the
1895 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1897 * Returns: A locked #GDBusMessage that is the reply to @message or %NULL if @error is set.
1902 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
1903 GDBusMessage *message,
1904 GDBusSendMessageFlags flags,
1906 volatile guint32 *out_serial,
1907 GCancellable *cancellable,
1910 SendMessageSyncData *data;
1911 GDBusMessage *reply;
1913 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1914 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
1915 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1916 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1917 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1919 data = g_new0 (SendMessageSyncData, 1);
1920 data->context = g_main_context_new ();
1921 data->loop = g_main_loop_new (data->context, FALSE);
1923 g_main_context_push_thread_default (data->context);
1925 g_dbus_connection_send_message_with_reply (connection,
1931 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
1933 g_main_loop_run (data->loop);
1934 reply = g_dbus_connection_send_message_with_reply_finish (connection,
1938 g_main_context_pop_thread_default (data->context);
1940 g_main_context_unref (data->context);
1941 g_main_loop_unref (data->loop);
1942 g_object_unref (data->res);
1948 /* ---------------------------------------------------------------------------------------------------- */
1952 GDBusMessageFilterFunction func;
1959 GDBusMessageFilterFunction filter_function;
1961 GDestroyNotify user_data_free_func;
1964 /* Called in worker's thread - we must not block */
1966 on_worker_message_received (GDBusWorker *worker,
1967 GDBusMessage *message,
1970 GDBusConnection *connection;
1971 FilterCallback *filters;
1972 gboolean consumed_by_filter;
1973 gboolean altered_by_filter;
1978 G_LOCK (message_bus_lock);
1979 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
1982 G_UNLOCK (message_bus_lock);
1985 connection = G_DBUS_CONNECTION (user_data);
1986 g_object_ref (connection);
1987 G_UNLOCK (message_bus_lock);
1989 //g_debug ("in on_worker_message_received");
1991 g_object_ref (message);
1992 g_dbus_message_lock (message);
1994 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
1996 /* First collect the set of callback functions */
1997 CONNECTION_LOCK (connection);
1998 num_filters = connection->filters->len;
1999 filters = g_new0 (FilterCallback, num_filters);
2000 for (n = 0; n < num_filters; n++)
2002 FilterData *data = connection->filters->pdata[n];
2003 filters[n].func = data->filter_function;
2004 filters[n].user_data = data->user_data;
2006 CONNECTION_UNLOCK (connection);
2008 /* then call the filters in order (without holding the lock) */
2009 consumed_by_filter = FALSE;
2010 altered_by_filter = FALSE;
2011 for (n = 0; n < num_filters; n++)
2013 message = filters[n].func (connection,
2016 filters[n].user_data);
2017 if (message == NULL)
2019 g_dbus_message_lock (message);
2022 /* Standard dispatch unless the filter ate the message - no need to
2023 * do anything if the message was altered
2025 if (message != NULL)
2027 GDBusMessageType message_type;
2029 message_type = g_dbus_message_get_message_type (message);
2030 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2032 guint32 reply_serial;
2033 SendMessageData *send_message_data;
2035 reply_serial = g_dbus_message_get_reply_serial (message);
2036 CONNECTION_LOCK (connection);
2037 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2038 GUINT_TO_POINTER (reply_serial));
2039 if (send_message_data != NULL)
2041 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2042 send_message_data_deliver_reply_unlocked (send_message_data, message);
2046 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2048 CONNECTION_UNLOCK (connection);
2050 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2052 CONNECTION_LOCK (connection);
2053 distribute_signals (connection, message);
2054 CONNECTION_UNLOCK (connection);
2056 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2058 CONNECTION_LOCK (connection);
2059 distribute_method_call (connection, message);
2060 CONNECTION_UNLOCK (connection);
2064 if (message != NULL)
2065 g_object_unref (message);
2066 g_object_unref (connection);
2070 /* Called in worker's thread */
2071 static GDBusMessage *
2072 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2073 GDBusMessage *message,
2076 GDBusConnection *connection;
2077 FilterCallback *filters;
2082 G_LOCK (message_bus_lock);
2083 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2086 G_UNLOCK (message_bus_lock);
2089 connection = G_DBUS_CONNECTION (user_data);
2090 g_object_ref (connection);
2091 G_UNLOCK (message_bus_lock);
2093 //g_debug ("in on_worker_message_about_to_be_sent");
2095 /* First collect the set of callback functions */
2096 CONNECTION_LOCK (connection);
2097 num_filters = connection->filters->len;
2098 filters = g_new0 (FilterCallback, num_filters);
2099 for (n = 0; n < num_filters; n++)
2101 FilterData *data = connection->filters->pdata[n];
2102 filters[n].func = data->filter_function;
2103 filters[n].user_data = data->user_data;
2105 CONNECTION_UNLOCK (connection);
2107 /* then call the filters in order (without holding the lock) */
2108 for (n = 0; n < num_filters; n++)
2110 g_dbus_message_lock (message);
2111 message = filters[n].func (connection,
2114 filters[n].user_data);
2115 if (message == NULL)
2119 g_object_unref (connection);
2125 /* Called in worker's thread - we must not block */
2127 on_worker_closed (GDBusWorker *worker,
2128 gboolean remote_peer_vanished,
2132 GDBusConnection *connection;
2135 G_LOCK (message_bus_lock);
2136 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2139 G_UNLOCK (message_bus_lock);
2142 connection = G_DBUS_CONNECTION (user_data);
2143 g_object_ref (connection);
2144 G_UNLOCK (message_bus_lock);
2146 //g_debug ("in on_worker_closed: %s", error->message);
2148 CONNECTION_LOCK (connection);
2149 if (!connection->closed)
2150 set_closed_unlocked (connection, remote_peer_vanished, error);
2151 CONNECTION_UNLOCK (connection);
2153 g_object_unref (connection);
2156 /* ---------------------------------------------------------------------------------------------------- */
2158 /* Determines the biggest set of capabilities we can support on this connection */
2159 static GDBusCapabilityFlags
2160 get_offered_capabilities_max (GDBusConnection *connection)
2162 GDBusCapabilityFlags ret;
2163 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2165 if (G_IS_UNIX_CONNECTION (connection->stream))
2166 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2172 initable_init (GInitable *initable,
2173 GCancellable *cancellable,
2176 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2179 /* This method needs to be idempotent to work with the singleton
2180 * pattern. See the docs for g_initable_init(). We implement this by
2183 * Unfortunately we can't use the main lock since the on_worker_*()
2184 * callbacks above needs the lock during initialization (for message
2185 * bus connections we do a synchronous Hello() call on the bus).
2187 g_mutex_lock (connection->init_lock);
2191 if (connection->is_initialized)
2193 if (connection->stream != NULL)
2196 g_assert (connection->initialization_error != NULL);
2199 g_assert (connection->initialization_error == NULL);
2201 /* The user can pass multiple (but mutally exclusive) construct
2204 * - stream (of type GIOStream)
2205 * - address (of type gchar*)
2207 * At the end of the day we end up with a non-NULL GIOStream
2208 * object in connection->stream.
2210 if (connection->address != NULL)
2212 g_assert (connection->stream == NULL);
2214 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2215 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2217 g_set_error_literal (error,
2219 G_IO_ERROR_INVALID_ARGUMENT,
2220 _("Unsupported flags encountered when constructing a client-side connection"));
2224 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2225 NULL, /* TODO: out_guid */
2227 &connection->initialization_error);
2228 if (connection->stream == NULL)
2231 else if (connection->stream != NULL)
2237 g_assert_not_reached ();
2240 /* Authenticate the connection */
2241 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2243 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2244 g_assert (connection->guid != NULL);
2245 connection->auth = _g_dbus_auth_new (connection->stream);
2246 if (!_g_dbus_auth_run_server (connection->auth,
2247 connection->authentication_observer,
2249 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2250 get_offered_capabilities_max (connection),
2251 &connection->capabilities,
2252 &connection->credentials,
2254 &connection->initialization_error))
2257 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2259 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2260 g_assert (connection->guid == NULL);
2261 connection->auth = _g_dbus_auth_new (connection->stream);
2262 connection->guid = _g_dbus_auth_run_client (connection->auth,
2263 get_offered_capabilities_max (connection),
2264 &connection->capabilities,
2266 &connection->initialization_error);
2267 if (connection->guid == NULL)
2271 if (connection->authentication_observer != NULL)
2273 g_object_unref (connection->authentication_observer);
2274 connection->authentication_observer = NULL;
2277 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2279 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2284 * https://bugzilla.gnome.org/show_bug.cgi?id=616458
2288 if (G_IS_SOCKET_CONNECTION (connection->stream))
2290 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2294 G_LOCK (message_bus_lock);
2295 if (alive_connections == NULL)
2296 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2297 g_hash_table_insert (alive_connections, connection, connection);
2298 G_UNLOCK (message_bus_lock);
2300 connection->worker = _g_dbus_worker_new (connection->stream,
2301 connection->capabilities,
2302 (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING),
2303 on_worker_message_received,
2304 on_worker_message_about_to_be_sent,
2308 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2309 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2311 GVariant *hello_result;
2313 /* we could lift this restriction by adding code in gdbusprivate.c */
2314 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2316 g_set_error_literal (&connection->initialization_error,
2319 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2323 hello_result = g_dbus_connection_call_sync (connection,
2324 "org.freedesktop.DBus", /* name */
2325 "/org/freedesktop/DBus", /* path */
2326 "org.freedesktop.DBus", /* interface */
2328 NULL, /* parameters */
2329 G_VARIANT_TYPE ("(s)"),
2330 G_DBUS_CALL_FLAGS_NONE,
2332 NULL, /* TODO: cancellable */
2333 &connection->initialization_error);
2334 if (hello_result == NULL)
2337 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2338 g_variant_unref (hello_result);
2339 //g_debug ("unique name is `%s'", connection->bus_unique_name);
2342 connection->is_initialized = TRUE;
2348 g_assert (connection->initialization_error != NULL);
2349 g_propagate_error (error, g_error_copy (connection->initialization_error));
2352 g_mutex_unlock (connection->init_lock);
2358 initable_iface_init (GInitableIface *initable_iface)
2360 initable_iface->init = initable_init;
2363 /* ---------------------------------------------------------------------------------------------------- */
2366 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2371 /* ---------------------------------------------------------------------------------------------------- */
2374 * g_dbus_connection_new:
2375 * @stream: A #GIOStream.
2376 * @guid: The GUID to use if a authenticating as a server or %NULL.
2377 * @flags: Flags describing how to make the connection.
2378 * @observer: A #GDBusAuthObserver or %NULL.
2379 * @cancellable: A #GCancellable or %NULL.
2380 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2381 * @user_data: The data to pass to @callback.
2383 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2384 * with the end represented by @stream.
2386 * If @observer is not %NULL it may be used to control the
2387 * authentication process.
2389 * When the operation is finished, @callback will be invoked. You can
2390 * then call g_dbus_connection_new_finish() to get the result of the
2393 * This is a asynchronous failable constructor. See
2394 * g_dbus_connection_new_sync() for the synchronous
2400 g_dbus_connection_new (GIOStream *stream,
2402 GDBusConnectionFlags flags,
2403 GDBusAuthObserver *observer,
2404 GCancellable *cancellable,
2405 GAsyncReadyCallback callback,
2408 g_return_if_fail (G_IS_IO_STREAM (stream));
2409 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2417 "authentication-observer", observer,
2422 * g_dbus_connection_new_finish:
2423 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2424 * @error: Return location for error or %NULL.
2426 * Finishes an operation started with g_dbus_connection_new().
2428 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2433 g_dbus_connection_new_finish (GAsyncResult *res,
2437 GObject *source_object;
2439 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2440 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2442 source_object = g_async_result_get_source_object (res);
2443 g_assert (source_object != NULL);
2444 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2447 g_object_unref (source_object);
2449 return G_DBUS_CONNECTION (object);
2455 * g_dbus_connection_new_sync:
2456 * @stream: A #GIOStream.
2457 * @guid: The GUID to use if a authenticating as a server or %NULL.
2458 * @flags: Flags describing how to make the connection.
2459 * @observer: A #GDBusAuthObserver or %NULL.
2460 * @cancellable: A #GCancellable or %NULL.
2461 * @error: Return location for error or %NULL.
2463 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2464 * with the end represented by @stream.
2466 * If @observer is not %NULL it may be used to control the
2467 * authentication process.
2469 * This is a synchronous failable constructor. See
2470 * g_dbus_connection_new() for the asynchronous version.
2472 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2477 g_dbus_connection_new_sync (GIOStream *stream,
2479 GDBusConnectionFlags flags,
2480 GDBusAuthObserver *observer,
2481 GCancellable *cancellable,
2484 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2485 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2486 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2492 "authentication-observer", observer,
2496 /* ---------------------------------------------------------------------------------------------------- */
2499 * g_dbus_connection_new_for_address:
2500 * @address: A D-Bus address.
2501 * @flags: Flags describing how to make the connection.
2502 * @observer: A #GDBusAuthObserver or %NULL.
2503 * @cancellable: A #GCancellable or %NULL.
2504 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2505 * @user_data: The data to pass to @callback.
2507 * Asynchronously connects and sets up a D-Bus client connection for
2508 * exchanging D-Bus messages with an endpoint specified by @address
2509 * which must be in the D-Bus address format.
2511 * This constructor can only be used to initiate client-side
2512 * connections - use g_dbus_connection_new() if you need to act as the
2513 * server. In particular, @flags cannot contain the
2514 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2515 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2517 * When the operation is finished, @callback will be invoked. You can
2518 * then call g_dbus_connection_new_finish() to get the result of the
2521 * If @observer is not %NULL it may be used to control the
2522 * authentication process.
2524 * This is a asynchronous failable constructor. See
2525 * g_dbus_connection_new_for_address_sync() for the synchronous
2531 g_dbus_connection_new_for_address (const gchar *address,
2532 GDBusConnectionFlags flags,
2533 GDBusAuthObserver *observer,
2534 GCancellable *cancellable,
2535 GAsyncReadyCallback callback,
2538 g_return_if_fail (address != NULL);
2539 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2546 "authentication-observer", observer,
2551 * g_dbus_connection_new_for_address_finish:
2552 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2553 * @error: Return location for error or %NULL.
2555 * Finishes an operation started with g_dbus_connection_new_for_address().
2557 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2562 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2566 GObject *source_object;
2568 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2569 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2571 source_object = g_async_result_get_source_object (res);
2572 g_assert (source_object != NULL);
2573 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2576 g_object_unref (source_object);
2578 return G_DBUS_CONNECTION (object);
2584 * g_dbus_connection_new_for_address_sync:
2585 * @address: A D-Bus address.
2586 * @flags: Flags describing how to make the connection.
2587 * @observer: A #GDBusAuthObserver or %NULL.
2588 * @cancellable: A #GCancellable or %NULL.
2589 * @error: Return location for error or %NULL.
2591 * Synchronously connects and sets up a D-Bus client connection for
2592 * exchanging D-Bus messages with an endpoint specified by @address
2593 * which must be in the D-Bus address format.
2595 * This constructor can only be used to initiate client-side
2596 * connections - use g_dbus_connection_new_sync() if you need to act
2597 * as the server. In particular, @flags cannot contain the
2598 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2599 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2601 * This is a synchronous failable constructor. See
2602 * g_dbus_connection_new_for_address() for the asynchronous version.
2604 * If @observer is not %NULL it may be used to control the
2605 * authentication process.
2607 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2612 g_dbus_connection_new_for_address_sync (const gchar *address,
2613 GDBusConnectionFlags flags,
2614 GDBusAuthObserver *observer,
2615 GCancellable *cancellable,
2618 g_return_val_if_fail (address != NULL, NULL);
2619 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2620 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2625 "authentication-observer", observer,
2629 /* ---------------------------------------------------------------------------------------------------- */
2632 * g_dbus_connection_set_exit_on_close:
2633 * @connection: A #GDBusConnection.
2634 * @exit_on_close: Whether the process should be terminated
2635 * when @connection is closed by the remote peer.
2637 * Sets whether the process should be terminated when @connection is
2638 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2644 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2645 gboolean exit_on_close)
2647 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2648 connection->exit_on_close = exit_on_close;
2652 * g_dbus_connection_get_exit_on_close:
2653 * @connection: A #GDBusConnection.
2655 * Gets whether the process is terminated when @connection is
2656 * closed by the remote peer. See
2657 * #GDBusConnection:exit-on-close for more details.
2659 * Returns: Whether the process is terminated when @connection is
2660 * closed by the remote peer.
2665 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2667 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2668 return connection->exit_on_close;
2672 * g_dbus_connection_get_guid:
2673 * @connection: A #GDBusConnection.
2675 * The GUID of the peer performing the role of server when
2676 * authenticating. See #GDBusConnection:guid for more details.
2678 * Returns: The GUID. Do not free this string, it is owned by
2684 g_dbus_connection_get_guid (GDBusConnection *connection)
2686 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2687 return connection->guid;
2691 * g_dbus_connection_get_unique_name:
2692 * @connection: A #GDBusConnection.
2694 * Gets the unique name of @connection as assigned by the message
2695 * bus. This can also be used to figure out if @connection is a
2696 * message bus connection.
2698 * Returns: The unique name or %NULL if @connection is not a message
2699 * bus connection. Do not free this string, it is owned by
2705 g_dbus_connection_get_unique_name (GDBusConnection *connection)
2707 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2708 return connection->bus_unique_name;
2712 * g_dbus_connection_get_peer_credentials:
2713 * @connection: A #GDBusConnection.
2715 * Gets the credentials of the authenticated peer. This will always
2716 * return %NULL unless @connection acted as a server
2717 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
2718 * when set up and the client passed credentials as part of the
2719 * authentication process.
2721 * In a message bus setup, the message bus is always the server and
2722 * each application is a client. So this method will always return
2723 * %NULL for message bus clients.
2725 * Returns: A #GCredentials or %NULL if not available. Do not free
2726 * this object, it is owned by @connection.
2731 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
2733 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2734 return connection->credentials;
2737 /* ---------------------------------------------------------------------------------------------------- */
2739 static guint _global_filter_id = 1;
2742 * g_dbus_connection_add_filter:
2743 * @connection: A #GDBusConnection.
2744 * @filter_function: A filter function.
2745 * @user_data: User data to pass to @filter_function.
2746 * @user_data_free_func: Function to free @user_data with when filter
2747 * is removed or %NULL.
2749 * Adds a message filter. Filters are handlers that are run on all
2750 * incoming and outgoing messages, prior to standard dispatch. Filters
2751 * are run in the order that they were added. The same handler can be
2752 * added as a filter more than once, in which case it will be run more
2753 * than once. Filters added during a filter callback won't be run on
2754 * the message being processed. Filter functions are allowed to modify
2755 * and even drop messages - see the #GDBusMessageFilterResult
2756 * enumeration for details.
2758 * Note that filters are run in a dedicated message handling thread so
2759 * they can't block and, generally, can't do anything but signal a
2760 * worker thread. Also note that filters are rarely needed - use API
2761 * such as g_dbus_connection_send_message_with_reply(),
2762 * g_dbus_connection_signal_subscribe() or
2763 * g_dbus_connection_call() instead.
2765 * If a filter consumes an incoming message the message is not
2766 * dispatched anywhere else - not even the standard dispatch machinery
2767 * (that API such as g_dbus_connection_signal_subscribe() and
2768 * g_dbus_connection_send_message_with_reply() relies on) will see the
2769 * message. Similary, if a filter consumes an outgoing message, the
2770 * message will not be sent to the other peer.
2772 * Returns: A filter identifier that can be used with
2773 * g_dbus_connection_remove_filter().
2778 g_dbus_connection_add_filter (GDBusConnection *connection,
2779 GDBusMessageFilterFunction filter_function,
2781 GDestroyNotify user_data_free_func)
2785 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2786 g_return_val_if_fail (filter_function != NULL, 0);
2788 CONNECTION_LOCK (connection);
2789 data = g_new0 (FilterData, 1);
2790 data->id = _global_filter_id++; /* TODO: overflow etc. */
2791 data->filter_function = filter_function;
2792 data->user_data = user_data;
2793 data->user_data_free_func = user_data_free_func;
2794 g_ptr_array_add (connection->filters, data);
2795 CONNECTION_UNLOCK (connection);
2800 /* only called from finalize(), removes all filters */
2802 purge_all_filters (GDBusConnection *connection)
2805 for (n = 0; n < connection->filters->len; n++)
2807 FilterData *data = connection->filters->pdata[n];
2808 if (data->user_data_free_func != NULL)
2809 data->user_data_free_func (data->user_data);
2815 * g_dbus_connection_remove_filter:
2816 * @connection: a #GDBusConnection
2817 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
2824 g_dbus_connection_remove_filter (GDBusConnection *connection,
2828 FilterData *to_destroy;
2830 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2832 CONNECTION_LOCK (connection);
2834 for (n = 0; n < connection->filters->len; n++)
2836 FilterData *data = connection->filters->pdata[n];
2837 if (data->id == filter_id)
2839 g_ptr_array_remove_index (connection->filters, n);
2844 CONNECTION_UNLOCK (connection);
2846 /* do free without holding lock */
2847 if (to_destroy != NULL)
2849 if (to_destroy->user_data_free_func != NULL)
2850 to_destroy->user_data_free_func (to_destroy->user_data);
2851 g_free (to_destroy);
2855 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
2859 /* ---------------------------------------------------------------------------------------------------- */
2865 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
2866 gchar *interface_name;
2870 GArray *subscribers;
2875 GDBusSignalCallback callback;
2877 GDestroyNotify user_data_free_func;
2879 GMainContext *context;
2883 signal_data_free (SignalData *signal_data)
2885 g_free (signal_data->rule);
2886 g_free (signal_data->sender);
2887 g_free (signal_data->sender_unique_name);
2888 g_free (signal_data->interface_name);
2889 g_free (signal_data->member);
2890 g_free (signal_data->object_path);
2891 g_free (signal_data->arg0);
2892 g_array_free (signal_data->subscribers, TRUE);
2893 g_free (signal_data);
2897 args_to_rule (const gchar *sender,
2898 const gchar *interface_name,
2899 const gchar *member,
2900 const gchar *object_path,
2905 rule = g_string_new ("type='signal'");
2907 g_string_append_printf (rule, ",sender='%s'", sender);
2908 if (interface_name != NULL)
2909 g_string_append_printf (rule, ",interface='%s'", interface_name);
2911 g_string_append_printf (rule, ",member='%s'", member);
2912 if (object_path != NULL)
2913 g_string_append_printf (rule, ",path='%s'", object_path);
2915 g_string_append_printf (rule, ",arg0='%s'", arg0);
2917 return g_string_free (rule, FALSE);
2920 static guint _global_subscriber_id = 1;
2921 static guint _global_registration_id = 1;
2922 static guint _global_subtree_registration_id = 1;
2924 /* ---------------------------------------------------------------------------------------------------- */
2926 /* must hold lock when calling */
2928 add_match_rule (GDBusConnection *connection,
2929 const gchar *match_rule)
2932 GDBusMessage *message;
2934 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2935 "/org/freedesktop/DBus", /* path */
2936 "org.freedesktop.DBus", /* interface */
2938 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2940 if (!g_dbus_connection_send_message_unlocked (connection,
2942 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
2946 g_critical ("Error while sending AddMatch() message: %s", error->message);
2947 g_error_free (error);
2949 g_object_unref (message);
2952 /* ---------------------------------------------------------------------------------------------------- */
2954 /* must hold lock when calling */
2956 remove_match_rule (GDBusConnection *connection,
2957 const gchar *match_rule)
2960 GDBusMessage *message;
2962 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2963 "/org/freedesktop/DBus", /* path */
2964 "org.freedesktop.DBus", /* interface */
2966 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2969 if (!g_dbus_connection_send_message_unlocked (connection,
2971 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
2975 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
2976 g_error_free (error);
2978 g_object_unref (message);
2981 /* ---------------------------------------------------------------------------------------------------- */
2984 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
2986 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
2987 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
2988 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
2989 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
2990 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
2993 /* ---------------------------------------------------------------------------------------------------- */
2996 * g_dbus_connection_signal_subscribe:
2997 * @connection: A #GDBusConnection.
2998 * @sender: Sender name to match on (unique or well-known name) or %NULL to listen from all senders.
2999 * @interface_name: D-Bus interface name to match on or %NULL to match on all interfaces.
3000 * @member: D-Bus signal name to match on or %NULL to match on all signals.
3001 * @object_path: Object path to match on or %NULL to match on all object paths.
3002 * @arg0: Contents of first string argument to match on or %NULL to match on all kinds of arguments.
3003 * @flags: Flags describing how to subscribe to the signal (currently unused).
3004 * @callback: Callback to invoke when there is a signal matching the requested data.
3005 * @user_data: User data to pass to @callback.
3006 * @user_data_free_func: Function to free @user_data with when subscription is removed or %NULL.
3008 * Subscribes to signals on @connection and invokes @callback with a
3009 * whenever the signal is received. Note that @callback
3010 * will be invoked in the <link
3011 * linkend="g-main-context-push-thread-default">thread-default main
3012 * loop</link> of the thread you are calling this method from.
3014 * If @connection is not a message bus connection, @sender must be
3017 * If @sender is a well-known name note that @callback is invoked with
3018 * the unique name for the owner of @sender, not the well-known name
3019 * as one would expect. This is because the message bus rewrites the
3020 * name. As such, to avoid certain race conditions, users should be
3021 * tracking the name owner of the well-known name and use that when
3022 * processing the received signal.
3024 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
3029 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3030 const gchar *sender,
3031 const gchar *interface_name,
3032 const gchar *member,
3033 const gchar *object_path,
3035 GDBusSignalFlags flags,
3036 GDBusSignalCallback callback,
3038 GDestroyNotify user_data_free_func)
3041 SignalData *signal_data;
3042 SignalSubscriber subscriber;
3043 GPtrArray *signal_data_array;
3044 const gchar *sender_unique_name;
3046 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3047 * an OOM condition. We might want to change that but that would involve making
3048 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3049 * handle that. And there's really no sensible way of handling this short of retrying
3050 * to add the match rule... and then there's the little thing that, hey, maybe there's
3051 * a reason the bus in an OOM condition.
3053 * Doable, but not really sure it's worth it...
3056 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3057 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3058 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3059 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3060 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3061 g_return_val_if_fail (callback != NULL, 0);
3063 CONNECTION_LOCK (connection);
3065 rule = args_to_rule (sender, interface_name, member, object_path, arg0);
3067 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3068 sender_unique_name = sender;
3070 sender_unique_name = "";
3072 subscriber.callback = callback;
3073 subscriber.user_data = user_data;
3074 subscriber.user_data_free_func = user_data_free_func;
3075 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3076 subscriber.context = g_main_context_get_thread_default ();
3077 if (subscriber.context != NULL)
3078 g_main_context_ref (subscriber.context);
3080 /* see if we've already have this rule */
3081 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3082 if (signal_data != NULL)
3084 g_array_append_val (signal_data->subscribers, subscriber);
3089 signal_data = g_new0 (SignalData, 1);
3090 signal_data->rule = rule;
3091 signal_data->sender = g_strdup (sender);
3092 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3093 signal_data->interface_name = g_strdup (interface_name);
3094 signal_data->member = g_strdup (member);
3095 signal_data->object_path = g_strdup (object_path);
3096 signal_data->arg0 = g_strdup (arg0);
3097 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3098 g_array_append_val (signal_data->subscribers, subscriber);
3100 g_hash_table_insert (connection->map_rule_to_signal_data,
3104 /* Add the match rule to the bus...
3106 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3107 * always send such messages to us.
3109 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3111 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3112 add_match_rule (connection, signal_data->rule);
3115 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3116 signal_data->sender_unique_name);
3117 if (signal_data_array == NULL)
3119 signal_data_array = g_ptr_array_new ();
3120 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3121 g_strdup (signal_data->sender_unique_name),
3124 g_ptr_array_add (signal_data_array, signal_data);
3127 g_hash_table_insert (connection->map_id_to_signal_data,
3128 GUINT_TO_POINTER (subscriber.id),
3131 CONNECTION_UNLOCK (connection);
3133 return subscriber.id;
3136 /* ---------------------------------------------------------------------------------------------------- */
3138 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3140 unsubscribe_id_internal (GDBusConnection *connection,
3141 guint subscription_id,
3142 GArray *out_removed_subscribers)
3144 SignalData *signal_data;
3145 GPtrArray *signal_data_array;
3148 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3149 GUINT_TO_POINTER (subscription_id));
3150 if (signal_data == NULL)
3152 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3156 for (n = 0; n < signal_data->subscribers->len; n++)
3158 SignalSubscriber *subscriber;
3160 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3161 if (subscriber->id != subscription_id)
3164 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3165 GUINT_TO_POINTER (subscription_id)));
3166 g_array_append_val (out_removed_subscribers, *subscriber);
3167 g_array_remove_index (signal_data->subscribers, n);
3169 if (signal_data->subscribers->len == 0)
3171 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3173 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3174 signal_data->sender_unique_name);
3175 g_warn_if_fail (signal_data_array != NULL);
3176 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3178 if (signal_data_array->len == 0)
3180 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3181 signal_data->sender_unique_name));
3184 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3185 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3187 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3188 if (!connection->closed && !connection->finalizing)
3189 remove_match_rule (connection, signal_data->rule);
3191 signal_data_free (signal_data);
3197 g_assert_not_reached ();
3204 * g_dbus_connection_signal_unsubscribe:
3205 * @connection: A #GDBusConnection.
3206 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
3208 * Unsubscribes from signals.
3213 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3214 guint subscription_id)
3216 GArray *subscribers;
3219 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3221 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3223 CONNECTION_LOCK (connection);
3224 unsubscribe_id_internal (connection,
3227 CONNECTION_UNLOCK (connection);
3230 g_assert (subscribers->len == 0 || subscribers->len == 1);
3232 /* call GDestroyNotify without lock held */
3233 for (n = 0; n < subscribers->len; n++)
3235 SignalSubscriber *subscriber;
3236 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3237 if (subscriber->user_data_free_func != NULL)
3238 subscriber->user_data_free_func (subscriber->user_data);
3239 if (subscriber->context != NULL)
3240 g_main_context_unref (subscriber->context);
3243 g_array_free (subscribers, TRUE);
3246 /* ---------------------------------------------------------------------------------------------------- */
3250 guint subscription_id;
3251 GDBusSignalCallback callback;
3253 GDBusMessage *message;
3254 GDBusConnection *connection;
3255 const gchar *sender;
3257 const gchar *interface;
3258 const gchar *member;
3261 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3265 emit_signal_instance_in_idle_cb (gpointer data)
3267 SignalInstance *signal_instance = data;
3268 GVariant *parameters;
3269 gboolean has_subscription;
3271 parameters = g_dbus_message_get_body (signal_instance->message);
3272 if (parameters == NULL)
3274 parameters = g_variant_new ("()");
3275 g_variant_ref_sink (parameters);
3279 g_variant_ref_sink (parameters);
3283 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3284 signal_instance->subscription_id,
3285 signal_instance->sender,
3286 signal_instance->path,
3287 signal_instance->interface,
3288 signal_instance->member,
3289 g_variant_print (parameters, TRUE));
3292 /* Careful here, don't do the callback if we no longer has the subscription */
3293 CONNECTION_LOCK (signal_instance->connection);
3294 has_subscription = FALSE;
3295 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3296 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3297 has_subscription = TRUE;
3298 CONNECTION_UNLOCK (signal_instance->connection);
3300 if (has_subscription)
3301 signal_instance->callback (signal_instance->connection,
3302 signal_instance->sender,
3303 signal_instance->path,
3304 signal_instance->interface,
3305 signal_instance->member,
3307 signal_instance->user_data);
3309 if (parameters != NULL)
3310 g_variant_unref (parameters);
3316 signal_instance_free (SignalInstance *signal_instance)
3318 g_object_unref (signal_instance->message);
3319 g_object_unref (signal_instance->connection);
3320 g_free (signal_instance);
3323 /* called in message handler thread WITH lock held */
3325 schedule_callbacks (GDBusConnection *connection,
3326 GPtrArray *signal_data_array,
3327 GDBusMessage *message,
3328 const gchar *sender)
3331 const gchar *interface;
3332 const gchar *member;
3341 interface = g_dbus_message_get_interface (message);
3342 member = g_dbus_message_get_member (message);
3343 path = g_dbus_message_get_path (message);
3344 arg0 = g_dbus_message_get_arg0 (message);
3347 g_print ("In schedule_callbacks:\n"
3349 " interface = `%s'\n"
3360 /* TODO: if this is slow, then we can change signal_data_array into
3361 * map_object_path_to_signal_data_array or something.
3363 for (n = 0; n < signal_data_array->len; n++)
3365 SignalData *signal_data = signal_data_array->pdata[n];
3367 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3370 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3373 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3376 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
3379 for (m = 0; m < signal_data->subscribers->len; m++)
3381 SignalSubscriber *subscriber;
3382 GSource *idle_source;
3383 SignalInstance *signal_instance;
3385 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3387 signal_instance = g_new0 (SignalInstance, 1);
3388 signal_instance->subscription_id = subscriber->id;
3389 signal_instance->callback = subscriber->callback;
3390 signal_instance->user_data = subscriber->user_data;
3391 signal_instance->message = g_object_ref (message);
3392 signal_instance->connection = g_object_ref (connection);
3393 signal_instance->sender = sender;
3394 signal_instance->path = path;
3395 signal_instance->interface = interface;
3396 signal_instance->member = member;
3398 idle_source = g_idle_source_new ();
3399 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3400 g_source_set_callback (idle_source,
3401 emit_signal_instance_in_idle_cb,
3403 (GDestroyNotify) signal_instance_free);
3404 g_source_attach (idle_source, subscriber->context);
3405 g_source_unref (idle_source);
3410 /* called in message handler thread with lock held */
3412 distribute_signals (GDBusConnection *connection,
3413 GDBusMessage *message)
3415 GPtrArray *signal_data_array;
3416 const gchar *sender;
3418 sender = g_dbus_message_get_sender (message);
3420 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3422 _g_dbus_debug_print_lock ();
3423 g_print ("========================================================================\n"
3424 "GDBus-debug:Signal:\n"
3425 " <<<< RECEIVED SIGNAL %s.%s\n"
3427 " sent by name %s\n",
3428 g_dbus_message_get_interface (message),
3429 g_dbus_message_get_member (message),
3430 g_dbus_message_get_path (message),
3431 sender != NULL ? sender : "(none)");
3432 _g_dbus_debug_print_unlock ();
3435 /* collect subscribers that match on sender */
3438 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3439 if (signal_data_array != NULL)
3440 schedule_callbacks (connection, signal_data_array, message, sender);
3443 /* collect subscribers not matching on sender */
3444 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3445 if (signal_data_array != NULL)
3446 schedule_callbacks (connection, signal_data_array, message, sender);
3449 /* ---------------------------------------------------------------------------------------------------- */
3451 /* only called from finalize(), removes all subscriptions */
3453 purge_all_signal_subscriptions (GDBusConnection *connection)
3455 GHashTableIter iter;
3458 GArray *subscribers;
3461 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3462 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3463 while (g_hash_table_iter_next (&iter, &key, NULL))
3465 guint subscription_id = GPOINTER_TO_UINT (key);
3466 g_array_append_val (ids, subscription_id);
3469 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3470 for (n = 0; n < ids->len; n++)
3472 guint subscription_id = g_array_index (ids, guint, n);
3473 unsubscribe_id_internal (connection,
3477 g_array_free (ids, TRUE);
3479 /* call GDestroyNotify without lock held */
3480 for (n = 0; n < subscribers->len; n++)
3482 SignalSubscriber *subscriber;
3483 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3484 if (subscriber->user_data_free_func != NULL)
3485 subscriber->user_data_free_func (subscriber->user_data);
3486 if (subscriber->context != NULL)
3487 g_main_context_unref (subscriber->context);
3490 g_array_free (subscribers, TRUE);
3493 /* ---------------------------------------------------------------------------------------------------- */
3495 static GDBusInterfaceVTable *
3496 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3498 /* Don't waste memory by copying padding - remember to update this
3499 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3501 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3505 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
3510 /* ---------------------------------------------------------------------------------------------------- */
3512 static GDBusSubtreeVTable *
3513 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
3515 /* Don't waste memory by copying padding - remember to update this
3516 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
3518 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3522 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
3527 /* ---------------------------------------------------------------------------------------------------- */
3529 struct ExportedObject
3532 GDBusConnection *connection;
3534 /* maps gchar* -> ExportedInterface* */
3535 GHashTable *map_if_name_to_ei;
3538 /* only called with lock held */
3540 exported_object_free (ExportedObject *eo)
3542 g_free (eo->object_path);
3543 g_hash_table_unref (eo->map_if_name_to_ei);
3552 gchar *interface_name;
3553 GDBusInterfaceVTable *vtable;
3554 GDBusInterfaceInfo *interface_info;
3556 GMainContext *context;
3558 GDestroyNotify user_data_free_func;
3559 } ExportedInterface;
3561 /* called with lock held */
3563 exported_interface_free (ExportedInterface *ei)
3565 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
3567 if (ei->user_data_free_func != NULL)
3568 /* TODO: push to thread-default mainloop */
3569 ei->user_data_free_func (ei->user_data);
3571 if (ei->context != NULL)
3572 g_main_context_unref (ei->context);
3574 g_free (ei->interface_name);
3575 _g_dbus_interface_vtable_free (ei->vtable);
3579 /* ---------------------------------------------------------------------------------------------------- */
3581 /* Convenience function to check if @registration_id (if not zero) or
3582 * @subtree_registration_id (if not zero) has been unregistered. If
3583 * so, returns %TRUE.
3585 * Caller must *not* hold lock.
3588 has_object_been_unregistered (GDBusConnection *connection,
3589 guint registration_id,
3590 guint subtree_registration_id)
3594 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3598 CONNECTION_LOCK (connection);
3599 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
3600 GUINT_TO_POINTER (registration_id)) == NULL)
3604 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
3605 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
3609 CONNECTION_UNLOCK (connection);
3614 /* ---------------------------------------------------------------------------------------------------- */
3618 GDBusConnection *connection;
3619 GDBusMessage *message;
3621 const gchar *property_name;
3622 const GDBusInterfaceVTable *vtable;
3623 GDBusInterfaceInfo *interface_info;
3624 const GDBusPropertyInfo *property_info;
3625 guint registration_id;
3626 guint subtree_registration_id;
3630 property_data_free (PropertyData *data)
3632 g_object_unref (data->connection);
3633 g_object_unref (data->message);
3637 /* called in thread where object was registered - no locks held */
3639 invoke_get_property_in_idle_cb (gpointer _data)
3641 PropertyData *data = _data;
3644 GDBusMessage *reply;
3646 if (has_object_been_unregistered (data->connection,
3647 data->registration_id,
3648 data->subtree_registration_id))
3650 reply = g_dbus_message_new_method_error (data->message,
3651 "org.freedesktop.DBus.Error.UnknownMethod",
3652 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
3653 g_dbus_message_get_path (data->message));
3654 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3655 g_object_unref (reply);
3660 value = data->vtable->get_property (data->connection,
3661 g_dbus_message_get_sender (data->message),
3662 g_dbus_message_get_path (data->message),
3663 data->interface_info->name,
3664 data->property_name,
3671 g_assert_no_error (error);
3673 if (g_variant_is_floating (value))
3674 g_variant_ref_sink (value);
3675 reply = g_dbus_message_new_method_reply (data->message);
3676 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
3677 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3678 g_variant_unref (value);
3679 g_object_unref (reply);
3683 gchar *dbus_error_name;
3684 g_assert (error != NULL);
3685 dbus_error_name = g_dbus_error_encode_gerror (error);
3686 reply = g_dbus_message_new_method_error_literal (data->message,
3689 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3690 g_free (dbus_error_name);
3691 g_error_free (error);
3692 g_object_unref (reply);
3699 /* called in thread where object was registered - no locks held */
3701 invoke_set_property_in_idle_cb (gpointer _data)
3703 PropertyData *data = _data;
3705 GDBusMessage *reply;
3711 g_variant_get (g_dbus_message_get_body (data->message),
3717 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
3718 * of the given value is wrong
3720 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
3722 reply = g_dbus_message_new_method_error (data->message,
3723 "org.freedesktop.DBus.Error.InvalidArgs",
3724 _("Error setting property `%s': Expected type `%s' but got `%s'"),
3725 data->property_info->name,
3726 data->property_info->signature,
3727 g_variant_get_type_string (value));
3731 if (!data->vtable->set_property (data->connection,
3732 g_dbus_message_get_sender (data->message),
3733 g_dbus_message_get_path (data->message),
3734 data->interface_info->name,
3735 data->property_name,
3740 gchar *dbus_error_name;
3741 g_assert (error != NULL);
3742 dbus_error_name = g_dbus_error_encode_gerror (error);
3743 reply = g_dbus_message_new_method_error_literal (data->message,
3746 g_free (dbus_error_name);
3747 g_error_free (error);
3751 reply = g_dbus_message_new_method_reply (data->message);
3755 g_assert (reply != NULL);
3756 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3757 g_object_unref (reply);
3758 g_variant_unref (value);
3763 /* called with lock held */
3765 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
3766 GDBusMessage *message,
3767 guint registration_id,
3768 guint subtree_registration_id,
3770 GDBusInterfaceInfo *interface_info,
3771 const GDBusInterfaceVTable *vtable,
3772 GMainContext *main_context,
3776 const char *interface_name;
3777 const char *property_name;
3778 const GDBusPropertyInfo *property_info;
3779 GSource *idle_source;
3780 PropertyData *property_data;
3781 GDBusMessage *reply;
3786 g_variant_get (g_dbus_message_get_body (message),
3791 g_variant_get (g_dbus_message_get_body (message),
3800 if (vtable == NULL || vtable->get_property == NULL)
3805 if (vtable == NULL || vtable->set_property == NULL)
3809 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
3811 property_info = NULL;
3813 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3814 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
3815 if (property_info == NULL)
3817 reply = g_dbus_message_new_method_error (message,
3818 "org.freedesktop.DBus.Error.InvalidArgs",
3819 _("No such property `%s'"),
3821 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3822 g_object_unref (reply);
3827 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3829 reply = g_dbus_message_new_method_error (message,
3830 "org.freedesktop.DBus.Error.InvalidArgs",
3831 _("Property `%s' is not readable"),
3833 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3834 g_object_unref (reply);
3838 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
3840 reply = g_dbus_message_new_method_error (message,
3841 "org.freedesktop.DBus.Error.InvalidArgs",
3842 _("Property `%s' is not writable"),
3844 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3845 g_object_unref (reply);
3850 /* ok, got the property info - call user code in an idle handler */
3851 property_data = g_new0 (PropertyData, 1);
3852 property_data->connection = g_object_ref (connection);
3853 property_data->message = g_object_ref (message);
3854 property_data->user_data = user_data;
3855 property_data->property_name = property_name;
3856 property_data->vtable = vtable;
3857 property_data->interface_info = interface_info;
3858 property_data->property_info = property_info;
3859 property_data->registration_id = registration_id;
3860 property_data->subtree_registration_id = subtree_registration_id;
3862 idle_source = g_idle_source_new ();
3863 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3864 g_source_set_callback (idle_source,
3865 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
3867 (GDestroyNotify) property_data_free);
3868 g_source_attach (idle_source, main_context);
3869 g_source_unref (idle_source);
3877 /* called with lock held */
3879 handle_getset_property (GDBusConnection *connection,
3881 GDBusMessage *message,
3884 ExportedInterface *ei;
3886 const char *interface_name;
3887 const char *property_name;
3892 g_variant_get (g_dbus_message_get_body (message),
3897 g_variant_get (g_dbus_message_get_body (message),
3903 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3904 * no such interface registered
3906 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3909 GDBusMessage *reply;
3910 reply = g_dbus_message_new_method_error (message,
3911 "org.freedesktop.DBus.Error.InvalidArgs",
3912 _("No such interface `%s'"),
3914 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3915 g_object_unref (reply);
3920 handled = validate_and_maybe_schedule_property_getset (eo->connection,
3933 /* ---------------------------------------------------------------------------------------------------- */
3937 GDBusConnection *connection;
3938 GDBusMessage *message;
3940 const GDBusInterfaceVTable *vtable;
3941 GDBusInterfaceInfo *interface_info;
3942 guint registration_id;
3943 guint subtree_registration_id;
3944 } PropertyGetAllData;
3947 property_get_all_data_free (PropertyData *data)
3949 g_object_unref (data->connection);
3950 g_object_unref (data->message);
3954 /* called in thread where object was registered - no locks held */
3956 invoke_get_all_properties_in_idle_cb (gpointer _data)
3958 PropertyGetAllData *data = _data;
3959 GVariantBuilder builder;
3961 GDBusMessage *reply;
3964 if (has_object_been_unregistered (data->connection,
3965 data->registration_id,
3966 data->subtree_registration_id))
3968 reply = g_dbus_message_new_method_error (data->message,
3969 "org.freedesktop.DBus.Error.UnknownMethod",
3970 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
3971 g_dbus_message_get_path (data->message));
3972 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3973 g_object_unref (reply);
3979 /* TODO: Right now we never fail this call - we just omit values if
3980 * a get_property() call is failing.
3982 * We could fail the whole call if just a single get_property() call
3983 * returns an error. We need clarification in the D-Bus spec about this.
3985 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
3986 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
3987 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
3989 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
3992 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3995 value = data->vtable->get_property (data->connection,
3996 g_dbus_message_get_sender (data->message),
3997 g_dbus_message_get_path (data->message),
3998 data->interface_info->name,
3999 property_info->name,
4006 if (g_variant_is_floating (value))
4007 g_variant_ref_sink (value);
4008 g_variant_builder_add (&builder,
4010 property_info->name,
4012 g_variant_unref (value);
4014 g_variant_builder_close (&builder);
4016 reply = g_dbus_message_new_method_reply (data->message);
4017 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4018 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4019 g_object_unref (reply);
4025 /* called with lock held */
4027 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4028 GDBusMessage *message,
4029 guint registration_id,
4030 guint subtree_registration_id,
4031 GDBusInterfaceInfo *interface_info,
4032 const GDBusInterfaceVTable *vtable,
4033 GMainContext *main_context,
4037 const char *interface_name;
4038 GSource *idle_source;
4039 PropertyGetAllData *property_get_all_data;
4043 g_variant_get (g_dbus_message_get_body (message),
4047 if (vtable == NULL || vtable->get_property == NULL)
4050 /* ok, got the property info - call user in an idle handler */
4051 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4052 property_get_all_data->connection = g_object_ref (connection);
4053 property_get_all_data->message = g_object_ref (message);
4054 property_get_all_data->user_data = user_data;
4055 property_get_all_data->vtable = vtable;
4056 property_get_all_data->interface_info = interface_info;
4057 property_get_all_data->registration_id = registration_id;
4058 property_get_all_data->subtree_registration_id = subtree_registration_id;
4060 idle_source = g_idle_source_new ();
4061 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4062 g_source_set_callback (idle_source,
4063 invoke_get_all_properties_in_idle_cb,
4064 property_get_all_data,
4065 (GDestroyNotify) property_get_all_data_free);
4066 g_source_attach (idle_source, main_context);
4067 g_source_unref (idle_source);
4075 /* called with lock held */
4077 handle_get_all_properties (GDBusConnection *connection,
4079 GDBusMessage *message)
4081 ExportedInterface *ei;
4083 const char *interface_name;
4087 g_variant_get (g_dbus_message_get_body (message),
4091 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4092 * no such interface registered
4094 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4097 GDBusMessage *reply;
4098 reply = g_dbus_message_new_method_error (message,
4099 "org.freedesktop.DBus.Error.InvalidArgs",
4100 _("No such interface"),
4102 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4103 g_object_unref (reply);
4108 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4120 /* ---------------------------------------------------------------------------------------------------- */
4122 static const gchar introspect_header[] =
4123 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4124 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4125 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4128 static const gchar introspect_tail[] =
4131 static const gchar introspect_standard_interfaces[] =
4132 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4133 " <method name=\"Get\">\n"
4134 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4135 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4136 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4138 " <method name=\"GetAll\">\n"
4139 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4140 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4142 " <method name=\"Set\">\n"
4143 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4144 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4145 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4147 " <signal name=\"PropertiesChanged\">\n"
4148 " <arg type=\"s\" name=\"interface_name\"/>\n"
4149 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4150 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4153 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4154 " <method name=\"Introspect\">\n"
4155 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4158 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4159 " <method name=\"Ping\"/>\n"
4160 " <method name=\"GetMachineId\">\n"
4161 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4166 introspect_append_header (GString *s)
4168 g_string_append (s, introspect_header);
4172 introspect_append_standard_interfaces (GString *s)
4174 g_string_append (s, introspect_standard_interfaces);
4178 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4180 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4186 begin = object_path + path_len;
4187 end = strchr (begin, '/');
4189 s = g_strndup (begin, end - begin);
4191 s = g_strdup (begin);
4193 if (g_hash_table_lookup (set, s) == NULL)
4194 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
4200 /* TODO: we want a nicer public interface for this */
4202 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4207 GHashTableIter hash_iter;
4208 const gchar *object_path;
4214 CONNECTION_ENSURE_LOCK (connection);
4216 path_len = strlen (path);
4220 set = g_hash_table_new (g_str_hash, g_str_equal);
4222 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4223 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4224 maybe_add_path (path, path_len, object_path, set);
4226 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4227 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4228 maybe_add_path (path, path_len, object_path, set);
4230 p = g_ptr_array_new ();
4231 keys = g_hash_table_get_keys (set);
4232 for (l = keys; l != NULL; l = l->next)
4233 g_ptr_array_add (p, l->data);
4234 g_hash_table_unref (set);
4237 g_ptr_array_add (p, NULL);
4238 ret = (gchar **) g_ptr_array_free (p, FALSE);
4243 g_dbus_connection_list_registered (GDBusConnection *connection,
4247 CONNECTION_LOCK (connection);
4248 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4249 CONNECTION_UNLOCK (connection);
4253 /* called in message handler thread with lock held */
4255 handle_introspect (GDBusConnection *connection,
4257 GDBusMessage *message)
4261 GDBusMessage *reply;
4262 GHashTableIter hash_iter;
4263 ExportedInterface *ei;
4266 /* first the header with the standard interfaces */
4267 s = g_string_sized_new (sizeof (introspect_header) +
4268 sizeof (introspect_standard_interfaces) +
4269 sizeof (introspect_tail));
4270 introspect_append_header (s);
4271 introspect_append_standard_interfaces (s);
4273 /* then include the registered interfaces */
4274 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4275 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4276 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4278 /* finally include nodes registered below us */
4279 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4280 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4281 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4282 g_strfreev (registered);
4283 g_string_append (s, introspect_tail);
4285 reply = g_dbus_message_new_method_reply (message);
4286 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4287 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4288 g_object_unref (reply);
4289 g_string_free (s, TRUE);
4294 /* called in thread where object was registered - no locks held */
4296 call_in_idle_cb (gpointer user_data)
4298 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4299 GDBusInterfaceVTable *vtable;
4300 guint registration_id;
4301 guint subtree_registration_id;
4303 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4304 g_assert (vtable != NULL && vtable->method_call != NULL);
4306 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4307 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4309 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4311 subtree_registration_id))
4313 GDBusMessage *reply;
4314 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4315 "org.freedesktop.DBus.Error.UnknownMethod",
4316 _("No such interface `%s' on object at path %s"),
4317 g_dbus_method_invocation_get_interface_name (invocation),
4318 g_dbus_method_invocation_get_object_path (invocation));
4319 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4320 g_object_unref (reply);
4324 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4325 g_dbus_method_invocation_get_sender (invocation),
4326 g_dbus_method_invocation_get_object_path (invocation),
4327 g_dbus_method_invocation_get_interface_name (invocation),
4328 g_dbus_method_invocation_get_method_name (invocation),
4329 g_dbus_method_invocation_get_parameters (invocation),
4330 g_object_ref (invocation),
4331 g_dbus_method_invocation_get_user_data (invocation));
4337 /* called in message handler thread with lock held */
4339 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4340 GDBusMessage *message,
4341 guint registration_id,
4342 guint subtree_registration_id,
4343 GDBusInterfaceInfo *interface_info,
4344 const GDBusInterfaceVTable *vtable,
4345 GMainContext *main_context,
4348 GDBusMethodInvocation *invocation;
4349 const GDBusMethodInfo *method_info;
4350 GDBusMessage *reply;
4351 GVariant *parameters;
4352 GSource *idle_source;
4354 GVariantType *in_type;
4358 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4359 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4361 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4362 * error to the caller
4364 if (method_info == NULL)
4366 reply = g_dbus_message_new_method_error (message,
4367 "org.freedesktop.DBus.Error.UnknownMethod",
4368 _("No such method `%s'"),
4369 g_dbus_message_get_member (message));
4370 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4371 g_object_unref (reply);
4376 parameters = g_dbus_message_get_body (message);
4377 if (parameters == NULL)
4379 parameters = g_variant_new ("()");
4380 g_variant_ref_sink (parameters);
4384 g_variant_ref (parameters);
4387 /* Check that the incoming args are of the right type - if they are not, return
4388 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4390 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4391 if (!g_variant_is_of_type (parameters, in_type))
4395 type_string = g_variant_type_dup_string (in_type);
4397 reply = g_dbus_message_new_method_error (message,
4398 "org.freedesktop.DBus.Error.InvalidArgs",
4399 _("Type of message, `%s', does not match expected type `%s'"),
4400 g_variant_get_type_string (parameters),
4402 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4403 g_variant_type_free (in_type);
4404 g_variant_unref (parameters);
4405 g_object_unref (reply);
4406 g_free (type_string);
4410 g_variant_type_free (in_type);
4412 /* schedule the call in idle */
4413 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4414 g_dbus_message_get_path (message),
4415 g_dbus_message_get_interface (message),
4416 g_dbus_message_get_member (message),
4422 g_variant_unref (parameters);
4424 /* TODO: would be nicer with a real MethodData like we already
4425 * have PropertyData and PropertyGetAllData... */
4426 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4427 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4428 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4430 idle_source = g_idle_source_new ();
4431 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4432 g_source_set_callback (idle_source,
4436 g_source_attach (idle_source, main_context);
4437 g_source_unref (idle_source);
4445 /* ---------------------------------------------------------------------------------------------------- */
4447 /* called in message handler thread with lock held */
4449 obj_message_func (GDBusConnection *connection,
4451 GDBusMessage *message)
4453 const gchar *interface_name;
4454 const gchar *member;
4455 const gchar *signature;
4460 interface_name = g_dbus_message_get_interface (message);
4461 member = g_dbus_message_get_member (message);
4462 signature = g_dbus_message_get_signature (message);
4464 /* see if we have an interface for handling this call */
4465 if (interface_name != NULL)
4467 ExportedInterface *ei;
4468 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4471 /* we do - invoke the handler in idle in the right thread */
4473 /* handle no vtable or handler being present */
4474 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
4477 handled = validate_and_maybe_schedule_method_call (connection,
4489 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4490 g_strcmp0 (member, "Introspect") == 0 &&
4491 g_strcmp0 (signature, "") == 0)
4493 handled = handle_introspect (connection, eo, message);
4496 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4497 g_strcmp0 (member, "Get") == 0 &&
4498 g_strcmp0 (signature, "ss") == 0)
4500 handled = handle_getset_property (connection, eo, message, TRUE);
4503 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4504 g_strcmp0 (member, "Set") == 0 &&
4505 g_strcmp0 (signature, "ssv") == 0)
4507 handled = handle_getset_property (connection, eo, message, FALSE);
4510 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4511 g_strcmp0 (member, "GetAll") == 0 &&
4512 g_strcmp0 (signature, "s") == 0)
4514 handled = handle_get_all_properties (connection, eo, message);
4523 * g_dbus_connection_register_object:
4524 * @connection: A #GDBusConnection.
4525 * @object_path: The object path to register at.
4526 * @interface_info: Introspection data for the interface.
4527 * @vtable: A #GDBusInterfaceVTable to call into or %NULL.
4528 * @user_data: Data to pass to functions in @vtable.
4529 * @user_data_free_func: Function to call when the object path is unregistered.
4530 * @error: Return location for error or %NULL.
4532 * Registers callbacks for exported objects at @object_path with the
4533 * D-Bus interface that is described in @interface_info.
4535 * Calls to functions in @vtable (and @user_data_free_func) will
4536 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
4537 * loop</link> of the thread you are calling this method from.
4539 * Note that all #GVariant values passed to functions in @vtable will match
4540 * the signature given in @interface_info - if a remote caller passes
4541 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
4542 * is returned to the remote caller.
4544 * Additionally, if the remote caller attempts to invoke methods or
4545 * access properties not mentioned in @interface_info the
4546 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
4547 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
4548 * are returned to the caller.
4550 * It is considered a programming error if the
4551 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
4552 * #GVariant of incorrect type.
4554 * If an existing callback is already registered at @object_path and
4555 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
4557 * GDBus automatically implements the standard D-Bus interfaces
4558 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
4559 * and org.freedesktop.Peer, so you don't have to implement those for
4560 * the objects you export. You <emphasis>can</emphasis> implement
4561 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
4562 * and setting of properties asynchronously.
4564 * Note that the reference count on @interface_info will be
4565 * incremented by 1 (unless allocated statically, e.g. if the
4566 * reference count is -1, see g_dbus_interface_info_ref()) for as long
4567 * as the object is exported. Also note that @vtable will be copied.
4569 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
4571 * Returns: 0 if @error is set, otherwise a registration id (never 0)
4572 * that can be used with g_dbus_connection_unregister_object() .
4577 g_dbus_connection_register_object (GDBusConnection *connection,
4578 const gchar *object_path,
4579 GDBusInterfaceInfo *interface_info,
4580 const GDBusInterfaceVTable *vtable,
4582 GDestroyNotify user_data_free_func,
4586 ExportedInterface *ei;
4589 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4590 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4591 g_return_val_if_fail (interface_info != NULL, 0);
4592 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
4593 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4597 CONNECTION_LOCK (connection);
4599 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
4602 eo = g_new0 (ExportedObject, 1);
4603 eo->object_path = g_strdup (object_path);
4604 eo->connection = connection;
4605 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
4608 (GDestroyNotify) exported_interface_free);
4609 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
4612 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
4618 _("An object is already exported for the interface %s at %s"),
4619 interface_info->name,
4624 ei = g_new0 (ExportedInterface, 1);
4625 ei->id = _global_registration_id++; /* TODO: overflow etc. */
4627 ei->user_data = user_data;
4628 ei->user_data_free_func = user_data_free_func;
4629 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
4630 ei->interface_info = g_dbus_interface_info_ref (interface_info);
4631 ei->interface_name = g_strdup (interface_info->name);
4632 ei->context = g_main_context_get_thread_default ();
4633 if (ei->context != NULL)
4634 g_main_context_ref (ei->context);
4636 g_hash_table_insert (eo->map_if_name_to_ei,
4637 (gpointer) ei->interface_name,
4639 g_hash_table_insert (connection->map_id_to_ei,
4640 GUINT_TO_POINTER (ei->id),
4646 CONNECTION_UNLOCK (connection);
4652 * g_dbus_connection_unregister_object:
4653 * @connection: A #GDBusConnection.
4654 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
4656 * Unregisters an object.
4658 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
4663 g_dbus_connection_unregister_object (GDBusConnection *connection,
4664 guint registration_id)
4666 ExportedInterface *ei;
4670 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4674 CONNECTION_LOCK (connection);
4676 ei = g_hash_table_lookup (connection->map_id_to_ei,
4677 GUINT_TO_POINTER (registration_id));
4683 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
4684 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
4685 /* unregister object path if we have no more exported interfaces */
4686 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
4687 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
4693 CONNECTION_UNLOCK (connection);
4698 /* ---------------------------------------------------------------------------------------------------- */
4701 * g_dbus_connection_emit_signal:
4702 * @connection: A #GDBusConnection.
4703 * @destination_bus_name: The unique bus name for the destination for the signal or %NULL to emit to all listeners.
4704 * @object_path: Path of remote object.
4705 * @interface_name: D-Bus interface to emit a signal on.
4706 * @signal_name: The name of the signal to emit.
4707 * @parameters: A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
4708 * @error: Return location for error or %NULL.
4712 * If the parameters GVariant is floating, it is consumed.
4714 * This can only fail if @parameters is not compatible with the D-Bus protocol.
4716 * Returns: %TRUE unless @error is set.
4721 g_dbus_connection_emit_signal (GDBusConnection *connection,
4722 const gchar *destination_bus_name,
4723 const gchar *object_path,
4724 const gchar *interface_name,
4725 const gchar *signal_name,
4726 GVariant *parameters,
4729 GDBusMessage *message;
4735 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4736 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
4737 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
4738 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
4739 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
4740 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
4742 if (G_UNLIKELY (_g_dbus_debug_emission ()))
4744 _g_dbus_debug_print_lock ();
4745 g_print ("========================================================================\n"
4746 "GDBus-debug:Emission:\n"
4747 " >>>> SIGNAL EMISSION %s.%s()\n"
4749 " destination %s\n",
4750 interface_name, signal_name,
4752 destination_bus_name != NULL ? destination_bus_name : "(none)");
4753 _g_dbus_debug_print_unlock ();
4756 message = g_dbus_message_new_signal (object_path,
4760 if (destination_bus_name != NULL)
4761 g_dbus_message_set_header (message,
4762 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
4763 g_variant_new_string (destination_bus_name));
4765 if (parameters != NULL)
4766 g_dbus_message_set_body (message, parameters);
4768 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
4769 g_object_unref (message);
4775 add_call_flags (GDBusMessage *message,
4776 GDBusCallFlags flags)
4778 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
4779 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
4783 decode_method_reply (GDBusMessage *reply,
4784 const gchar *method_name,
4785 const GVariantType *reply_type,
4791 switch (g_dbus_message_get_message_type (reply))
4793 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
4794 result = g_dbus_message_get_body (reply);
4797 result = g_variant_new ("()");
4798 g_variant_ref_sink (result);
4802 g_variant_ref (result);
4805 if (!g_variant_is_of_type (result, reply_type))
4807 gchar *type_string = g_variant_type_dup_string (reply_type);
4811 G_IO_ERROR_INVALID_ARGUMENT,
4812 _("Method `%s' returned type `%s', but expected `%s'"),
4813 method_name, g_variant_get_type_string (result), type_string);
4815 g_variant_unref (result);
4816 g_free (type_string);
4821 case G_DBUS_MESSAGE_TYPE_ERROR:
4822 g_dbus_message_to_gerror (reply, error);
4826 g_assert_not_reached ();
4836 GSimpleAsyncResult *simple;
4837 GVariantType *reply_type;
4838 gchar *method_name; /* for error message */
4843 g_dbus_connection_call_done (GObject *source,
4844 GAsyncResult *result,
4847 GDBusConnection *connection = G_DBUS_CONNECTION (source);
4848 CallState *state = user_data;
4850 GDBusMessage *reply;
4854 reply = g_dbus_connection_send_message_with_reply_finish (connection,
4858 if (G_UNLIKELY (_g_dbus_debug_call ()))
4860 _g_dbus_debug_print_lock ();
4861 g_print ("========================================================================\n"
4862 "GDBus-debug:Call:\n"
4863 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
4869 g_print ("SUCCESS\n");
4873 g_print ("FAILED: %s\n",
4876 _g_dbus_debug_print_unlock ();
4882 value = decode_method_reply (reply, state->method_name,
4883 state->reply_type, &error);
4884 g_object_unref (reply);
4891 g_simple_async_result_set_from_error (state->simple, error);
4892 g_error_free (error);
4895 g_simple_async_result_set_op_res_gpointer (state->simple, value,
4896 (GDestroyNotify) g_variant_unref);
4898 g_simple_async_result_complete (state->simple);
4899 g_variant_type_free (state->reply_type);
4900 g_object_unref (state->simple);
4901 g_free (state->method_name);
4903 g_slice_free (CallState, state);
4907 * g_dbus_connection_call:
4908 * @connection: A #GDBusConnection.
4909 * @bus_name: A unique or well-known bus name or %NULL if @connection is not a message bus connection.
4910 * @object_path: Path of remote object.
4911 * @interface_name: D-Bus interface to invoke method on.
4912 * @method_name: The name of the method to invoke.
4913 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4914 * @reply_type: The expected type of the reply, or %NULL.
4915 * @flags: Flags from the #GDBusCallFlags enumeration.
4916 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4917 * @cancellable: A #GCancellable or %NULL.
4918 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
4919 * care about the result of the method invocation.
4920 * @user_data: The data to pass to @callback.
4922 * Asynchronously invokes the @method_name method on the
4923 * @interface_name D-Bus interface on the remote object at
4924 * @object_path owned by @bus_name.
4926 * If @connection is closed then the operation will fail with
4927 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
4928 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
4929 * not compatible with the D-Bus protocol, the operation fails with
4930 * %G_IO_ERROR_INVALID_ARGUMENT.
4932 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
4933 * error will be raised if it does not match. Said another way, if you give a @reply_type
4934 * then any non-%NULL return value will be of this type.
4936 * If the @parameters #GVariant is floating, it is consumed. This allows
4937 * convenient 'inline' use of g_variant_new(), e.g.:
4939 * g_dbus_connection_call (connection,
4940 * "org.freedesktop.StringThings",
4941 * "/org/freedesktop/StringThings",
4942 * "org.freedesktop.StringThings",
4944 * g_variant_new ("(ss)",
4948 * G_DBUS_CALL_FLAGS_NONE,
4951 * (GAsyncReadyCallback) two_strings_done,
4955 * This is an asynchronous method. When the operation is finished, @callback will be invoked
4956 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
4957 * of the thread you are calling this method from. You can then call
4958 * g_dbus_connection_call_finish() to get the result of the operation.
4959 * See g_dbus_connection_call_sync() for the synchronous version of this
4965 g_dbus_connection_call (GDBusConnection *connection,
4966 const gchar *bus_name,
4967 const gchar *object_path,
4968 const gchar *interface_name,
4969 const gchar *method_name,
4970 GVariant *parameters,
4971 const GVariantType *reply_type,
4972 GDBusCallFlags flags,
4974 GCancellable *cancellable,
4975 GAsyncReadyCallback callback,
4978 GDBusMessage *message;
4981 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4982 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
4983 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
4984 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
4985 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
4986 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
4987 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
4989 state = g_slice_new (CallState);
4990 state->simple = g_simple_async_result_new (G_OBJECT (connection),
4991 callback, user_data,
4992 g_dbus_connection_call);
4993 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
4995 if (reply_type == NULL)
4996 reply_type = G_VARIANT_TYPE_ANY;
4998 state->reply_type = g_variant_type_copy (reply_type);
5000 message = g_dbus_message_new_method_call (bus_name,
5004 add_call_flags (message, flags);
5005 if (parameters != NULL)
5006 g_dbus_message_set_body (message, parameters);
5008 g_dbus_connection_send_message_with_reply (connection,
5010 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5014 g_dbus_connection_call_done,
5017 if (G_UNLIKELY (_g_dbus_debug_call ()))
5019 _g_dbus_debug_print_lock ();
5020 g_print ("========================================================================\n"
5021 "GDBus-debug:Call:\n"
5022 " >>>> ASYNC %s.%s()\n"
5024 " owned by name %s (serial %d)\n",
5028 bus_name != NULL ? bus_name : "(none)",
5030 _g_dbus_debug_print_unlock ();
5033 if (message != NULL)
5034 g_object_unref (message);
5038 * g_dbus_connection_call_finish:
5039 * @connection: A #GDBusConnection.
5040 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
5041 * @error: Return location for error or %NULL.
5043 * Finishes an operation started with g_dbus_connection_call().
5045 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5046 * return values. Free with g_variant_unref().
5051 g_dbus_connection_call_finish (GDBusConnection *connection,
5055 GSimpleAsyncResult *simple;
5057 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5058 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
5059 g_dbus_connection_call), NULL);
5060 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5062 simple = G_SIMPLE_ASYNC_RESULT (res);
5064 if (g_simple_async_result_propagate_error (simple, error))
5067 return g_variant_ref (g_simple_async_result_get_op_res_gpointer (simple));
5070 /* ---------------------------------------------------------------------------------------------------- */
5073 * g_dbus_connection_call_sync:
5074 * @connection: A #GDBusConnection.
5075 * @bus_name: A unique or well-known bus name.
5076 * @object_path: Path of remote object.
5077 * @interface_name: D-Bus interface to invoke method on.
5078 * @method_name: The name of the method to invoke.
5079 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
5080 * @reply_type: The expected type of the reply, or %NULL.
5081 * @flags: Flags from the #GDBusCallFlags enumeration.
5082 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
5083 * @cancellable: A #GCancellable or %NULL.
5084 * @error: Return location for error or %NULL.
5086 * Synchronously invokes the @method_name method on the
5087 * @interface_name D-Bus interface on the remote object at
5088 * @object_path owned by @bus_name.
5090 * If @connection is closed then the operation will fail with
5091 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
5092 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
5093 * contains a value not compatible with the D-Bus protocol, the operation
5094 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
5096 * If @reply_type is non-%NULL then the reply will be checked for having
5097 * this type and an error will be raised if it does not match. Said
5098 * another way, if you give a @reply_type then any non-%NULL return
5099 * value will be of this type.
5101 * If the @parameters #GVariant is floating, it is consumed.
5102 * This allows convenient 'inline' use of g_variant_new(), e.g.:
5104 * g_dbus_connection_call_sync (connection,
5105 * "org.freedesktop.StringThings",
5106 * "/org/freedesktop/StringThings",
5107 * "org.freedesktop.StringThings",
5109 * g_variant_new ("(ss)",
5113 * G_DBUS_CALL_FLAGS_NONE,
5119 * The calling thread is blocked until a reply is received. See
5120 * g_dbus_connection_call() for the asynchronous version of
5123 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5124 * return values. Free with g_variant_unref().
5129 g_dbus_connection_call_sync (GDBusConnection *connection,
5130 const gchar *bus_name,
5131 const gchar *object_path,
5132 const gchar *interface_name,
5133 const gchar *method_name,
5134 GVariant *parameters,
5135 const GVariantType *reply_type,
5136 GDBusCallFlags flags,
5138 GCancellable *cancellable,
5141 GDBusMessage *message;
5142 GDBusMessage *reply;
5144 GError *local_error;
5150 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5151 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5152 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5153 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5154 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5155 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5156 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5158 if (reply_type == NULL)
5159 reply_type = G_VARIANT_TYPE_ANY;
5161 message = g_dbus_message_new_method_call (bus_name,
5165 add_call_flags (message, flags);
5166 if (parameters != NULL)
5167 g_dbus_message_set_body (message, parameters);
5169 if (G_UNLIKELY (_g_dbus_debug_call ()))
5171 _g_dbus_debug_print_lock ();
5172 g_print ("========================================================================\n"
5173 "GDBus-debug:Call:\n"
5174 " >>>> SYNC %s.%s()\n"
5176 " owned by name %s\n",
5180 bus_name != NULL ? bus_name : "(none)");
5181 _g_dbus_debug_print_unlock ();
5185 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5187 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5189 NULL, /* volatile guint32 *out_serial */
5193 if (G_UNLIKELY (_g_dbus_debug_call ()))
5195 _g_dbus_debug_print_lock ();
5196 g_print ("========================================================================\n"
5197 "GDBus-debug:Call:\n"
5198 " <<<< SYNC COMPLETE %s.%s()\n"
5204 g_print ("SUCCESS\n");
5208 g_print ("FAILED: %s\n",
5209 local_error->message);
5211 _g_dbus_debug_print_unlock ();
5217 *error = local_error;
5219 g_error_free (local_error);
5223 result = decode_method_reply (reply, method_name, reply_type, error);
5226 if (message != NULL)
5227 g_object_unref (message);
5229 g_object_unref (reply);
5234 /* ---------------------------------------------------------------------------------------------------- */
5236 struct ExportedSubtree
5240 GDBusConnection *connection;
5241 GDBusSubtreeVTable *vtable;
5242 GDBusSubtreeFlags flags;
5244 GMainContext *context;
5246 GDestroyNotify user_data_free_func;
5250 exported_subtree_free (ExportedSubtree *es)
5252 if (es->user_data_free_func != NULL)
5253 /* TODO: push to thread-default mainloop */
5254 es->user_data_free_func (es->user_data);
5256 if (es->context != NULL)
5257 g_main_context_unref (es->context);
5259 _g_dbus_subtree_vtable_free (es->vtable);
5260 g_free (es->object_path);
5264 /* called without lock held */
5266 handle_subtree_introspect (GDBusConnection *connection,
5267 ExportedSubtree *es,
5268 GDBusMessage *message)
5272 GDBusMessage *reply;
5275 const gchar *sender;
5276 const gchar *requested_object_path;
5277 const gchar *requested_node;
5278 GDBusInterfaceInfo **interfaces;
5280 gchar **subnode_paths;
5284 requested_object_path = g_dbus_message_get_path (message);
5285 sender = g_dbus_message_get_sender (message);
5286 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5288 s = g_string_new (NULL);
5289 introspect_append_header (s);
5291 /* Strictly we don't need the children in dynamic mode, but we avoid the
5292 * conditionals to preserve code clarity
5294 children = es->vtable->enumerate (es->connection,
5301 requested_node = strrchr (requested_object_path, '/') + 1;
5303 /* Assert existence of object if we are not dynamic */
5304 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
5305 !_g_strv_has_string ((const gchar * const *) children, requested_node))
5310 requested_node = NULL;
5313 interfaces = es->vtable->introspect (es->connection,
5318 if (interfaces != NULL)
5320 introspect_append_standard_interfaces (s);
5322 for (n = 0; interfaces[n] != NULL; n++)
5324 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
5325 g_dbus_interface_info_unref (interfaces[n]);
5327 g_free (interfaces);
5330 /* then include <node> entries from the Subtree for the root */
5333 for (n = 0; children != NULL && children[n] != NULL; n++)
5334 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
5337 /* finally include nodes registered below us */
5338 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
5339 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
5340 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
5341 g_strfreev (subnode_paths);
5343 g_string_append (s, "</node>\n");
5345 reply = g_dbus_message_new_method_reply (message);
5346 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5347 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5348 g_object_unref (reply);
5353 g_string_free (s, TRUE);
5354 g_strfreev (children);
5358 /* called without lock held */
5360 handle_subtree_method_invocation (GDBusConnection *connection,
5361 ExportedSubtree *es,
5362 GDBusMessage *message)
5365 const gchar *sender;
5366 const gchar *interface_name;
5367 const gchar *member;
5368 const gchar *signature;
5369 const gchar *requested_object_path;
5370 const gchar *requested_node;
5372 GDBusInterfaceInfo *interface_info;
5373 const GDBusInterfaceVTable *interface_vtable;
5374 gpointer interface_user_data;
5376 GDBusInterfaceInfo **interfaces;
5377 gboolean is_property_get;
5378 gboolean is_property_set;
5379 gboolean is_property_get_all;
5384 requested_object_path = g_dbus_message_get_path (message);
5385 sender = g_dbus_message_get_sender (message);
5386 interface_name = g_dbus_message_get_interface (message);
5387 member = g_dbus_message_get_member (message);
5388 signature = g_dbus_message_get_signature (message);
5389 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5391 is_property_get = FALSE;
5392 is_property_set = FALSE;
5393 is_property_get_all = FALSE;
5394 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
5396 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
5397 is_property_get = TRUE;
5398 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
5399 is_property_set = TRUE;
5400 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
5401 is_property_get_all = TRUE;
5406 requested_node = strrchr (requested_object_path, '/') + 1;
5408 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
5410 /* We don't want to dispatch to unenumerated
5411 * nodes, so ensure that the child exists.
5416 children = es->vtable->enumerate (es->connection,
5421 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
5422 g_strfreev (children);
5430 requested_node = NULL;
5433 /* get introspection data for the node */
5434 interfaces = es->vtable->introspect (es->connection,
5436 requested_object_path,
5440 if (interfaces == NULL)
5443 interface_info = NULL;
5444 for (n = 0; interfaces[n] != NULL; n++)
5446 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
5447 interface_info = interfaces[n];
5450 /* dispatch the call if the user wants to handle it */
5451 if (interface_info != NULL)
5453 /* figure out where to dispatch the method call */
5454 interface_user_data = NULL;
5455 interface_vtable = es->vtable->dispatch (es->connection,
5460 &interface_user_data,
5462 if (interface_vtable == NULL)
5465 CONNECTION_LOCK (connection);
5466 handled = validate_and_maybe_schedule_method_call (es->connection,
5473 interface_user_data);
5474 CONNECTION_UNLOCK (connection);
5476 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
5477 else if (is_property_get || is_property_set || is_property_get_all)
5479 if (is_property_get)
5480 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
5481 else if (is_property_set)
5482 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
5483 else if (is_property_get_all)
5484 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
5486 g_assert_not_reached ();
5488 /* see if the object supports this interface at all */
5489 for (n = 0; interfaces[n] != NULL; n++)
5491 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
5492 interface_info = interfaces[n];
5495 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
5496 * claims it won't support the interface
5498 if (interface_info == NULL)
5500 GDBusMessage *reply;
5501 reply = g_dbus_message_new_method_error (message,
5502 "org.freedesktop.DBus.Error.InvalidArgs",
5503 _("No such interface `%s'"),
5505 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5506 g_object_unref (reply);
5511 /* figure out where to dispatch the property get/set/getall calls */
5512 interface_user_data = NULL;
5513 interface_vtable = es->vtable->dispatch (es->connection,
5518 &interface_user_data,
5520 if (interface_vtable == NULL)
5522 g_warning ("The subtree introspection function indicates that '%s' "
5523 "is a valid interface name, but calling the dispatch "
5524 "function on that interface gave us NULL", interface_name);
5528 if (is_property_get || is_property_set)
5530 CONNECTION_LOCK (connection);
5531 handled = validate_and_maybe_schedule_property_getset (es->connection,
5539 interface_user_data);
5540 CONNECTION_UNLOCK (connection);
5542 else if (is_property_get_all)
5544 CONNECTION_LOCK (connection);
5545 handled = validate_and_maybe_schedule_property_get_all (es->connection,
5552 interface_user_data);
5553 CONNECTION_UNLOCK (connection);
5558 if (interfaces != NULL)
5560 for (n = 0; interfaces[n] != NULL; n++)
5561 g_dbus_interface_info_unref (interfaces[n]);
5562 g_free (interfaces);
5570 GDBusMessage *message;
5571 ExportedSubtree *es;
5572 } SubtreeDeferredData;
5575 subtree_deferred_data_free (SubtreeDeferredData *data)
5577 g_object_unref (data->message);
5581 /* called without lock held in the thread where the caller registered the subtree */
5583 process_subtree_vtable_message_in_idle_cb (gpointer _data)
5585 SubtreeDeferredData *data = _data;
5590 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
5591 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
5592 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
5593 handled = handle_subtree_introspect (data->es->connection,
5597 handled = handle_subtree_method_invocation (data->es->connection,
5603 CONNECTION_LOCK (data->es->connection);
5604 handled = handle_generic_unlocked (data->es->connection, data->message);
5605 CONNECTION_UNLOCK (data->es->connection);
5608 /* if we couldn't handle the request, just bail with the UnknownMethod error */
5611 GDBusMessage *reply;
5612 reply = g_dbus_message_new_method_error (data->message,
5613 "org.freedesktop.DBus.Error.UnknownMethod",
5614 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
5615 g_dbus_message_get_member (data->message),
5616 g_dbus_message_get_interface (data->message),
5617 g_dbus_message_get_signature (data->message));
5618 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5619 g_object_unref (reply);
5625 /* called in message handler thread with lock held */
5627 subtree_message_func (GDBusConnection *connection,
5628 ExportedSubtree *es,
5629 GDBusMessage *message)
5631 GSource *idle_source;
5632 SubtreeDeferredData *data;
5634 data = g_new0 (SubtreeDeferredData, 1);
5635 data->message = g_object_ref (message);
5638 /* defer this call to an idle handler in the right thread */
5639 idle_source = g_idle_source_new ();
5640 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
5641 g_source_set_callback (idle_source,
5642 process_subtree_vtable_message_in_idle_cb,
5644 (GDestroyNotify) subtree_deferred_data_free);
5645 g_source_attach (idle_source, es->context);
5646 g_source_unref (idle_source);
5648 /* since we own the entire subtree, handlers for objects not in the subtree have been
5649 * tried already by libdbus-1 - so we just need to ensure that we're always going
5650 * to reply to the message
5656 * g_dbus_connection_register_subtree:
5657 * @connection: A #GDBusConnection.
5658 * @object_path: The object path to register the subtree at.
5659 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
5660 * @flags: Flags used to fine tune the behavior of the subtree.
5661 * @user_data: Data to pass to functions in @vtable.
5662 * @user_data_free_func: Function to call when the subtree is unregistered.
5663 * @error: Return location for error or %NULL.
5665 * Registers a whole subtree of <quote>dynamic</quote> objects.
5667 * The @enumerate and @introspection functions in @vtable are used to
5668 * convey, to remote callers, what nodes exist in the subtree rooted
5671 * When handling remote calls into any node in the subtree, first the
5672 * @enumerate function is used to check if the node exists. If the node exists
5673 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
5674 * the @introspection function is used to check if the node supports the
5675 * requested method. If so, the @dispatch function is used to determine
5676 * where to dispatch the call. The collected #GDBusInterfaceVTable and
5677 * #gpointer will be used to call into the interface vtable for processing
5680 * All calls into user-provided code will be invoked in the <link
5681 * linkend="g-main-context-push-thread-default">thread-default main
5682 * loop</link> of the thread you are calling this method from.
5684 * If an existing subtree is already registered at @object_path or
5685 * then @error is set to #G_IO_ERROR_EXISTS.
5687 * Note that it is valid to register regular objects (using
5688 * g_dbus_connection_register_object()) in a subtree registered with
5689 * g_dbus_connection_register_subtree() - if so, the subtree handler
5690 * is tried as the last resort. One way to think about a subtree
5691 * handler is to consider it a <quote>fallback handler</quote>
5692 * for object paths not registered via g_dbus_connection_register_object()
5693 * or other bindings.
5695 * Note that @vtable will be copied so you cannot change it after
5698 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
5700 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
5701 * that can be used with g_dbus_connection_unregister_subtree() .
5706 g_dbus_connection_register_subtree (GDBusConnection *connection,
5707 const gchar *object_path,
5708 const GDBusSubtreeVTable *vtable,
5709 GDBusSubtreeFlags flags,
5711 GDestroyNotify user_data_free_func,
5715 ExportedSubtree *es;
5717 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5718 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5719 g_return_val_if_fail (vtable != NULL, 0);
5720 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5724 CONNECTION_LOCK (connection);
5726 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
5732 _("A subtree is already exported for %s"),
5737 es = g_new0 (ExportedSubtree, 1);
5738 es->object_path = g_strdup (object_path);
5739 es->connection = connection;
5741 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
5743 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
5744 es->user_data = user_data;
5745 es->user_data_free_func = user_data_free_func;
5746 es->context = g_main_context_get_thread_default ();
5747 if (es->context != NULL)
5748 g_main_context_ref (es->context);
5750 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
5751 g_hash_table_insert (connection->map_id_to_es,
5752 GUINT_TO_POINTER (es->id),
5758 CONNECTION_UNLOCK (connection);
5763 /* ---------------------------------------------------------------------------------------------------- */
5766 * g_dbus_connection_unregister_subtree:
5767 * @connection: A #GDBusConnection.
5768 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
5770 * Unregisters a subtree.
5772 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
5777 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
5778 guint registration_id)
5780 ExportedSubtree *es;
5783 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5787 CONNECTION_LOCK (connection);
5789 es = g_hash_table_lookup (connection->map_id_to_es,
5790 GUINT_TO_POINTER (registration_id));
5794 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
5795 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
5800 CONNECTION_UNLOCK (connection);
5805 /* ---------------------------------------------------------------------------------------------------- */
5807 /* must be called with lock held */
5809 handle_generic_ping_unlocked (GDBusConnection *connection,
5810 const gchar *object_path,
5811 GDBusMessage *message)
5813 GDBusMessage *reply;
5814 reply = g_dbus_message_new_method_reply (message);
5815 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5816 g_object_unref (reply);
5819 /* must be called with lock held */
5821 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
5822 const gchar *object_path,
5823 GDBusMessage *message)
5825 GDBusMessage *reply;
5828 if (connection->machine_id == NULL)
5833 connection->machine_id = _g_dbus_get_machine_id (&error);
5834 if (connection->machine_id == NULL)
5836 reply = g_dbus_message_new_method_error_literal (message,
5837 "org.freedesktop.DBus.Error.Failed",
5839 g_error_free (error);
5845 reply = g_dbus_message_new_method_reply (message);
5846 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
5848 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5849 g_object_unref (reply);
5852 /* must be called with lock held */
5854 handle_generic_introspect_unlocked (GDBusConnection *connection,
5855 const gchar *object_path,
5856 GDBusMessage *message)
5861 GDBusMessage *reply;
5863 /* first the header */
5864 s = g_string_new (NULL);
5865 introspect_append_header (s);
5867 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
5868 for (n = 0; registered != NULL && registered[n] != NULL; n++)
5869 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
5870 g_strfreev (registered);
5871 g_string_append (s, "</node>\n");
5873 reply = g_dbus_message_new_method_reply (message);
5874 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5875 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5876 g_object_unref (reply);
5877 g_string_free (s, TRUE);
5880 /* must be called with lock held */
5882 handle_generic_unlocked (GDBusConnection *connection,
5883 GDBusMessage *message)
5886 const gchar *interface_name;
5887 const gchar *member;
5888 const gchar *signature;
5891 CONNECTION_ENSURE_LOCK (connection);
5895 interface_name = g_dbus_message_get_interface (message);
5896 member = g_dbus_message_get_member (message);
5897 signature = g_dbus_message_get_signature (message);
5898 path = g_dbus_message_get_path (message);
5900 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5901 g_strcmp0 (member, "Introspect") == 0 &&
5902 g_strcmp0 (signature, "") == 0)
5904 handle_generic_introspect_unlocked (connection, path, message);
5907 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5908 g_strcmp0 (member, "Ping") == 0 &&
5909 g_strcmp0 (signature, "") == 0)
5911 handle_generic_ping_unlocked (connection, path, message);
5914 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5915 g_strcmp0 (member, "GetMachineId") == 0 &&
5916 g_strcmp0 (signature, "") == 0)
5918 handle_generic_get_machine_id_unlocked (connection, path, message);
5925 /* ---------------------------------------------------------------------------------------------------- */
5927 /* called in message handler thread with lock held */
5929 distribute_method_call (GDBusConnection *connection,
5930 GDBusMessage *message)
5932 GDBusMessage *reply;
5934 ExportedSubtree *es;
5935 const gchar *object_path;
5936 const gchar *interface_name;
5937 const gchar *member;
5938 const gchar *signature;
5940 gchar *subtree_path;
5943 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
5945 interface_name = g_dbus_message_get_interface (message);
5946 member = g_dbus_message_get_member (message);
5947 signature = g_dbus_message_get_signature (message);
5948 path = g_dbus_message_get_path (message);
5949 subtree_path = g_strdup (path);
5950 needle = strrchr (subtree_path, '/');
5951 if (needle != NULL && needle != subtree_path)
5957 g_free (subtree_path);
5958 subtree_path = NULL;
5962 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
5964 _g_dbus_debug_print_lock ();
5965 g_print ("========================================================================\n"
5966 "GDBus-debug:Incoming:\n"
5967 " <<<< METHOD INVOCATION %s.%s()\n"
5969 " invoked by name %s\n"
5971 interface_name, member,
5973 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
5974 g_dbus_message_get_serial (message));
5975 _g_dbus_debug_print_unlock ();
5979 g_debug ("interface = `%s'", interface_name);
5980 g_debug ("member = `%s'", member);
5981 g_debug ("signature = `%s'", signature);
5982 g_debug ("path = `%s'", path);
5983 g_debug ("subtree_path = `%s'", subtree_path != NULL ? subtree_path : "N/A");
5986 object_path = g_dbus_message_get_path (message);
5987 g_assert (object_path != NULL);
5989 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5992 if (obj_message_func (connection, eo, message))
5996 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
5999 if (subtree_message_func (connection, es, message))
6003 if (subtree_path != NULL)
6005 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
6008 if (subtree_message_func (connection, es, message))
6013 if (handle_generic_unlocked (connection, message))
6016 /* if we end up here, the message has not been not handled - so return an error saying this */
6017 reply = g_dbus_message_new_method_error (message,
6018 "org.freedesktop.DBus.Error.UnknownMethod",
6019 _("No such interface `%s' on object at path %s"),
6022 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6023 g_object_unref (reply);
6026 g_free (subtree_path);
6029 /* ---------------------------------------------------------------------------------------------------- */
6031 static GDBusConnection **
6032 message_bus_get_singleton (GBusType bus_type,
6035 GDBusConnection **ret;
6036 const gchar *starter_bus;
6042 case G_BUS_TYPE_SESSION:
6043 ret = &the_session_bus;
6046 case G_BUS_TYPE_SYSTEM:
6047 ret = &the_system_bus;
6050 case G_BUS_TYPE_STARTER:
6051 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
6052 if (g_strcmp0 (starter_bus, "session") == 0)
6054 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
6057 else if (g_strcmp0 (starter_bus, "system") == 0)
6059 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
6064 if (starter_bus != NULL)
6068 G_IO_ERROR_INVALID_ARGUMENT,
6069 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
6070 " - unknown value `%s'"),
6075 g_set_error_literal (error,
6077 G_IO_ERROR_INVALID_ARGUMENT,
6078 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
6079 "variable is not set"));
6085 g_assert_not_reached ();
6093 static GDBusConnection *
6094 get_uninitialized_connection (GBusType bus_type,
6095 GCancellable *cancellable,
6098 GDBusConnection **singleton;
6099 GDBusConnection *ret;
6103 G_LOCK (message_bus_lock);
6104 singleton = message_bus_get_singleton (bus_type, error);
6105 if (singleton == NULL)
6108 if (*singleton == NULL)
6111 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
6112 if (address == NULL)
6114 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
6116 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
6117 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
6118 "exit-on-close", TRUE,
6124 ret = g_object_ref (*singleton);
6127 g_assert (ret != NULL);
6130 G_UNLOCK (message_bus_lock);
6136 * @bus_type: A #GBusType.
6137 * @cancellable: A #GCancellable or %NULL.
6138 * @error: Return location for error or %NULL.
6140 * Synchronously connects to the message bus specified by @bus_type.
6141 * Note that the returned object may shared with other callers,
6142 * e.g. if two separate parts of a process calls this function with
6143 * the same @bus_type, they will share the same object.
6145 * This is a synchronous failable function. See g_bus_get() and
6146 * g_bus_get_finish() for the asynchronous version.
6148 * The returned object is a singleton, that is, shared with other
6149 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6150 * event that you need a private message bus connection, use
6151 * g_dbus_address_get_for_bus_sync() and
6152 * g_dbus_connection_new_for_address().
6154 * Note that the returned #GDBusConnection object will (usually) have
6155 * the #GDBusConnection:exit-on-close property set to %TRUE.
6157 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6162 g_bus_get_sync (GBusType bus_type,
6163 GCancellable *cancellable,
6166 GDBusConnection *connection;
6168 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6170 connection = get_uninitialized_connection (bus_type, cancellable, error);
6171 if (connection == NULL)
6174 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
6176 g_object_unref (connection);
6185 bus_get_async_initable_cb (GObject *source_object,
6189 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
6193 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
6197 g_assert (error != NULL);
6198 g_simple_async_result_set_from_error (simple, error);
6199 g_error_free (error);
6200 g_object_unref (source_object);
6204 g_simple_async_result_set_op_res_gpointer (simple,
6208 g_simple_async_result_complete_in_idle (simple);
6209 g_object_unref (simple);
6214 * @bus_type: A #GBusType.
6215 * @cancellable: A #GCancellable or %NULL.
6216 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
6217 * @user_data: The data to pass to @callback.
6219 * Asynchronously connects to the message bus specified by @bus_type.
6221 * When the operation is finished, @callback will be invoked. You can
6222 * then call g_bus_get_finish() to get the result of the operation.
6224 * This is a asynchronous failable function. See g_bus_get_sync() for
6225 * the synchronous version.
6230 g_bus_get (GBusType bus_type,
6231 GCancellable *cancellable,
6232 GAsyncReadyCallback callback,
6235 GDBusConnection *connection;
6236 GSimpleAsyncResult *simple;
6239 simple = g_simple_async_result_new (NULL,
6245 connection = get_uninitialized_connection (bus_type, cancellable, &error);
6246 if (connection == NULL)
6248 g_assert (error != NULL);
6249 g_simple_async_result_set_from_error (simple, error);
6250 g_error_free (error);
6251 g_simple_async_result_complete_in_idle (simple);
6252 g_object_unref (simple);
6256 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
6259 bus_get_async_initable_cb,
6266 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
6267 * @error: Return location for error or %NULL.
6269 * Finishes an operation started with g_bus_get().
6271 * The returned object is a singleton, that is, shared with other
6272 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6273 * event that you need a private message bus connection, use
6274 * g_dbus_address_get_for_bus() and
6275 * g_dbus_connection_new_for_address().
6277 * Note that the returned #GDBusConnection object will (usually) have
6278 * the #GDBusConnection:exit-on-close property set to %TRUE.
6280 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6285 g_bus_get_finish (GAsyncResult *res,
6288 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
6290 GDBusConnection *ret;
6292 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6294 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
6298 if (g_simple_async_result_propagate_error (simple, error))
6301 object = g_simple_async_result_get_op_res_gpointer (simple);
6302 g_assert (object != NULL);
6303 ret = g_object_ref (G_DBUS_CONNECTION (object));
6309 /* ---------------------------------------------------------------------------------------------------- */