1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, write to the
17 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18 * Boston, MA 02111-1307, USA.
20 * Author: David Zeuthen <davidz@redhat.com>
26 * - Validate all data (e.g. UTF-8) and check all the required D-Bus headers
27 * are present and forbidden ones aren't
28 * - When writing: g_dbus_message_to_blob()
29 * - When reading: g_dbus_message_new_from_blob()
31 * - would be nice to expose GDBusAuthMechanism and an extension point
33 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
34 * the mechanism VFuncs need to be able to set an error.
36 * - Need to document other mechanisms/sources for determining the D-Bus
37 * address of a well-known bus.
39 * - e.g. on Win32 we need code like from here
41 * http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
43 * that was never copied over here because it originally was copy-paste
44 * from the GPLv2 / AFL 2.1 libdbus sources.
46 * - on OS X we need to look in launchd for the address
48 * https://bugs.freedesktop.org/show_bug.cgi?id=14259
50 * - on X11 we need to look in a X11 property on the X server
51 * - (we can also just use dbus-launch(1) from the D-Bus
54 * - (ideally) this requires D-Bus spec work because none of
55 * this has never really been specced out properly (excect
58 * - Related to the above, we also need to be able to launch a message bus
59 * instance.... Since we don't want to write our own bus daemon we should
60 * launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
62 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
63 * to specify where the nonce is stored. This will allow people to use
64 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
65 * to easily acheive secure RPC via nonce-tcp.
67 * - need to expose an extension point for resolving D-Bus address and
68 * turning them into GIOStream objects. This will allow us to implement
69 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
71 * - see g_dbus_address_connect() in gdbusaddress.c
73 * - would be cute to use kernel-specific APIs to resolve fds for
74 * debug output when using G_DBUS_DEBUG=message, e.g. in addition to
76 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
78 * maybe we can show more information about what fd 21 really is.
79 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
80 * Initial experiments on Linux 2.6 suggests that the symlink looks
85 * e.g. not of much use.
87 * - GDBus High-Level docs
88 * - Proxy: properties, signals...
89 * - Connection: IOStream based, ::close, connection setup steps
90 * mainloop integration, threading
91 * - Differences from libdbus (extend "Migrating from")
92 * - the message handling thread
93 * - Using GVariant instead of GValue
94 * - Explain why the high-level API is a good thing and what
95 * kind of pitfalls it avoids
96 * - Export objects before claiming names
97 * - Talk about auto-starting services (cf. GBusNameWatcherFlags)
104 #include <sys/types.h>
109 #include "gdbusauth.h"
110 #include "gdbusutils.h"
111 #include "gdbusaddress.h"
112 #include "gdbusmessage.h"
113 #include "gdbusconnection.h"
114 #include "gdbuserror.h"
115 #include "gioenumtypes.h"
116 #include "gdbusintrospection.h"
117 #include "gdbusmethodinvocation.h"
118 #include "gdbusprivate.h"
119 #include "gdbusauthobserver.h"
120 #include "gio-marshal.h"
121 #include "ginitable.h"
122 #include "gasyncinitable.h"
123 #include "giostream.h"
124 #include "gasyncresult.h"
125 #include "gsimpleasyncresult.h"
128 #include "gunixconnection.h"
129 #include "gunixfdmessage.h"
132 #include "glibintl.h"
135 * SECTION:gdbusconnection
136 * @short_description: D-Bus Connections
137 * @include: gio/gio.h
139 * The #GDBusConnection type is used for D-Bus connections to remote
140 * peers such as a message buses. It is a low-level API that offers a
141 * lot of flexibility. For instance, it lets you establish a connection
142 * over any transport that can by represented as an #GIOStream.
144 * This class is rarely used directly in D-Bus clients. If you are writing
145 * an D-Bus client, it is often easier to use the g_bus_own_name(),
146 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
148 * <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>
150 * <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>
152 * <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>
154 * <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>
157 /* ---------------------------------------------------------------------------------------------------- */
159 typedef struct _GDBusConnectionClass GDBusConnectionClass;
162 * GDBusConnectionClass:
163 * @closed: Signal class handler for the #GDBusConnection::closed signal.
165 * Class structure for #GDBusConnection.
169 struct _GDBusConnectionClass
172 GObjectClass parent_class;
176 void (*closed) (GDBusConnection *connection,
177 gboolean remote_peer_vanished,
181 G_LOCK_DEFINE_STATIC (message_bus_lock);
183 static GDBusConnection *the_session_bus = NULL;
184 static GDBusConnection *the_system_bus = NULL;
186 /* ---------------------------------------------------------------------------------------------------- */
189 _g_strv_has_string (const gchar* const *haystack,
194 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
196 if (g_strcmp0 (haystack[n], needle) == 0)
202 /* ---------------------------------------------------------------------------------------------------- */
205 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
207 // TODO: for some reason this doesn't work on Windows
208 #define CONNECTION_ENSURE_LOCK(obj) do { \
209 if (G_UNLIKELY (g_mutex_trylock((obj)->lock))) \
211 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
212 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
217 #define CONNECTION_LOCK(obj) do { \
218 g_mutex_lock ((obj)->lock); \
221 #define CONNECTION_UNLOCK(obj) do { \
222 g_mutex_unlock ((obj)->lock); \
228 * The #GDBusConnection structure contains only private data and
229 * should only be accessed using the provided API.
233 struct _GDBusConnection
236 GObject parent_instance;
238 /* ------------------------------------------------------------------------ */
239 /* -- General object state ------------------------------------------------ */
240 /* ------------------------------------------------------------------------ */
242 /* object-wide lock */
245 /* A lock used in the init() method of the GInitable interface - see comments
246 * in initable_init() for why a separate lock is needed
250 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
251 * someone calls org.freedesktop.DBus.GetMachineId()
255 /* The underlying stream used for communication */
258 /* The object used for authentication (if any) */
261 /* Set to TRUE if the connection has been closed */
264 /* Last serial used */
267 /* The object used to send/receive message */
270 /* If connected to a message bus, this contains the unique name assigned to
271 * us by the bus (e.g. ":1.42")
273 gchar *bus_unique_name;
275 /* The GUID returned by the other side if we authenticed as a client or
276 * the GUID to use if authenticating as a server
280 /* set to TRUE exactly when initable_init() has finished running */
281 gboolean is_initialized;
283 /* If the connection could not be established during initable_init(), this GError will set */
284 GError *initialization_error;
286 /* The result of g_main_context_get_thread_default() when the object
287 * was created (the GObject _init() function) - this is used for delivery
288 * of the :closed GObject signal.
290 GMainContext *main_context_at_construction;
292 /* construct properties */
294 GDBusConnectionFlags flags;
296 /* Map used for managing method replies */
297 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
299 /* Maps used for managing signal subscription */
300 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
301 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
302 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
304 /* Maps used for managing exported objects and subtrees */
305 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
306 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
307 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
308 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
310 /* Structure used for message filters */
313 /* Whether to exit on close */
314 gboolean exit_on_close;
316 /* Capabilities negotiated during authentication */
317 GDBusCapabilityFlags capabilities;
319 GDBusAuthObserver *authentication_observer;
320 GCredentials *credentials;
322 /* set to TRUE when finalizing */
326 typedef struct ExportedObject ExportedObject;
327 static void exported_object_free (ExportedObject *eo);
329 typedef struct ExportedSubtree ExportedSubtree;
330 static void exported_subtree_free (ExportedSubtree *es);
348 PROP_CAPABILITY_FLAGS,
349 PROP_AUTHENTICATION_OBSERVER,
352 static void distribute_signals (GDBusConnection *connection,
353 GDBusMessage *message);
355 static void distribute_method_call (GDBusConnection *connection,
356 GDBusMessage *message);
358 static gboolean handle_generic_unlocked (GDBusConnection *connection,
359 GDBusMessage *message);
362 static void purge_all_signal_subscriptions (GDBusConnection *connection);
363 static void purge_all_filters (GDBusConnection *connection);
365 #define _G_ENSURE_LOCK(name) do { \
366 if (G_UNLIKELY (G_TRYLOCK(name))) \
368 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
369 "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
373 static guint signals[LAST_SIGNAL] = { 0 };
375 static void initable_iface_init (GInitableIface *initable_iface);
376 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
378 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
379 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
380 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
384 g_dbus_connection_dispose (GObject *object)
386 GDBusConnection *connection = G_DBUS_CONNECTION (object);
388 G_LOCK (message_bus_lock);
389 //g_debug ("disposing %p", connection);
390 if (connection == the_session_bus)
392 the_session_bus = NULL;
394 else if (connection == the_system_bus)
396 the_system_bus = NULL;
398 if (connection->worker != NULL)
400 _g_dbus_worker_stop (connection->worker);
401 connection->worker = NULL;
403 G_UNLOCK (message_bus_lock);
405 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
406 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
410 g_dbus_connection_finalize (GObject *object)
412 GDBusConnection *connection = G_DBUS_CONNECTION (object);
414 connection->finalizing = TRUE;
416 purge_all_signal_subscriptions (connection);
418 purge_all_filters (connection);
419 g_ptr_array_unref (connection->filters);
421 if (connection->authentication_observer != NULL)
422 g_object_unref (connection->authentication_observer);
424 if (connection->auth != NULL)
425 g_object_unref (connection->auth);
427 if (connection->stream != NULL)
429 /* We don't really care if closing the stream succeeds or not */
430 g_io_stream_close_async (connection->stream,
432 NULL, /* GCancellable */
433 NULL, /* GAsyncReadyCallback */
434 NULL); /* userdata */
435 g_object_unref (connection->stream);
436 connection->stream = NULL;
439 g_free (connection->address);
441 g_free (connection->guid);
442 g_free (connection->bus_unique_name);
444 if (connection->initialization_error != NULL)
445 g_error_free (connection->initialization_error);
447 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
449 g_hash_table_unref (connection->map_rule_to_signal_data);
450 g_hash_table_unref (connection->map_id_to_signal_data);
451 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
453 g_hash_table_unref (connection->map_id_to_ei);
454 g_hash_table_unref (connection->map_object_path_to_eo);
455 g_hash_table_unref (connection->map_id_to_es);
456 g_hash_table_unref (connection->map_object_path_to_es);
458 if (connection->main_context_at_construction != NULL)
459 g_main_context_unref (connection->main_context_at_construction);
461 g_free (connection->machine_id);
463 g_mutex_free (connection->init_lock);
464 g_mutex_free (connection->lock);
466 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
470 g_dbus_connection_get_property (GObject *object,
475 GDBusConnection *connection = G_DBUS_CONNECTION (object);
480 g_value_set_object (value, g_dbus_connection_get_stream (connection));
484 g_value_set_string (value, g_dbus_connection_get_guid (connection));
487 case PROP_UNIQUE_NAME:
488 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
492 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
495 case PROP_EXIT_ON_CLOSE:
496 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
499 case PROP_CAPABILITY_FLAGS:
500 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
504 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
510 g_dbus_connection_set_property (GObject *object,
515 GDBusConnection *connection = G_DBUS_CONNECTION (object);
520 connection->stream = g_value_dup_object (value);
524 connection->guid = g_value_dup_string (value);
528 connection->address = g_value_dup_string (value);
532 connection->flags = g_value_get_flags (value);
535 case PROP_EXIT_ON_CLOSE:
536 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
539 case PROP_AUTHENTICATION_OBSERVER:
540 connection->authentication_observer = g_value_dup_object (value);
544 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
550 g_dbus_connection_real_closed (GDBusConnection *connection,
551 gboolean remote_peer_vanished,
554 if (remote_peer_vanished && connection->exit_on_close)
558 g_print ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
561 g_quark_to_string (error->domain), error->code);
565 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
572 g_dbus_connection_class_init (GDBusConnectionClass *klass)
574 GObjectClass *gobject_class;
576 gobject_class = G_OBJECT_CLASS (klass);
578 gobject_class->finalize = g_dbus_connection_finalize;
579 gobject_class->dispose = g_dbus_connection_dispose;
580 gobject_class->set_property = g_dbus_connection_set_property;
581 gobject_class->get_property = g_dbus_connection_get_property;
583 klass->closed = g_dbus_connection_real_closed;
586 * GDBusConnection:stream:
588 * The underlying #GIOStream used for I/O.
592 g_object_class_install_property (gobject_class,
594 g_param_spec_object ("stream",
596 P_("The underlying streams used for I/O"),
600 G_PARAM_CONSTRUCT_ONLY |
601 G_PARAM_STATIC_NAME |
602 G_PARAM_STATIC_BLURB |
603 G_PARAM_STATIC_NICK));
606 * GDBusConnection:address:
608 * A D-Bus address specifying potential endpoints that can be used
609 * when establishing the connection.
613 g_object_class_install_property (gobject_class,
615 g_param_spec_string ("address",
617 P_("D-Bus address specifying potential socket endpoints"),
620 G_PARAM_CONSTRUCT_ONLY |
621 G_PARAM_STATIC_NAME |
622 G_PARAM_STATIC_BLURB |
623 G_PARAM_STATIC_NICK));
626 * GDBusConnection:flags:
628 * Flags from the #GDBusConnectionFlags enumeration.
632 g_object_class_install_property (gobject_class,
634 g_param_spec_flags ("flags",
637 G_TYPE_DBUS_CONNECTION_FLAGS,
638 G_DBUS_CONNECTION_FLAGS_NONE,
640 G_PARAM_CONSTRUCT_ONLY |
641 G_PARAM_STATIC_NAME |
642 G_PARAM_STATIC_BLURB |
643 G_PARAM_STATIC_NICK));
646 * GDBusConnection:guid:
648 * The GUID of the peer performing the role of server when
651 * If you are constructing a #GDBusConnection and pass
652 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
653 * #GDBusConnection:flags property then you MUST also set this
654 * property to a valid guid.
656 * If you are constructing a #GDBusConnection and pass
657 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
658 * #GDBusConnection:flags property you will be able to read the GUID
659 * of the other peer here after the connection has been successfully
664 g_object_class_install_property (gobject_class,
666 g_param_spec_string ("guid",
668 P_("GUID of the server peer"),
672 G_PARAM_CONSTRUCT_ONLY |
673 G_PARAM_STATIC_NAME |
674 G_PARAM_STATIC_BLURB |
675 G_PARAM_STATIC_NICK));
678 * GDBusConnection:unique-name:
680 * The unique name as assigned by the message bus or %NULL if the
681 * connection is not open or not a message bus connection.
685 g_object_class_install_property (gobject_class,
687 g_param_spec_string ("unique-name",
689 P_("Unique name of bus connection"),
692 G_PARAM_STATIC_NAME |
693 G_PARAM_STATIC_BLURB |
694 G_PARAM_STATIC_NICK));
697 * GDBusConnection:closed:
699 * A boolean specifying whether the connection has been closed.
703 g_object_class_install_property (gobject_class,
705 g_param_spec_boolean ("closed",
707 P_("Whether the connection is closed"),
710 G_PARAM_STATIC_NAME |
711 G_PARAM_STATIC_BLURB |
712 G_PARAM_STATIC_NICK));
715 * GDBusConnection:exit-on-close:
717 * A boolean specifying whether the process will be terminated (by
718 * calling <literal>raise(SIGTERM)</literal>) if the connection
719 * is closed by the remote peer.
723 g_object_class_install_property (gobject_class,
725 g_param_spec_boolean ("exit-on-close",
727 P_("Whether the process is terminated when the connection is closed"),
731 G_PARAM_STATIC_NAME |
732 G_PARAM_STATIC_BLURB |
733 G_PARAM_STATIC_NICK));
736 * GDBusConnection:capabilities:
738 * Flags from the #GDBusCapabilityFlags enumeration
739 * representing connection features negotiated with the other peer.
743 g_object_class_install_property (gobject_class,
744 PROP_CAPABILITY_FLAGS,
745 g_param_spec_flags ("capabilities",
748 G_TYPE_DBUS_CAPABILITY_FLAGS,
749 G_DBUS_CAPABILITY_FLAGS_NONE,
751 G_PARAM_STATIC_NAME |
752 G_PARAM_STATIC_BLURB |
753 G_PARAM_STATIC_NICK));
756 * GDBusConnection:authentication-observer:
758 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
762 g_object_class_install_property (gobject_class,
763 PROP_AUTHENTICATION_OBSERVER,
764 g_param_spec_object ("authentication-observer",
765 P_("Authentication Observer"),
766 P_("Object used to assist in the authentication process"),
767 G_TYPE_DBUS_AUTH_OBSERVER,
769 G_PARAM_CONSTRUCT_ONLY |
770 G_PARAM_STATIC_NAME |
771 G_PARAM_STATIC_BLURB |
772 G_PARAM_STATIC_NICK));
775 * GDBusConnection::closed:
776 * @connection: The #GDBusConnection emitting the signal.
777 * @remote_peer_vanished: %TRUE if @connection is closed because the
778 * remote peer closed its end of the connection.
779 * @error: A #GError with more details about the event or %NULL.
781 * Emitted when the connection is closed.
783 * The cause of this event can be
786 * If g_dbus_connection_close() is called. In this case
787 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
790 * If the remote peer closes the connection. In this case
791 * @remote_peer_vanished is set to %TRUE and @error is set.
794 * If the remote peer sends invalid or malformed data. In this
795 * case @remote_peer_vanished is set to %FALSE and @error
800 * Upon receiving this signal, you should give up your reference to
801 * @connection. You are guaranteed that this signal is emitted only
806 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
807 G_TYPE_DBUS_CONNECTION,
809 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
812 _gio_marshal_VOID__BOOLEAN_BOXED,
820 g_dbus_connection_init (GDBusConnection *connection)
822 connection->lock = g_mutex_new ();
823 connection->init_lock = g_mutex_new ();
825 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
827 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
829 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
831 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
836 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
839 (GDestroyNotify) exported_object_free);
841 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
844 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
847 (GDestroyNotify) exported_subtree_free);
849 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
852 connection->main_context_at_construction = g_main_context_get_thread_default ();
853 if (connection->main_context_at_construction != NULL)
854 g_main_context_ref (connection->main_context_at_construction);
856 connection->filters = g_ptr_array_new ();
860 * g_dbus_connection_get_stream:
861 * @connection: a #GDBusConnection
863 * Gets the underlying stream used for IO.
865 * Returns: the stream used for IO
870 g_dbus_connection_get_stream (GDBusConnection *connection)
872 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
873 return connection->stream;
877 * g_dbus_connection_start_message_processing:
878 * @connection: A #GDBusConnection.
880 * If @connection was created with
881 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
882 * starts processing messages. Does nothing on if @connection wasn't
883 * created with this flag or if the method has already been called.
888 g_dbus_connection_start_message_processing (GDBusConnection *connection)
890 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
891 _g_dbus_worker_unfreeze (connection->worker);
895 * g_dbus_connection_is_closed:
896 * @connection: A #GDBusConnection.
898 * Gets whether @connection is closed.
900 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
905 g_dbus_connection_is_closed (GDBusConnection *connection)
907 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
908 return connection->closed;
912 * g_dbus_connection_get_capabilities:
913 * @connection: A #GDBusConnection.
915 * Gets the capabilities negotiated with the remote peer
917 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
922 g_dbus_connection_get_capabilities (GDBusConnection *connection)
924 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
925 return connection->capabilities;
928 /* ---------------------------------------------------------------------------------------------------- */
931 flush_in_thread_func (GSimpleAsyncResult *res,
933 GCancellable *cancellable)
938 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
942 g_simple_async_result_set_from_error (res, error);
943 g_error_free (error);
948 * g_dbus_connection_flush:
949 * @connection: A #GDBusConnection.
950 * @cancellable: A #GCancellable or %NULL.
951 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
952 * care about the result.
953 * @user_data: The data to pass to @callback.
955 * Asynchronously flushes @connection, that is, writes all queued
956 * outgoing message to the transport and then flushes the transport
957 * (using g_output_stream_flush_async()). This is useful in programs
958 * that wants to emit a D-Bus signal and then exit
959 * immediately. Without flushing the connection, there is no guarantee
960 * that the message has been sent to the networking buffers in the OS
963 * This is an asynchronous method. When the operation is finished,
964 * @callback will be invoked in the <link
965 * linkend="g-main-context-push-thread-default">thread-default main
966 * loop</link> of the thread you are calling this method from. You can
967 * then call g_dbus_connection_flush_finish() to get the result of the
968 * operation. See g_dbus_connection_flush_sync() for the synchronous
974 g_dbus_connection_flush (GDBusConnection *connection,
975 GCancellable *cancellable,
976 GAsyncReadyCallback callback,
979 GSimpleAsyncResult *simple;
981 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
983 simple = g_simple_async_result_new (G_OBJECT (connection),
986 g_dbus_connection_flush);
987 g_simple_async_result_run_in_thread (simple,
988 flush_in_thread_func,
991 g_object_unref (simple);
995 * g_dbus_connection_flush_finish:
996 * @connection: A #GDBusConnection.
997 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_flush().
998 * @error: Return location for error or %NULL.
1000 * Finishes an operation started with g_dbus_connection_flush().
1002 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1007 g_dbus_connection_flush_finish (GDBusConnection *connection,
1011 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1016 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1017 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1018 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1020 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1022 if (g_simple_async_result_propagate_error (simple, error))
1032 * g_dbus_connection_flush_sync:
1033 * @connection: A #GDBusConnection.
1034 * @cancellable: A #GCancellable or %NULL.
1035 * @error: Return location for error or %NULL.
1037 * Synchronously flushes @connection. The calling thread is blocked
1038 * until this is done. See g_dbus_connection_flush() for the
1039 * asynchronous version of this method and more details about what it
1042 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1047 g_dbus_connection_flush_sync (GDBusConnection *connection,
1048 GCancellable *cancellable,
1053 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1054 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1058 if (connection->closed)
1060 g_set_error_literal (error,
1063 _("The connection is closed"));
1067 ret = _g_dbus_worker_flush_sync (connection->worker,
1075 /* ---------------------------------------------------------------------------------------------------- */
1079 GDBusConnection *connection;
1081 gboolean remote_peer_vanished;
1085 emit_closed_data_free (EmitClosedData *data)
1087 g_object_unref (data->connection);
1088 if (data->error != NULL)
1089 g_error_free (data->error);
1094 emit_closed_in_idle (gpointer user_data)
1096 EmitClosedData *data = user_data;
1099 g_object_notify (G_OBJECT (data->connection), "closed");
1100 g_signal_emit (data->connection,
1101 signals[CLOSED_SIGNAL],
1103 data->remote_peer_vanished,
1109 /* Can be called from any thread, must hold lock */
1111 set_closed_unlocked (GDBusConnection *connection,
1112 gboolean remote_peer_vanished,
1115 GSource *idle_source;
1116 EmitClosedData *data;
1118 CONNECTION_ENSURE_LOCK (connection);
1120 g_assert (!connection->closed);
1122 connection->closed = TRUE;
1124 data = g_new0 (EmitClosedData, 1);
1125 data->connection = g_object_ref (connection);
1126 data->remote_peer_vanished = remote_peer_vanished;
1127 data->error = error != NULL ? g_error_copy (error) : NULL;
1129 idle_source = g_idle_source_new ();
1130 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1131 g_source_set_callback (idle_source,
1132 emit_closed_in_idle,
1134 (GDestroyNotify) emit_closed_data_free);
1135 g_source_attach (idle_source, connection->main_context_at_construction);
1136 g_source_unref (idle_source);
1139 /* ---------------------------------------------------------------------------------------------------- */
1142 close_in_thread_func (GSimpleAsyncResult *res,
1144 GCancellable *cancellable)
1149 if (!g_dbus_connection_close_sync (G_DBUS_CONNECTION (object),
1153 g_simple_async_result_set_from_error (res, error);
1154 g_error_free (error);
1159 * g_dbus_connection_close:
1160 * @connection: A #GDBusConnection.
1161 * @cancellable: A #GCancellable or %NULL.
1162 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1163 * care about the result.
1164 * @user_data: The data to pass to @callback.
1166 * Closes @connection. Note that this never causes the process to
1167 * exit (this might only happen if the other end of a shared message
1168 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1170 * Once the connection is closed, operations such as sending a message
1171 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1172 * will not automatically flush the connection so queued messages may
1173 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1175 * If @connection is already closed, this method fails with
1176 * %G_IO_ERROR_CLOSED.
1178 * When @connection has been closed, the #GDBusConnection::closed
1179 * signal is emitted in the <link
1180 * linkend="g-main-context-push-thread-default">thread-default main
1181 * loop</link> of the thread that @connection was constructed in.
1183 * This is an asynchronous method. When the operation is finished,
1184 * @callback will be invoked in the <link
1185 * linkend="g-main-context-push-thread-default">thread-default main
1186 * loop</link> of the thread you are calling this method from. You can
1187 * then call g_dbus_connection_close_finish() to get the result of the
1188 * operation. See g_dbus_connection_close_sync() for the synchronous
1194 g_dbus_connection_close (GDBusConnection *connection,
1195 GCancellable *cancellable,
1196 GAsyncReadyCallback callback,
1199 GSimpleAsyncResult *simple;
1201 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1203 simple = g_simple_async_result_new (G_OBJECT (connection),
1206 g_dbus_connection_close);
1207 g_simple_async_result_run_in_thread (simple,
1208 close_in_thread_func,
1211 g_object_unref (simple);
1215 * g_dbus_connection_close_finish:
1216 * @connection: A #GDBusConnection.
1217 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_close().
1218 * @error: Return location for error or %NULL.
1220 * Finishes an operation started with g_dbus_connection_close().
1222 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1227 g_dbus_connection_close_finish (GDBusConnection *connection,
1231 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1236 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1237 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1238 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1240 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1242 if (g_simple_async_result_propagate_error (simple, error))
1252 * g_dbus_connection_close_sync:
1253 * @connection: A #GDBusConnection.
1254 * @cancellable: A #GCancellable or %NULL.
1255 * @error: Return location for error or %NULL.
1257 * Synchronously closees @connection. The calling thread is blocked
1258 * until this is done. See g_dbus_connection_close() for the
1259 * asynchronous version of this method and more details about what it
1262 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1267 g_dbus_connection_close_sync (GDBusConnection *connection,
1268 GCancellable *cancellable,
1273 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1274 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1278 CONNECTION_LOCK (connection);
1279 if (!connection->closed)
1281 ret = g_io_stream_close (connection->stream,
1285 set_closed_unlocked (connection, FALSE, NULL);
1289 g_set_error_literal (error,
1292 _("The connection is closed"));
1294 CONNECTION_UNLOCK (connection);
1299 /* ---------------------------------------------------------------------------------------------------- */
1302 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1303 GDBusMessage *message,
1304 GDBusSendMessageFlags flags,
1305 volatile guint32 *out_serial,
1310 guint32 serial_to_use;
1313 CONNECTION_ENSURE_LOCK (connection);
1315 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1316 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1318 /* TODO: check all necessary headers are present */
1323 if (out_serial != NULL)
1326 if (connection->closed)
1328 g_set_error_literal (error,
1331 _("The connection is closed"));
1335 blob = g_dbus_message_to_blob (message,
1337 connection->capabilities,
1342 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1343 serial_to_use = g_dbus_message_get_serial (message);
1345 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1350 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1353 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1356 g_assert_not_reached ();
1361 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1362 blob_size, serial_to_use, connection);
1363 g_printerr ("----\n");
1364 hexdump (blob, blob_size);
1365 g_printerr ("----\n");
1368 /* TODO: use connection->auth to encode the blob */
1370 if (out_serial != NULL)
1371 *out_serial = serial_to_use;
1373 g_dbus_message_set_serial (message, serial_to_use);
1375 _g_dbus_worker_send_message (connection->worker,
1379 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1390 * g_dbus_connection_send_message:
1391 * @connection: A #GDBusConnection.
1392 * @message: A #GDBusMessage
1393 * @flags: Flags affecting how the message is sent.
1394 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1395 * @error: Return location for error or %NULL.
1397 * Asynchronously sends @message to the peer represented by @connection.
1399 * Unless @flags contain the
1400 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1401 * will be assigned by @connection and set on @message via
1402 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1403 * serial number used will be written to this location prior to
1404 * submitting the message to the underlying transport.
1406 * If @connection is closed then the operation will fail with
1407 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1408 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1410 * See <xref linkend="gdbus-server"/> and <xref
1411 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1412 * low-level API to send and receive UNIX file descriptors.
1414 * Returns: %TRUE if the message was well-formed and queued for
1415 * transmission, %FALSE if @error is set.
1420 g_dbus_connection_send_message (GDBusConnection *connection,
1421 GDBusMessage *message,
1422 GDBusSendMessageFlags flags,
1423 volatile guint32 *out_serial,
1428 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1429 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1430 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1432 CONNECTION_LOCK (connection);
1433 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1434 CONNECTION_UNLOCK (connection);
1438 /* ---------------------------------------------------------------------------------------------------- */
1442 volatile gint ref_count;
1443 GDBusConnection *connection;
1445 GSimpleAsyncResult *simple;
1447 GMainContext *main_context;
1449 GCancellable *cancellable;
1451 gulong cancellable_handler_id;
1453 GSource *timeout_source;
1458 static SendMessageData *
1459 send_message_data_ref (SendMessageData *data)
1461 g_atomic_int_inc (&data->ref_count);
1466 send_message_data_unref (SendMessageData *data)
1468 if (g_atomic_int_dec_and_test (&data->ref_count))
1470 g_assert (data->timeout_source == NULL);
1471 g_assert (data->simple == NULL);
1472 g_assert (data->cancellable_handler_id == 0);
1473 g_object_unref (data->connection);
1474 if (data->cancellable != NULL)
1475 g_object_unref (data->cancellable);
1476 if (data->main_context != NULL)
1477 g_main_context_unref (data->main_context);
1482 /* ---------------------------------------------------------------------------------------------------- */
1484 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1486 send_message_with_reply_deliver (SendMessageData *data)
1488 CONNECTION_ENSURE_LOCK (data->connection);
1490 g_assert (!data->delivered);
1492 data->delivered = TRUE;
1494 g_simple_async_result_complete_in_idle (data->simple);
1495 g_object_unref (data->simple);
1496 data->simple = NULL;
1498 if (data->timeout_source != NULL)
1500 g_source_destroy (data->timeout_source);
1501 data->timeout_source = NULL;
1503 if (data->cancellable_handler_id > 0)
1505 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1506 data->cancellable_handler_id = 0;
1509 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
1510 GUINT_TO_POINTER (data->serial)));
1512 send_message_data_unref (data);
1515 /* ---------------------------------------------------------------------------------------------------- */
1517 /* must hold lock */
1519 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1520 GDBusMessage *reply)
1522 if (data->delivered)
1525 g_simple_async_result_set_op_res_gpointer (data->simple,
1526 g_object_ref (reply),
1529 send_message_with_reply_deliver (data);
1535 /* ---------------------------------------------------------------------------------------------------- */
1538 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1540 SendMessageData *data = user_data;
1542 CONNECTION_LOCK (data->connection);
1543 if (data->delivered)
1546 g_simple_async_result_set_error (data->simple,
1548 G_IO_ERROR_CANCELLED,
1549 _("Operation was cancelled"));
1551 send_message_with_reply_deliver (data);
1554 CONNECTION_UNLOCK (data->connection);
1558 /* Can be called from any thread with or without lock held */
1560 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1563 SendMessageData *data = user_data;
1564 GSource *idle_source;
1566 /* postpone cancellation to idle handler since we may be called directly
1567 * via g_cancellable_connect() (e.g. holding lock)
1569 idle_source = g_idle_source_new ();
1570 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1571 g_source_set_callback (idle_source,
1572 send_message_with_reply_cancelled_idle_cb,
1573 send_message_data_ref (data),
1574 (GDestroyNotify) send_message_data_unref);
1575 g_source_attach (idle_source, data->main_context);
1576 g_source_unref (idle_source);
1579 /* ---------------------------------------------------------------------------------------------------- */
1582 send_message_with_reply_timeout_cb (gpointer user_data)
1584 SendMessageData *data = user_data;
1586 CONNECTION_LOCK (data->connection);
1587 if (data->delivered)
1590 g_simple_async_result_set_error (data->simple,
1592 G_IO_ERROR_TIMED_OUT,
1593 _("Timeout was reached"));
1595 send_message_with_reply_deliver (data);
1598 CONNECTION_UNLOCK (data->connection);
1603 /* ---------------------------------------------------------------------------------------------------- */
1606 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1607 GDBusMessage *message,
1608 GDBusSendMessageFlags flags,
1610 volatile guint32 *out_serial,
1611 GCancellable *cancellable,
1612 GAsyncReadyCallback callback,
1615 GSimpleAsyncResult *simple;
1616 SendMessageData *data;
1618 volatile guint32 serial;
1622 if (out_serial == NULL)
1623 out_serial = &serial;
1625 if (timeout_msec == -1)
1626 timeout_msec = 25 * 1000;
1628 simple = g_simple_async_result_new (G_OBJECT (connection),
1631 g_dbus_connection_send_message_with_reply);
1633 if (g_cancellable_is_cancelled (cancellable))
1635 g_simple_async_result_set_error (simple,
1637 G_IO_ERROR_CANCELLED,
1638 _("Operation was cancelled"));
1639 g_simple_async_result_complete_in_idle (simple);
1640 g_object_unref (simple);
1644 if (connection->closed)
1646 g_simple_async_result_set_error (simple,
1649 _("The connection is closed"));
1650 g_simple_async_result_complete_in_idle (simple);
1651 g_object_unref (simple);
1656 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1658 g_simple_async_result_set_from_error (simple, error);
1659 g_simple_async_result_complete_in_idle (simple);
1660 g_object_unref (simple);
1664 data = g_new0 (SendMessageData, 1);
1665 data->ref_count = 1;
1666 data->connection = g_object_ref (connection);
1667 data->simple = simple;
1668 data->serial = *out_serial;
1669 data->main_context = g_main_context_get_thread_default ();
1670 if (data->main_context != NULL)
1671 g_main_context_ref (data->main_context);
1673 if (cancellable != NULL)
1675 data->cancellable = g_object_ref (cancellable);
1676 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1677 G_CALLBACK (send_message_with_reply_cancelled_cb),
1678 send_message_data_ref (data),
1679 (GDestroyNotify) send_message_data_unref);
1680 g_object_set_data_full (G_OBJECT (simple),
1682 g_object_ref (cancellable),
1683 (GDestroyNotify) g_object_unref);
1686 data->timeout_source = g_timeout_source_new (timeout_msec);
1687 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1688 g_source_set_callback (data->timeout_source,
1689 send_message_with_reply_timeout_cb,
1690 send_message_data_ref (data),
1691 (GDestroyNotify) send_message_data_unref);
1692 g_source_attach (data->timeout_source, data->main_context);
1693 g_source_unref (data->timeout_source);
1695 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
1696 GUINT_TO_POINTER (*out_serial),
1704 * g_dbus_connection_send_message_with_reply:
1705 * @connection: A #GDBusConnection.
1706 * @message: A #GDBusMessage.
1707 * @flags: Flags affecting how the message is sent.
1708 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1709 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1710 * @cancellable: A #GCancellable or %NULL.
1711 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1712 * care about the result.
1713 * @user_data: The data to pass to @callback.
1715 * Asynchronously sends @message to the peer represented by @connection.
1717 * Unless @flags contain the
1718 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1719 * will be assigned by @connection and set on @message via
1720 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1721 * serial number used will be written to this location prior to
1722 * submitting the message to the underlying transport.
1724 * If @connection is closed then the operation will fail with
1725 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1726 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1727 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1729 * This is an asynchronous method. When the operation is finished, @callback will be invoked
1730 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
1731 * of the thread you are calling this method from. You can then call
1732 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1733 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
1735 * See <xref linkend="gdbus-server"/> and <xref
1736 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1737 * low-level API to send and receive UNIX file descriptors.
1742 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
1743 GDBusMessage *message,
1744 GDBusSendMessageFlags flags,
1746 volatile guint32 *out_serial,
1747 GCancellable *cancellable,
1748 GAsyncReadyCallback callback,
1751 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1752 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1753 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
1755 CONNECTION_LOCK (connection);
1756 g_dbus_connection_send_message_with_reply_unlocked (connection,
1764 CONNECTION_UNLOCK (connection);
1768 * g_dbus_connection_send_message_with_reply_finish:
1769 * @connection: a #GDBusConnection
1770 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
1771 * @error: Return location for error or %NULL.
1773 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
1775 * Note that @error is only set if a local in-process error
1776 * occured. That is to say that the returned #GDBusMessage object may
1777 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1778 * g_dbus_message_to_gerror() to transcode this to a #GError.
1780 * See <xref linkend="gdbus-server"/> and <xref
1781 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1782 * low-level API to send and receive UNIX file descriptors.
1784 * Returns: A #GDBusMessage or %NULL if @error is set.
1789 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
1793 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1794 GDBusMessage *reply;
1795 GCancellable *cancellable;
1797 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1798 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1802 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
1804 if (g_simple_async_result_propagate_error (simple, error))
1807 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
1808 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
1809 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
1811 g_object_unref (reply);
1813 g_set_error_literal (error,
1815 G_IO_ERROR_CANCELLED,
1816 _("Operation was cancelled"));
1822 /* ---------------------------------------------------------------------------------------------------- */
1827 GMainContext *context;
1829 } SendMessageSyncData;
1832 send_message_with_reply_sync_cb (GDBusConnection *connection,
1836 SendMessageSyncData *data = user_data;
1837 data->res = g_object_ref (res);
1838 g_main_loop_quit (data->loop);
1842 * g_dbus_connection_send_message_with_reply_sync:
1843 * @connection: A #GDBusConnection.
1844 * @message: A #GDBusMessage.
1845 * @flags: Flags affecting how the message is sent.
1846 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1847 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1848 * @cancellable: A #GCancellable or %NULL.
1849 * @error: Return location for error or %NULL.
1851 * Synchronously sends @message to the peer represented by @connection
1852 * and blocks the calling thread until a reply is received or the
1853 * timeout is reached. See g_dbus_connection_send_message_with_reply()
1854 * for the asynchronous version of this method.
1856 * Unless @flags contain the
1857 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1858 * will be assigned by @connection and set on @message via
1859 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1860 * serial number used will be written to this location prior to
1861 * submitting the message to the underlying transport.
1863 * If @connection is closed then the operation will fail with
1864 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1865 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1866 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1868 * Note that @error is only set if a local in-process error
1869 * occured. That is to say that the returned #GDBusMessage object may
1870 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1871 * g_dbus_message_to_gerror() to transcode this to a #GError.
1873 * See <xref linkend="gdbus-server"/> and <xref
1874 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1875 * low-level API to send and receive UNIX file descriptors.
1877 * Returns: A #GDBusMessage that is the reply to @message or %NULL if @error is set.
1882 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
1883 GDBusMessage *message,
1884 GDBusSendMessageFlags flags,
1886 volatile guint32 *out_serial,
1887 GCancellable *cancellable,
1890 SendMessageSyncData *data;
1891 GDBusMessage *reply;
1893 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1894 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
1895 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1896 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1898 data = g_new0 (SendMessageSyncData, 1);
1899 data->context = g_main_context_new ();
1900 data->loop = g_main_loop_new (data->context, FALSE);
1902 g_main_context_push_thread_default (data->context);
1904 g_dbus_connection_send_message_with_reply (connection,
1910 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
1912 g_main_loop_run (data->loop);
1913 reply = g_dbus_connection_send_message_with_reply_finish (connection,
1917 g_main_context_pop_thread_default (data->context);
1919 g_main_context_unref (data->context);
1920 g_main_loop_unref (data->loop);
1921 g_object_unref (data->res);
1927 /* ---------------------------------------------------------------------------------------------------- */
1931 GDBusMessageFilterFunction func;
1938 GDBusMessageFilterFunction filter_function;
1940 GDestroyNotify user_data_free_func;
1943 /* Called in worker's thread - we must not block */
1945 on_worker_message_received (GDBusWorker *worker,
1946 GDBusMessage *message,
1949 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1950 FilterCallback *filters;
1951 gboolean consumed_by_filter;
1955 //g_debug ("in on_worker_message_received");
1957 g_object_ref (connection);
1959 /* First collect the set of callback functions */
1960 CONNECTION_LOCK (connection);
1961 num_filters = connection->filters->len;
1962 filters = g_new0 (FilterCallback, num_filters);
1963 for (n = 0; n < num_filters; n++)
1965 FilterData *data = connection->filters->pdata[n];
1966 filters[n].func = data->filter_function;
1967 filters[n].user_data = data->user_data;
1969 CONNECTION_UNLOCK (connection);
1971 /* the call the filters in order (without holding the lock) */
1972 consumed_by_filter = FALSE;
1973 for (n = 0; n < num_filters; n++)
1975 consumed_by_filter = filters[n].func (connection,
1978 filters[n].user_data);
1979 if (consumed_by_filter)
1983 /* Standard dispatch unless the filter ate the message */
1984 if (!consumed_by_filter)
1986 GDBusMessageType message_type;
1988 message_type = g_dbus_message_get_message_type (message);
1989 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
1991 guint32 reply_serial;
1992 SendMessageData *send_message_data;
1994 reply_serial = g_dbus_message_get_reply_serial (message);
1995 CONNECTION_LOCK (connection);
1996 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
1997 GUINT_TO_POINTER (reply_serial));
1998 if (send_message_data != NULL)
2000 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2001 send_message_data_deliver_reply_unlocked (send_message_data, message);
2005 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2007 CONNECTION_UNLOCK (connection);
2009 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2011 CONNECTION_LOCK (connection);
2012 distribute_signals (connection, message);
2013 CONNECTION_UNLOCK (connection);
2015 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2017 CONNECTION_LOCK (connection);
2018 distribute_method_call (connection, message);
2019 CONNECTION_UNLOCK (connection);
2023 g_object_unref (connection);
2027 /* Called in worker's thread */
2029 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2030 GDBusMessage *message,
2033 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
2034 FilterCallback *filters;
2035 gboolean consumed_by_filter;
2039 //g_debug ("in on_worker_message_about_to_be_sent");
2041 g_object_ref (connection);
2043 /* First collect the set of callback functions */
2044 CONNECTION_LOCK (connection);
2045 num_filters = connection->filters->len;
2046 filters = g_new0 (FilterCallback, num_filters);
2047 for (n = 0; n < num_filters; n++)
2049 FilterData *data = connection->filters->pdata[n];
2050 filters[n].func = data->filter_function;
2051 filters[n].user_data = data->user_data;
2053 CONNECTION_UNLOCK (connection);
2055 /* the call the filters in order (without holding the lock) */
2056 consumed_by_filter = FALSE;
2057 for (n = 0; n < num_filters; n++)
2059 consumed_by_filter = filters[n].func (connection,
2062 filters[n].user_data);
2063 if (consumed_by_filter)
2067 g_object_unref (connection);
2070 return consumed_by_filter;
2073 /* Called in worker's thread - we must not block */
2075 on_worker_closed (GDBusWorker *worker,
2076 gboolean remote_peer_vanished,
2080 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
2082 //g_debug ("in on_worker_closed: %s", error->message);
2084 CONNECTION_LOCK (connection);
2085 if (!connection->closed)
2086 set_closed_unlocked (connection, remote_peer_vanished, error);
2087 CONNECTION_UNLOCK (connection);
2090 /* ---------------------------------------------------------------------------------------------------- */
2092 /* Determines the biggest set of capabilities we can support on this connection */
2093 static GDBusCapabilityFlags
2094 get_offered_capabilities_max (GDBusConnection *connection)
2096 GDBusCapabilityFlags ret;
2097 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2099 if (G_IS_UNIX_CONNECTION (connection->stream))
2100 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2106 initable_init (GInitable *initable,
2107 GCancellable *cancellable,
2110 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2113 /* This method needs to be idempotent to work with the singleton
2114 * pattern. See the docs for g_initable_init(). We implement this by
2117 * Unfortunately we can't use the main lock since the on_worker_*()
2118 * callbacks above needs the lock during initialization (for message
2119 * bus connections we do a synchronous Hello() call on the bus).
2121 g_mutex_lock (connection->init_lock);
2125 if (connection->is_initialized)
2127 if (connection->stream != NULL)
2130 g_assert (connection->initialization_error != NULL);
2133 g_assert (connection->initialization_error == NULL);
2135 /* The user can pass multiple (but mutally exclusive) construct
2138 * - stream (of type GIOStream)
2139 * - address (of type gchar*)
2141 * At the end of the day we end up with a non-NULL GIOStream
2142 * object in connection->stream.
2144 if (connection->address != NULL)
2146 g_assert (connection->stream == NULL);
2148 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2149 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2151 g_set_error_literal (error,
2153 G_IO_ERROR_INVALID_ARGUMENT,
2154 _("Unsupported flags encountered when constructing a client-side connection"));
2158 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2159 NULL, /* TODO: out_guid */
2161 &connection->initialization_error);
2162 if (connection->stream == NULL)
2165 else if (connection->stream != NULL)
2171 g_assert_not_reached ();
2174 /* Authenticate the connection */
2175 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2177 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2178 g_assert (connection->guid != NULL);
2179 connection->auth = _g_dbus_auth_new (connection->stream);
2180 if (!_g_dbus_auth_run_server (connection->auth,
2181 connection->authentication_observer,
2183 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2184 get_offered_capabilities_max (connection),
2185 &connection->capabilities,
2186 &connection->credentials,
2188 &connection->initialization_error))
2191 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2193 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2194 g_assert (connection->guid == NULL);
2195 connection->auth = _g_dbus_auth_new (connection->stream);
2196 connection->guid = _g_dbus_auth_run_client (connection->auth,
2197 get_offered_capabilities_max (connection),
2198 &connection->capabilities,
2200 &connection->initialization_error);
2201 if (connection->guid == NULL)
2205 if (connection->authentication_observer != NULL)
2207 g_object_unref (connection->authentication_observer);
2208 connection->authentication_observer = NULL;
2211 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2213 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2218 * https://bugzilla.gnome.org/show_bug.cgi?id=616458
2222 if (G_IS_SOCKET_CONNECTION (connection->stream))
2224 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2228 connection->worker = _g_dbus_worker_new (connection->stream,
2229 connection->capabilities,
2230 (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING),
2231 on_worker_message_received,
2232 on_worker_message_about_to_be_sent,
2236 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2237 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2239 GVariant *hello_result;
2241 /* we could lift this restriction by adding code in gdbusprivate.c */
2242 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2244 g_set_error_literal (&connection->initialization_error,
2247 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2251 hello_result = g_dbus_connection_call_sync (connection,
2252 "org.freedesktop.DBus", /* name */
2253 "/org/freedesktop/DBus", /* path */
2254 "org.freedesktop.DBus", /* interface */
2256 NULL, /* parameters */
2257 G_VARIANT_TYPE ("(s)"),
2258 G_DBUS_CALL_FLAGS_NONE,
2260 NULL, /* TODO: cancellable */
2261 &connection->initialization_error);
2262 if (hello_result == NULL)
2265 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2266 g_variant_unref (hello_result);
2267 //g_debug ("unique name is `%s'", connection->bus_unique_name);
2270 connection->is_initialized = TRUE;
2276 g_assert (connection->initialization_error != NULL);
2277 g_propagate_error (error, g_error_copy (connection->initialization_error));
2280 g_mutex_unlock (connection->init_lock);
2286 initable_iface_init (GInitableIface *initable_iface)
2288 initable_iface->init = initable_init;
2291 /* ---------------------------------------------------------------------------------------------------- */
2294 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2299 /* ---------------------------------------------------------------------------------------------------- */
2302 * g_dbus_connection_new:
2303 * @stream: A #GIOStream.
2304 * @guid: The GUID to use if a authenticating as a server or %NULL.
2305 * @flags: Flags describing how to make the connection.
2306 * @observer: A #GDBusAuthObserver or %NULL.
2307 * @cancellable: A #GCancellable or %NULL.
2308 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2309 * @user_data: The data to pass to @callback.
2311 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2312 * with the end represented by @stream.
2314 * If @observer is not %NULL it may be used to control the
2315 * authentication process.
2317 * When the operation is finished, @callback will be invoked. You can
2318 * then call g_dbus_connection_new_finish() to get the result of the
2321 * This is a asynchronous failable constructor. See
2322 * g_dbus_connection_new_sync() for the synchronous
2328 g_dbus_connection_new (GIOStream *stream,
2330 GDBusConnectionFlags flags,
2331 GDBusAuthObserver *observer,
2332 GCancellable *cancellable,
2333 GAsyncReadyCallback callback,
2336 g_return_if_fail (G_IS_IO_STREAM (stream));
2337 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2345 "authentication-observer", observer,
2350 * g_dbus_connection_new_finish:
2351 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2352 * @error: Return location for error or %NULL.
2354 * Finishes an operation started with g_dbus_connection_new().
2356 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2361 g_dbus_connection_new_finish (GAsyncResult *res,
2365 GObject *source_object;
2367 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2368 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2370 source_object = g_async_result_get_source_object (res);
2371 g_assert (source_object != NULL);
2372 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2375 g_object_unref (source_object);
2377 return G_DBUS_CONNECTION (object);
2383 * g_dbus_connection_new_sync:
2384 * @stream: A #GIOStream.
2385 * @guid: The GUID to use if a authenticating as a server or %NULL.
2386 * @flags: Flags describing how to make the connection.
2387 * @observer: A #GDBusAuthObserver or %NULL.
2388 * @cancellable: A #GCancellable or %NULL.
2389 * @error: Return location for error or %NULL.
2391 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2392 * with the end represented by @stream.
2394 * If @observer is not %NULL it may be used to control the
2395 * authentication process.
2397 * This is a synchronous failable constructor. See
2398 * g_dbus_connection_new() for the asynchronous version.
2400 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2405 g_dbus_connection_new_sync (GIOStream *stream,
2407 GDBusConnectionFlags flags,
2408 GDBusAuthObserver *observer,
2409 GCancellable *cancellable,
2412 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2413 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2414 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2420 "authentication-observer", observer,
2424 /* ---------------------------------------------------------------------------------------------------- */
2427 * g_dbus_connection_new_for_address:
2428 * @address: A D-Bus address.
2429 * @flags: Flags describing how to make the connection.
2430 * @observer: A #GDBusAuthObserver or %NULL.
2431 * @cancellable: A #GCancellable or %NULL.
2432 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2433 * @user_data: The data to pass to @callback.
2435 * Asynchronously connects and sets up a D-Bus client connection for
2436 * exchanging D-Bus messages with an endpoint specified by @address
2437 * which must be in the D-Bus address format.
2439 * This constructor can only be used to initiate client-side
2440 * connections - use g_dbus_connection_new() if you need to act as the
2441 * server. In particular, @flags cannot contain the
2442 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2443 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2445 * When the operation is finished, @callback will be invoked. You can
2446 * then call g_dbus_connection_new_finish() to get the result of the
2449 * If @observer is not %NULL it may be used to control the
2450 * authentication process.
2452 * This is a asynchronous failable constructor. See
2453 * g_dbus_connection_new_for_address_sync() for the synchronous
2459 g_dbus_connection_new_for_address (const gchar *address,
2460 GDBusConnectionFlags flags,
2461 GDBusAuthObserver *observer,
2462 GCancellable *cancellable,
2463 GAsyncReadyCallback callback,
2466 g_return_if_fail (address != NULL);
2467 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2474 "authentication-observer", observer,
2479 * g_dbus_connection_new_for_address_finish:
2480 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2481 * @error: Return location for error or %NULL.
2483 * Finishes an operation started with g_dbus_connection_new_for_address().
2485 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2490 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2494 GObject *source_object;
2496 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2497 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2499 source_object = g_async_result_get_source_object (res);
2500 g_assert (source_object != NULL);
2501 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2504 g_object_unref (source_object);
2506 return G_DBUS_CONNECTION (object);
2512 * g_dbus_connection_new_for_address_sync:
2513 * @address: A D-Bus address.
2514 * @flags: Flags describing how to make the connection.
2515 * @observer: A #GDBusAuthObserver or %NULL.
2516 * @cancellable: A #GCancellable or %NULL.
2517 * @error: Return location for error or %NULL.
2519 * Synchronously connects and sets up a D-Bus client connection for
2520 * exchanging D-Bus messages with an endpoint specified by @address
2521 * which must be in the D-Bus address format.
2523 * This constructor can only be used to initiate client-side
2524 * connections - use g_dbus_connection_new_sync() if you need to act
2525 * as the server. In particular, @flags cannot contain the
2526 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2527 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2529 * This is a synchronous failable constructor. See
2530 * g_dbus_connection_new_for_address() for the asynchronous version.
2532 * If @observer is not %NULL it may be used to control the
2533 * authentication process.
2535 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2540 g_dbus_connection_new_for_address_sync (const gchar *address,
2541 GDBusConnectionFlags flags,
2542 GDBusAuthObserver *observer,
2543 GCancellable *cancellable,
2546 g_return_val_if_fail (address != NULL, NULL);
2547 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2548 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2553 "authentication-observer", observer,
2557 /* ---------------------------------------------------------------------------------------------------- */
2560 * g_dbus_connection_set_exit_on_close:
2561 * @connection: A #GDBusConnection.
2562 * @exit_on_close: Whether the process should be terminated
2563 * when @connection is closed by the remote peer.
2565 * Sets whether the process should be terminated when @connection is
2566 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2572 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2573 gboolean exit_on_close)
2575 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2576 connection->exit_on_close = exit_on_close;
2580 * g_dbus_connection_get_exit_on_close:
2581 * @connection: A #GDBusConnection.
2583 * Gets whether the process is terminated when @connection is
2584 * closed by the remote peer. See
2585 * #GDBusConnection:exit-on-close for more details.
2587 * Returns: Whether the process is terminated when @connection is
2588 * closed by the remote peer.
2593 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2595 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2596 return connection->exit_on_close;
2600 * g_dbus_connection_get_guid:
2601 * @connection: A #GDBusConnection.
2603 * The GUID of the peer performing the role of server when
2604 * authenticating. See #GDBusConnection:guid for more details.
2606 * Returns: The GUID. Do not free this string, it is owned by
2612 g_dbus_connection_get_guid (GDBusConnection *connection)
2614 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2615 return connection->guid;
2619 * g_dbus_connection_get_unique_name:
2620 * @connection: A #GDBusConnection.
2622 * Gets the unique name of @connection as assigned by the message
2623 * bus. This can also be used to figure out if @connection is a
2624 * message bus connection.
2626 * Returns: The unique name or %NULL if @connection is not a message
2627 * bus connection. Do not free this string, it is owned by
2633 g_dbus_connection_get_unique_name (GDBusConnection *connection)
2635 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2636 return connection->bus_unique_name;
2640 * g_dbus_connection_get_peer_credentials:
2641 * @connection: A #GDBusConnection.
2643 * Gets the credentials of the authenticated peer. This will always
2644 * return %NULL unless @connection acted as a server
2645 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
2646 * when set up and the client passed credentials as part of the
2647 * authentication process.
2649 * In a message bus setup, the message bus is always the server and
2650 * each application is a client. So this method will always return
2651 * %NULL for message bus clients.
2653 * Returns: A #GCredentials or %NULL if not available. Do not free
2654 * this object, it is owned by @connection.
2659 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
2661 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2662 return connection->credentials;
2665 /* ---------------------------------------------------------------------------------------------------- */
2667 static guint _global_filter_id = 1;
2670 * g_dbus_connection_add_filter:
2671 * @connection: A #GDBusConnection.
2672 * @filter_function: A filter function.
2673 * @user_data: User data to pass to @filter_function.
2674 * @user_data_free_func: Function to free @user_data with when filter
2675 * is removed or %NULL.
2677 * Adds a message filter. Filters are handlers that are run on all
2678 * incoming and outgoing messages, prior to standard dispatch. Filters
2679 * are run in the order that they were added. The same handler can be
2680 * added as a filter more than once, in which case it will be run more
2681 * than once. Filters added during a filter callback won't be run on
2682 * the message being processed.
2684 * Note that filters are run in a dedicated message handling thread so
2685 * they can't block and, generally, can't do anything but signal a
2686 * worker thread. Also note that filters are rarely needed - use API
2687 * such as g_dbus_connection_send_message_with_reply(),
2688 * g_dbus_connection_signal_subscribe() or
2689 * g_dbus_connection_call() instead.
2691 * If a filter consumes an incoming message (by returning %TRUE), the
2692 * message is not dispatched anywhere else - not even the standard
2693 * dispatch machinery (that API such as
2694 * g_dbus_connection_signal_subscribe() and
2695 * g_dbus_connection_send_message_with_reply() relies on) will see the
2696 * message. Similary, if a filter consumes an outgoing message, the
2697 * message will not be sent to the other peer.
2699 * Returns: A filter identifier that can be used with
2700 * g_dbus_connection_remove_filter().
2705 g_dbus_connection_add_filter (GDBusConnection *connection,
2706 GDBusMessageFilterFunction filter_function,
2708 GDestroyNotify user_data_free_func)
2712 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2713 g_return_val_if_fail (filter_function != NULL, 0);
2715 CONNECTION_LOCK (connection);
2716 data = g_new0 (FilterData, 1);
2717 data->id = _global_filter_id++; /* TODO: overflow etc. */
2718 data->filter_function = filter_function;
2719 data->user_data = user_data;
2720 data->user_data_free_func = user_data_free_func;
2721 g_ptr_array_add (connection->filters, data);
2722 CONNECTION_UNLOCK (connection);
2727 /* only called from finalize(), removes all filters */
2729 purge_all_filters (GDBusConnection *connection)
2732 for (n = 0; n < connection->filters->len; n++)
2734 FilterData *data = connection->filters->pdata[n];
2735 if (data->user_data_free_func != NULL)
2736 data->user_data_free_func (data->user_data);
2742 * g_dbus_connection_remove_filter:
2743 * @connection: a #GDBusConnection
2744 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
2751 g_dbus_connection_remove_filter (GDBusConnection *connection,
2755 FilterData *to_destroy;
2757 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2759 CONNECTION_LOCK (connection);
2761 for (n = 0; n < connection->filters->len; n++)
2763 FilterData *data = connection->filters->pdata[n];
2764 if (data->id == filter_id)
2766 g_ptr_array_remove_index (connection->filters, n);
2771 CONNECTION_UNLOCK (connection);
2773 /* do free without holding lock */
2774 if (to_destroy != NULL)
2776 if (to_destroy->user_data_free_func != NULL)
2777 to_destroy->user_data_free_func (to_destroy->user_data);
2778 g_free (to_destroy);
2782 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
2786 /* ---------------------------------------------------------------------------------------------------- */
2792 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
2793 gchar *interface_name;
2797 GArray *subscribers;
2802 GDBusSignalCallback callback;
2804 GDestroyNotify user_data_free_func;
2806 GMainContext *context;
2810 signal_data_free (SignalData *signal_data)
2812 g_free (signal_data->rule);
2813 g_free (signal_data->sender);
2814 g_free (signal_data->sender_unique_name);
2815 g_free (signal_data->interface_name);
2816 g_free (signal_data->member);
2817 g_free (signal_data->object_path);
2818 g_free (signal_data->arg0);
2819 g_array_free (signal_data->subscribers, TRUE);
2820 g_free (signal_data);
2824 args_to_rule (const gchar *sender,
2825 const gchar *interface_name,
2826 const gchar *member,
2827 const gchar *object_path,
2832 rule = g_string_new ("type='signal'");
2834 g_string_append_printf (rule, ",sender='%s'", sender);
2835 if (interface_name != NULL)
2836 g_string_append_printf (rule, ",interface='%s'", interface_name);
2838 g_string_append_printf (rule, ",member='%s'", member);
2839 if (object_path != NULL)
2840 g_string_append_printf (rule, ",path='%s'", object_path);
2842 g_string_append_printf (rule, ",arg0='%s'", arg0);
2844 return g_string_free (rule, FALSE);
2847 static guint _global_subscriber_id = 1;
2848 static guint _global_registration_id = 1;
2849 static guint _global_subtree_registration_id = 1;
2851 /* ---------------------------------------------------------------------------------------------------- */
2853 /* must hold lock when calling */
2855 add_match_rule (GDBusConnection *connection,
2856 const gchar *match_rule)
2859 GDBusMessage *message;
2861 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2862 "/org/freedesktop/DBus", /* path */
2863 "org.freedesktop.DBus", /* interface */
2865 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2867 if (!g_dbus_connection_send_message_unlocked (connection,
2869 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
2873 g_critical ("Error while sending AddMatch() message: %s", error->message);
2874 g_error_free (error);
2876 g_object_unref (message);
2879 /* ---------------------------------------------------------------------------------------------------- */
2881 /* must hold lock when calling */
2883 remove_match_rule (GDBusConnection *connection,
2884 const gchar *match_rule)
2887 GDBusMessage *message;
2889 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2890 "/org/freedesktop/DBus", /* path */
2891 "org.freedesktop.DBus", /* interface */
2893 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2896 if (!g_dbus_connection_send_message_unlocked (connection,
2898 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
2902 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
2903 g_error_free (error);
2905 g_object_unref (message);
2908 /* ---------------------------------------------------------------------------------------------------- */
2911 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
2913 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
2914 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
2915 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
2916 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
2917 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
2920 /* ---------------------------------------------------------------------------------------------------- */
2923 * g_dbus_connection_signal_subscribe:
2924 * @connection: A #GDBusConnection.
2925 * @sender: Sender name to match on (unique or well-known name) or %NULL to listen from all senders.
2926 * @interface_name: D-Bus interface name to match on or %NULL to match on all interfaces.
2927 * @member: D-Bus signal name to match on or %NULL to match on all signals.
2928 * @object_path: Object path to match on or %NULL to match on all object paths.
2929 * @arg0: Contents of first string argument to match on or %NULL to match on all kinds of arguments.
2930 * @flags: Flags describing how to subscribe to the signal (currently unused).
2931 * @callback: Callback to invoke when there is a signal matching the requested data.
2932 * @user_data: User data to pass to @callback.
2933 * @user_data_free_func: Function to free @user_data with when subscription is removed or %NULL.
2935 * Subscribes to signals on @connection and invokes @callback with a
2936 * whenever the signal is received. Note that @callback
2937 * will be invoked in the <link
2938 * linkend="g-main-context-push-thread-default">thread-default main
2939 * loop</link> of the thread you are calling this method from.
2941 * If @connection is not a message bus connection, @sender must be
2944 * If @sender is a well-known name note that @callback is invoked with
2945 * the unique name for the owner of @sender, not the well-known name
2946 * as one would expect. This is because the message bus rewrites the
2947 * name. As such, to avoid certain race conditions, users should be
2948 * tracking the name owner of the well-known name and use that when
2949 * processing the received signal.
2951 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
2956 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
2957 const gchar *sender,
2958 const gchar *interface_name,
2959 const gchar *member,
2960 const gchar *object_path,
2962 GDBusSignalFlags flags,
2963 GDBusSignalCallback callback,
2965 GDestroyNotify user_data_free_func)
2968 SignalData *signal_data;
2969 SignalSubscriber subscriber;
2970 GPtrArray *signal_data_array;
2971 const gchar *sender_unique_name;
2973 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
2974 * an OOM condition. We might want to change that but that would involve making
2975 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
2976 * handle that. And there's really no sensible way of handling this short of retrying
2977 * to add the match rule... and then there's the little thing that, hey, maybe there's
2978 * a reason the bus in an OOM condition.
2980 * Doable, but not really sure it's worth it...
2983 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2984 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
2985 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
2986 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
2987 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
2988 g_return_val_if_fail (callback != NULL, 0);
2990 CONNECTION_LOCK (connection);
2992 rule = args_to_rule (sender, interface_name, member, object_path, arg0);
2994 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
2995 sender_unique_name = sender;
2997 sender_unique_name = "";
2999 subscriber.callback = callback;
3000 subscriber.user_data = user_data;
3001 subscriber.user_data_free_func = user_data_free_func;
3002 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3003 subscriber.context = g_main_context_get_thread_default ();
3004 if (subscriber.context != NULL)
3005 g_main_context_ref (subscriber.context);
3007 /* see if we've already have this rule */
3008 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3009 if (signal_data != NULL)
3011 g_array_append_val (signal_data->subscribers, subscriber);
3016 signal_data = g_new0 (SignalData, 1);
3017 signal_data->rule = rule;
3018 signal_data->sender = g_strdup (sender);
3019 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3020 signal_data->interface_name = g_strdup (interface_name);
3021 signal_data->member = g_strdup (member);
3022 signal_data->object_path = g_strdup (object_path);
3023 signal_data->arg0 = g_strdup (arg0);
3024 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3025 g_array_append_val (signal_data->subscribers, subscriber);
3027 g_hash_table_insert (connection->map_rule_to_signal_data,
3031 /* Add the match rule to the bus...
3033 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3034 * always send such messages to us.
3036 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3038 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3039 add_match_rule (connection, signal_data->rule);
3042 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3043 signal_data->sender_unique_name);
3044 if (signal_data_array == NULL)
3046 signal_data_array = g_ptr_array_new ();
3047 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3048 g_strdup (signal_data->sender_unique_name),
3051 g_ptr_array_add (signal_data_array, signal_data);
3054 g_hash_table_insert (connection->map_id_to_signal_data,
3055 GUINT_TO_POINTER (subscriber.id),
3058 CONNECTION_UNLOCK (connection);
3060 return subscriber.id;
3063 /* ---------------------------------------------------------------------------------------------------- */
3065 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3067 unsubscribe_id_internal (GDBusConnection *connection,
3068 guint subscription_id,
3069 GArray *out_removed_subscribers)
3071 SignalData *signal_data;
3072 GPtrArray *signal_data_array;
3075 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3076 GUINT_TO_POINTER (subscription_id));
3077 if (signal_data == NULL)
3079 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3083 for (n = 0; n < signal_data->subscribers->len; n++)
3085 SignalSubscriber *subscriber;
3087 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3088 if (subscriber->id != subscription_id)
3091 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3092 GUINT_TO_POINTER (subscription_id)));
3093 g_array_append_val (out_removed_subscribers, *subscriber);
3094 g_array_remove_index (signal_data->subscribers, n);
3096 if (signal_data->subscribers->len == 0)
3098 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3100 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3101 signal_data->sender_unique_name);
3102 g_warn_if_fail (signal_data_array != NULL);
3103 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3105 if (signal_data_array->len == 0)
3107 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3108 signal_data->sender_unique_name));
3111 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3112 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3114 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3115 if (!connection->closed && !connection->finalizing)
3116 remove_match_rule (connection, signal_data->rule);
3118 signal_data_free (signal_data);
3124 g_assert_not_reached ();
3131 * g_dbus_connection_signal_unsubscribe:
3132 * @connection: A #GDBusConnection.
3133 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
3135 * Unsubscribes from signals.
3140 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3141 guint subscription_id)
3143 GArray *subscribers;
3146 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3148 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3150 CONNECTION_LOCK (connection);
3151 unsubscribe_id_internal (connection,
3154 CONNECTION_UNLOCK (connection);
3157 g_assert (subscribers->len == 0 || subscribers->len == 1);
3159 /* call GDestroyNotify without lock held */
3160 for (n = 0; n < subscribers->len; n++)
3162 SignalSubscriber *subscriber;
3163 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3164 if (subscriber->user_data_free_func != NULL)
3165 subscriber->user_data_free_func (subscriber->user_data);
3166 if (subscriber->context != NULL)
3167 g_main_context_unref (subscriber->context);
3170 g_array_free (subscribers, TRUE);
3173 /* ---------------------------------------------------------------------------------------------------- */
3177 guint subscription_id;
3178 GDBusSignalCallback callback;
3180 GDBusMessage *message;
3181 GDBusConnection *connection;
3182 const gchar *sender;
3184 const gchar *interface;
3185 const gchar *member;
3188 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3192 emit_signal_instance_in_idle_cb (gpointer data)
3194 SignalInstance *signal_instance = data;
3195 GVariant *parameters;
3196 gboolean has_subscription;
3198 parameters = g_dbus_message_get_body (signal_instance->message);
3199 if (parameters == NULL)
3201 parameters = g_variant_new ("()");
3202 g_variant_ref_sink (parameters);
3206 g_variant_ref_sink (parameters);
3210 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3211 signal_instance->subscription_id,
3212 signal_instance->sender,
3213 signal_instance->path,
3214 signal_instance->interface,
3215 signal_instance->member,
3216 g_variant_print (parameters, TRUE));
3219 /* Careful here, don't do the callback if we no longer has the subscription */
3220 CONNECTION_LOCK (signal_instance->connection);
3221 has_subscription = FALSE;
3222 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3223 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3224 has_subscription = TRUE;
3225 CONNECTION_UNLOCK (signal_instance->connection);
3227 if (has_subscription)
3228 signal_instance->callback (signal_instance->connection,
3229 signal_instance->sender,
3230 signal_instance->path,
3231 signal_instance->interface,
3232 signal_instance->member,
3234 signal_instance->user_data);
3236 if (parameters != NULL)
3237 g_variant_unref (parameters);
3243 signal_instance_free (SignalInstance *signal_instance)
3245 g_object_unref (signal_instance->message);
3246 g_object_unref (signal_instance->connection);
3247 g_free (signal_instance);
3250 /* called in message handler thread WITH lock held */
3252 schedule_callbacks (GDBusConnection *connection,
3253 GPtrArray *signal_data_array,
3254 GDBusMessage *message,
3255 const gchar *sender)
3258 const gchar *interface;
3259 const gchar *member;
3268 interface = g_dbus_message_get_interface (message);
3269 member = g_dbus_message_get_member (message);
3270 path = g_dbus_message_get_path (message);
3271 arg0 = g_dbus_message_get_arg0 (message);
3274 g_print ("In schedule_callbacks:\n"
3276 " interface = `%s'\n"
3287 /* TODO: if this is slow, then we can change signal_data_array into
3288 * map_object_path_to_signal_data_array or something.
3290 for (n = 0; n < signal_data_array->len; n++)
3292 SignalData *signal_data = signal_data_array->pdata[n];
3294 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3297 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3300 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3303 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
3306 for (m = 0; m < signal_data->subscribers->len; m++)
3308 SignalSubscriber *subscriber;
3309 GSource *idle_source;
3310 SignalInstance *signal_instance;
3312 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3314 signal_instance = g_new0 (SignalInstance, 1);
3315 signal_instance->subscription_id = subscriber->id;
3316 signal_instance->callback = subscriber->callback;
3317 signal_instance->user_data = subscriber->user_data;
3318 signal_instance->message = g_object_ref (message);
3319 signal_instance->connection = g_object_ref (connection);
3320 signal_instance->sender = sender;
3321 signal_instance->path = path;
3322 signal_instance->interface = interface;
3323 signal_instance->member = member;
3325 idle_source = g_idle_source_new ();
3326 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3327 g_source_set_callback (idle_source,
3328 emit_signal_instance_in_idle_cb,
3330 (GDestroyNotify) signal_instance_free);
3331 g_source_attach (idle_source, subscriber->context);
3332 g_source_unref (idle_source);
3337 /* called in message handler thread with lock held */
3339 distribute_signals (GDBusConnection *connection,
3340 GDBusMessage *message)
3342 GPtrArray *signal_data_array;
3343 const gchar *sender;
3345 sender = g_dbus_message_get_sender (message);
3347 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3349 _g_dbus_debug_print_lock ();
3350 g_print ("========================================================================\n"
3351 "GDBus-debug:Signal:\n"
3352 " <<<< RECEIVED SIGNAL %s.%s\n"
3354 " sent by name %s\n",
3355 g_dbus_message_get_interface (message),
3356 g_dbus_message_get_member (message),
3357 g_dbus_message_get_path (message),
3358 sender != NULL ? sender : "(none)");
3359 _g_dbus_debug_print_unlock ();
3362 /* collect subscribers that match on sender */
3365 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3366 if (signal_data_array != NULL)
3367 schedule_callbacks (connection, signal_data_array, message, sender);
3370 /* collect subscribers not matching on sender */
3371 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3372 if (signal_data_array != NULL)
3373 schedule_callbacks (connection, signal_data_array, message, sender);
3376 /* ---------------------------------------------------------------------------------------------------- */
3378 /* only called from finalize(), removes all subscriptions */
3380 purge_all_signal_subscriptions (GDBusConnection *connection)
3382 GHashTableIter iter;
3385 GArray *subscribers;
3388 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3389 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3390 while (g_hash_table_iter_next (&iter, &key, NULL))
3392 guint subscription_id = GPOINTER_TO_UINT (key);
3393 g_array_append_val (ids, subscription_id);
3396 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3397 for (n = 0; n < ids->len; n++)
3399 guint subscription_id = g_array_index (ids, guint, n);
3400 unsubscribe_id_internal (connection,
3404 g_array_free (ids, TRUE);
3406 /* call GDestroyNotify without lock held */
3407 for (n = 0; n < subscribers->len; n++)
3409 SignalSubscriber *subscriber;
3410 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3411 if (subscriber->user_data_free_func != NULL)
3412 subscriber->user_data_free_func (subscriber->user_data);
3413 if (subscriber->context != NULL)
3414 g_main_context_unref (subscriber->context);
3417 g_array_free (subscribers, TRUE);
3420 /* ---------------------------------------------------------------------------------------------------- */
3422 static GDBusInterfaceVTable *
3423 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3425 /* Don't waste memory by copying padding - remember to update this
3426 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3428 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3432 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
3437 /* ---------------------------------------------------------------------------------------------------- */
3439 static GDBusSubtreeVTable *
3440 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
3442 /* Don't waste memory by copying padding - remember to update this
3443 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
3445 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3449 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
3454 /* ---------------------------------------------------------------------------------------------------- */
3456 struct ExportedObject
3459 GDBusConnection *connection;
3461 /* maps gchar* -> ExportedInterface* */
3462 GHashTable *map_if_name_to_ei;
3465 /* only called with lock held */
3467 exported_object_free (ExportedObject *eo)
3469 g_free (eo->object_path);
3470 g_hash_table_unref (eo->map_if_name_to_ei);
3479 gchar *interface_name;
3480 GDBusInterfaceVTable *vtable;
3481 GDBusInterfaceInfo *interface_info;
3483 GMainContext *context;
3485 GDestroyNotify user_data_free_func;
3486 } ExportedInterface;
3488 /* called with lock held */
3490 exported_interface_free (ExportedInterface *ei)
3492 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
3494 if (ei->user_data_free_func != NULL)
3495 /* TODO: push to thread-default mainloop */
3496 ei->user_data_free_func (ei->user_data);
3498 if (ei->context != NULL)
3499 g_main_context_unref (ei->context);
3501 g_free (ei->interface_name);
3502 _g_dbus_interface_vtable_free (ei->vtable);
3506 /* ---------------------------------------------------------------------------------------------------- */
3508 /* Convenience function to check if @registration_id (if not zero) or
3509 * @subtree_registration_id (if not zero) has been unregistered. If
3510 * so, returns %TRUE.
3512 * Caller must *not* hold lock.
3515 has_object_been_unregistered (GDBusConnection *connection,
3516 guint registration_id,
3517 guint subtree_registration_id)
3521 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3525 CONNECTION_LOCK (connection);
3526 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
3527 GUINT_TO_POINTER (registration_id)) == NULL)
3531 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
3532 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
3536 CONNECTION_UNLOCK (connection);
3541 /* ---------------------------------------------------------------------------------------------------- */
3545 GDBusConnection *connection;
3546 GDBusMessage *message;
3548 const gchar *property_name;
3549 const GDBusInterfaceVTable *vtable;
3550 GDBusInterfaceInfo *interface_info;
3551 const GDBusPropertyInfo *property_info;
3552 guint registration_id;
3553 guint subtree_registration_id;
3557 property_data_free (PropertyData *data)
3559 g_object_unref (data->connection);
3560 g_object_unref (data->message);
3564 /* called in thread where object was registered - no locks held */
3566 invoke_get_property_in_idle_cb (gpointer _data)
3568 PropertyData *data = _data;
3571 GDBusMessage *reply;
3573 if (has_object_been_unregistered (data->connection,
3574 data->registration_id,
3575 data->subtree_registration_id))
3577 reply = g_dbus_message_new_method_error (data->message,
3578 "org.freedesktop.DBus.Error.UnknownMethod",
3579 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
3580 g_dbus_message_get_path (data->message));
3581 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3582 g_object_unref (reply);
3587 value = data->vtable->get_property (data->connection,
3588 g_dbus_message_get_sender (data->message),
3589 g_dbus_message_get_path (data->message),
3590 data->interface_info->name,
3591 data->property_name,
3598 g_assert_no_error (error);
3600 g_variant_ref_sink (value);
3601 reply = g_dbus_message_new_method_reply (data->message);
3602 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
3603 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3604 g_variant_unref (value);
3605 g_object_unref (reply);
3609 gchar *dbus_error_name;
3610 g_assert (error != NULL);
3611 dbus_error_name = g_dbus_error_encode_gerror (error);
3612 reply = g_dbus_message_new_method_error_literal (data->message,
3615 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3616 g_free (dbus_error_name);
3617 g_error_free (error);
3618 g_object_unref (reply);
3625 /* called in thread where object was registered - no locks held */
3627 invoke_set_property_in_idle_cb (gpointer _data)
3629 PropertyData *data = _data;
3631 GDBusMessage *reply;
3637 g_variant_get (g_dbus_message_get_body (data->message),
3643 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
3644 * of the given value is wrong
3646 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
3648 reply = g_dbus_message_new_method_error (data->message,
3649 "org.freedesktop.DBus.Error.InvalidArgs",
3650 _("Error setting property `%s': Expected type `%s' but got `%s'"),
3651 data->property_info->name,
3652 data->property_info->signature,
3653 g_variant_get_type_string (value));
3657 if (!data->vtable->set_property (data->connection,
3658 g_dbus_message_get_sender (data->message),
3659 g_dbus_message_get_path (data->message),
3660 data->interface_info->name,
3661 data->property_name,
3666 gchar *dbus_error_name;
3667 g_assert (error != NULL);
3668 dbus_error_name = g_dbus_error_encode_gerror (error);
3669 reply = g_dbus_message_new_method_error_literal (data->message,
3672 g_free (dbus_error_name);
3673 g_error_free (error);
3677 reply = g_dbus_message_new_method_reply (data->message);
3681 g_assert (reply != NULL);
3682 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3683 g_object_unref (reply);
3688 /* called with lock held */
3690 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
3691 GDBusMessage *message,
3692 guint registration_id,
3693 guint subtree_registration_id,
3695 GDBusInterfaceInfo *interface_info,
3696 const GDBusInterfaceVTable *vtable,
3697 GMainContext *main_context,
3701 const char *interface_name;
3702 const char *property_name;
3703 const GDBusPropertyInfo *property_info;
3704 GSource *idle_source;
3705 PropertyData *property_data;
3706 GDBusMessage *reply;
3711 g_variant_get (g_dbus_message_get_body (message),
3716 g_variant_get (g_dbus_message_get_body (message),
3725 if (vtable == NULL || vtable->get_property == NULL)
3730 if (vtable == NULL || vtable->set_property == NULL)
3734 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
3736 property_info = NULL;
3738 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3739 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
3740 if (property_info == NULL)
3742 reply = g_dbus_message_new_method_error (message,
3743 "org.freedesktop.DBus.Error.InvalidArgs",
3744 _("No such property `%s'"),
3746 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3747 g_object_unref (reply);
3752 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3754 reply = g_dbus_message_new_method_error (message,
3755 "org.freedesktop.DBus.Error.InvalidArgs",
3756 _("Property `%s' is not readable"),
3758 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3759 g_object_unref (reply);
3763 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
3765 reply = g_dbus_message_new_method_error (message,
3766 "org.freedesktop.DBus.Error.InvalidArgs",
3767 _("Property `%s' is not writable"),
3769 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3770 g_object_unref (reply);
3775 /* ok, got the property info - call user code in an idle handler */
3776 property_data = g_new0 (PropertyData, 1);
3777 property_data->connection = g_object_ref (connection);
3778 property_data->message = g_object_ref (message);
3779 property_data->user_data = user_data;
3780 property_data->property_name = property_name;
3781 property_data->vtable = vtable;
3782 property_data->interface_info = interface_info;
3783 property_data->property_info = property_info;
3784 property_data->registration_id = registration_id;
3785 property_data->subtree_registration_id = subtree_registration_id;
3787 idle_source = g_idle_source_new ();
3788 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3789 g_source_set_callback (idle_source,
3790 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
3792 (GDestroyNotify) property_data_free);
3793 g_source_attach (idle_source, main_context);
3794 g_source_unref (idle_source);
3802 /* called with lock held */
3804 handle_getset_property (GDBusConnection *connection,
3806 GDBusMessage *message,
3809 ExportedInterface *ei;
3811 const char *interface_name;
3812 const char *property_name;
3817 g_variant_get (g_dbus_message_get_body (message),
3822 g_variant_get (g_dbus_message_get_body (message),
3828 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3829 * no such interface registered
3831 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3834 GDBusMessage *reply;
3835 reply = g_dbus_message_new_method_error (message,
3836 "org.freedesktop.DBus.Error.InvalidArgs",
3837 _("No such interface `%s'"),
3839 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3840 g_object_unref (reply);
3845 handled = validate_and_maybe_schedule_property_getset (eo->connection,
3858 /* ---------------------------------------------------------------------------------------------------- */
3862 GDBusConnection *connection;
3863 GDBusMessage *message;
3865 const GDBusInterfaceVTable *vtable;
3866 GDBusInterfaceInfo *interface_info;
3867 guint registration_id;
3868 guint subtree_registration_id;
3869 } PropertyGetAllData;
3872 property_get_all_data_free (PropertyData *data)
3874 g_object_unref (data->connection);
3875 g_object_unref (data->message);
3879 /* called in thread where object was registered - no locks held */
3881 invoke_get_all_properties_in_idle_cb (gpointer _data)
3883 PropertyGetAllData *data = _data;
3884 GVariantBuilder builder;
3886 GDBusMessage *reply;
3889 if (has_object_been_unregistered (data->connection,
3890 data->registration_id,
3891 data->subtree_registration_id))
3893 reply = g_dbus_message_new_method_error (data->message,
3894 "org.freedesktop.DBus.Error.UnknownMethod",
3895 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
3896 g_dbus_message_get_path (data->message));
3897 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3898 g_object_unref (reply);
3904 /* TODO: Right now we never fail this call - we just omit values if
3905 * a get_property() call is failing.
3907 * We could fail the whole call if just a single get_property() call
3908 * returns an error. We need clarification in the D-Bus spec about this.
3910 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
3911 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
3912 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
3914 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
3917 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3920 value = data->vtable->get_property (data->connection,
3921 g_dbus_message_get_sender (data->message),
3922 g_dbus_message_get_path (data->message),
3923 data->interface_info->name,
3924 property_info->name,
3931 g_variant_builder_add (&builder,
3933 property_info->name,
3936 g_variant_builder_close (&builder);
3938 reply = g_dbus_message_new_method_reply (data->message);
3939 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
3940 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3941 g_object_unref (reply);
3947 /* called with lock held */
3949 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
3950 GDBusMessage *message,
3951 guint registration_id,
3952 guint subtree_registration_id,
3953 GDBusInterfaceInfo *interface_info,
3954 const GDBusInterfaceVTable *vtable,
3955 GMainContext *main_context,
3959 const char *interface_name;
3960 GSource *idle_source;
3961 PropertyGetAllData *property_get_all_data;
3965 g_variant_get (g_dbus_message_get_body (message),
3969 if (vtable == NULL || vtable->get_property == NULL)
3972 /* ok, got the property info - call user in an idle handler */
3973 property_get_all_data = g_new0 (PropertyGetAllData, 1);
3974 property_get_all_data->connection = g_object_ref (connection);
3975 property_get_all_data->message = g_object_ref (message);
3976 property_get_all_data->user_data = user_data;
3977 property_get_all_data->vtable = vtable;
3978 property_get_all_data->interface_info = interface_info;
3979 property_get_all_data->registration_id = registration_id;
3980 property_get_all_data->subtree_registration_id = subtree_registration_id;
3982 idle_source = g_idle_source_new ();
3983 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3984 g_source_set_callback (idle_source,
3985 invoke_get_all_properties_in_idle_cb,
3986 property_get_all_data,
3987 (GDestroyNotify) property_get_all_data_free);
3988 g_source_attach (idle_source, main_context);
3989 g_source_unref (idle_source);
3997 /* called with lock held */
3999 handle_get_all_properties (GDBusConnection *connection,
4001 GDBusMessage *message)
4003 ExportedInterface *ei;
4005 const char *interface_name;
4009 g_variant_get (g_dbus_message_get_body (message),
4013 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4014 * no such interface registered
4016 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4019 GDBusMessage *reply;
4020 reply = g_dbus_message_new_method_error (message,
4021 "org.freedesktop.DBus.Error.InvalidArgs",
4022 _("No such interface"),
4024 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4025 g_object_unref (reply);
4030 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4042 /* ---------------------------------------------------------------------------------------------------- */
4044 static const gchar introspect_header[] =
4045 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4046 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4047 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4050 static const gchar introspect_tail[] =
4053 static const gchar introspect_standard_interfaces[] =
4054 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4055 " <method name=\"Get\">\n"
4056 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4057 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4058 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4060 " <method name=\"GetAll\">\n"
4061 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4062 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4064 " <method name=\"Set\">\n"
4065 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4066 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4067 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4069 " <signal name=\"PropertiesChanged\">\n"
4070 " <arg type=\"s\" name=\"interface_name\"/>\n"
4071 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4072 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4075 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4076 " <method name=\"Introspect\">\n"
4077 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4080 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4081 " <method name=\"Ping\"/>\n"
4082 " <method name=\"GetMachineId\">\n"
4083 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4088 introspect_append_header (GString *s)
4090 g_string_append (s, introspect_header);
4094 introspect_append_standard_interfaces (GString *s)
4096 g_string_append (s, introspect_standard_interfaces);
4100 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4102 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4108 begin = object_path + path_len;
4109 end = strchr (begin, '/');
4111 s = g_strndup (begin, end - begin);
4113 s = g_strdup (begin);
4115 if (g_hash_table_lookup (set, s) == NULL)
4116 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
4122 /* TODO: we want a nicer public interface for this */
4124 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4129 GHashTableIter hash_iter;
4130 const gchar *object_path;
4136 CONNECTION_ENSURE_LOCK (connection);
4138 path_len = strlen (path);
4142 set = g_hash_table_new (g_str_hash, g_str_equal);
4144 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4145 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4146 maybe_add_path (path, path_len, object_path, set);
4148 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4149 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4150 maybe_add_path (path, path_len, object_path, set);
4152 p = g_ptr_array_new ();
4153 keys = g_hash_table_get_keys (set);
4154 for (l = keys; l != NULL; l = l->next)
4155 g_ptr_array_add (p, l->data);
4156 g_hash_table_unref (set);
4159 g_ptr_array_add (p, NULL);
4160 ret = (gchar **) g_ptr_array_free (p, FALSE);
4165 g_dbus_connection_list_registered (GDBusConnection *connection,
4169 CONNECTION_LOCK (connection);
4170 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4171 CONNECTION_UNLOCK (connection);
4175 /* called in message handler thread with lock held */
4177 handle_introspect (GDBusConnection *connection,
4179 GDBusMessage *message)
4183 GDBusMessage *reply;
4184 GHashTableIter hash_iter;
4185 ExportedInterface *ei;
4188 /* first the header with the standard interfaces */
4189 s = g_string_sized_new (sizeof (introspect_header) +
4190 sizeof (introspect_standard_interfaces) +
4191 sizeof (introspect_tail));
4192 introspect_append_header (s);
4193 introspect_append_standard_interfaces (s);
4195 /* then include the registered interfaces */
4196 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4197 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4198 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4200 /* finally include nodes registered below us */
4201 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4202 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4203 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4204 g_strfreev (registered);
4205 g_string_append (s, introspect_tail);
4207 reply = g_dbus_message_new_method_reply (message);
4208 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4209 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4210 g_object_unref (reply);
4211 g_string_free (s, TRUE);
4216 /* called in thread where object was registered - no locks held */
4218 call_in_idle_cb (gpointer user_data)
4220 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4221 GDBusInterfaceVTable *vtable;
4222 guint registration_id;
4223 guint subtree_registration_id;
4225 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4226 g_assert (vtable != NULL && vtable->method_call != NULL);
4228 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4229 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4231 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4233 subtree_registration_id))
4235 GDBusMessage *reply;
4236 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4237 "org.freedesktop.DBus.Error.UnknownMethod",
4238 _("No such interface `%s' on object at path %s"),
4239 g_dbus_method_invocation_get_interface_name (invocation),
4240 g_dbus_method_invocation_get_object_path (invocation));
4241 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4242 g_object_unref (reply);
4246 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4247 g_dbus_method_invocation_get_sender (invocation),
4248 g_dbus_method_invocation_get_object_path (invocation),
4249 g_dbus_method_invocation_get_interface_name (invocation),
4250 g_dbus_method_invocation_get_method_name (invocation),
4251 g_dbus_method_invocation_get_parameters (invocation),
4252 g_object_ref (invocation),
4253 g_dbus_method_invocation_get_user_data (invocation));
4259 /* called in message handler thread with lock held */
4261 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4262 GDBusMessage *message,
4263 guint registration_id,
4264 guint subtree_registration_id,
4265 GDBusInterfaceInfo *interface_info,
4266 const GDBusInterfaceVTable *vtable,
4267 GMainContext *main_context,
4270 GDBusMethodInvocation *invocation;
4271 const GDBusMethodInfo *method_info;
4272 GDBusMessage *reply;
4273 GVariant *parameters;
4274 GSource *idle_source;
4276 GVariantType *in_type;
4280 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4281 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4283 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4284 * error to the caller
4286 if (method_info == NULL)
4288 reply = g_dbus_message_new_method_error (message,
4289 "org.freedesktop.DBus.Error.UnknownMethod",
4290 _("No such method `%s'"),
4291 g_dbus_message_get_member (message));
4292 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4293 g_object_unref (reply);
4298 parameters = g_dbus_message_get_body (message);
4299 if (parameters == NULL)
4301 parameters = g_variant_new ("()");
4302 g_variant_ref_sink (parameters);
4306 g_variant_ref (parameters);
4309 /* Check that the incoming args are of the right type - if they are not, return
4310 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4312 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4313 if (!g_variant_is_of_type (parameters, in_type))
4317 type_string = g_variant_type_dup_string (in_type);
4319 reply = g_dbus_message_new_method_error (message,
4320 "org.freedesktop.DBus.Error.InvalidArgs",
4321 _("Type of message, `%s', does not match expected type `%s'"),
4322 g_variant_get_type_string (parameters),
4324 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4325 g_variant_type_free (in_type);
4326 g_variant_unref (parameters);
4327 g_object_unref (reply);
4328 g_free (type_string);
4332 g_variant_type_free (in_type);
4334 /* schedule the call in idle */
4335 invocation = g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4336 g_dbus_message_get_path (message),
4337 g_dbus_message_get_interface (message),
4338 g_dbus_message_get_member (message),
4344 g_variant_unref (parameters);
4346 /* TODO: would be nicer with a real MethodData like we already
4347 * have PropertyData and PropertyGetAllData... */
4348 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4349 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4350 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4352 idle_source = g_idle_source_new ();
4353 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4354 g_source_set_callback (idle_source,
4358 g_source_attach (idle_source, main_context);
4359 g_source_unref (idle_source);
4367 /* ---------------------------------------------------------------------------------------------------- */
4369 /* called in message handler thread with lock held */
4371 obj_message_func (GDBusConnection *connection,
4373 GDBusMessage *message)
4375 const gchar *interface_name;
4376 const gchar *member;
4377 const gchar *signature;
4382 interface_name = g_dbus_message_get_interface (message);
4383 member = g_dbus_message_get_member (message);
4384 signature = g_dbus_message_get_signature (message);
4386 /* see if we have an interface for handling this call */
4387 if (interface_name != NULL)
4389 ExportedInterface *ei;
4390 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4393 /* we do - invoke the handler in idle in the right thread */
4395 /* handle no vtable or handler being present */
4396 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
4399 handled = validate_and_maybe_schedule_method_call (connection,
4411 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4412 g_strcmp0 (member, "Introspect") == 0 &&
4413 g_strcmp0 (signature, "") == 0)
4415 handled = handle_introspect (connection, eo, message);
4418 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4419 g_strcmp0 (member, "Get") == 0 &&
4420 g_strcmp0 (signature, "ss") == 0)
4422 handled = handle_getset_property (connection, eo, message, TRUE);
4425 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4426 g_strcmp0 (member, "Set") == 0 &&
4427 g_strcmp0 (signature, "ssv") == 0)
4429 handled = handle_getset_property (connection, eo, message, FALSE);
4432 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4433 g_strcmp0 (member, "GetAll") == 0 &&
4434 g_strcmp0 (signature, "s") == 0)
4436 handled = handle_get_all_properties (connection, eo, message);
4445 * g_dbus_connection_register_object:
4446 * @connection: A #GDBusConnection.
4447 * @object_path: The object path to register at.
4448 * @interface_info: Introspection data for the interface.
4449 * @vtable: A #GDBusInterfaceVTable to call into or %NULL.
4450 * @user_data: Data to pass to functions in @vtable.
4451 * @user_data_free_func: Function to call when the object path is unregistered.
4452 * @error: Return location for error or %NULL.
4454 * Registers callbacks for exported objects at @object_path with the
4455 * D-Bus interface that is described in @interface_info.
4457 * Calls to functions in @vtable (and @user_data_free_func) will
4458 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
4459 * loop</link> of the thread you are calling this method from.
4461 * Note that all #GVariant values passed to functions in @vtable will match
4462 * the signature given in @interface_info - if a remote caller passes
4463 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
4464 * is returned to the remote caller.
4466 * Additionally, if the remote caller attempts to invoke methods or
4467 * access properties not mentioned in @interface_info the
4468 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
4469 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
4470 * are returned to the caller.
4472 * It is considered a programming error if the
4473 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
4474 * #GVariant of incorrect type.
4476 * If an existing callback is already registered at @object_path and
4477 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
4479 * GDBus automatically implements the standard D-Bus interfaces
4480 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
4481 * and org.freedesktop.Peer, so you don't have to implement those for
4482 * the objects you export. You <emphasis>can</emphasis> implement
4483 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
4484 * and setting of properties asynchronously.
4486 * Note that the reference count on @interface_info will be
4487 * incremented by 1 (unless allocated statically, e.g. if the
4488 * reference count is -1, see g_dbus_interface_info_ref()) for as long
4489 * as the object is exported. Also note that @vtable will be copied.
4491 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
4493 * Returns: 0 if @error is set, otherwise a registration id (never 0)
4494 * that can be used with g_dbus_connection_unregister_object() .
4499 g_dbus_connection_register_object (GDBusConnection *connection,
4500 const gchar *object_path,
4501 GDBusInterfaceInfo *interface_info,
4502 const GDBusInterfaceVTable *vtable,
4504 GDestroyNotify user_data_free_func,
4508 ExportedInterface *ei;
4511 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4512 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4513 g_return_val_if_fail (interface_info != NULL, 0);
4514 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
4515 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4519 CONNECTION_LOCK (connection);
4521 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
4524 eo = g_new0 (ExportedObject, 1);
4525 eo->object_path = g_strdup (object_path);
4526 eo->connection = connection;
4527 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
4530 (GDestroyNotify) exported_interface_free);
4531 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
4534 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
4540 _("An object is already exported for the interface %s at %s"),
4541 interface_info->name,
4546 ei = g_new0 (ExportedInterface, 1);
4547 ei->id = _global_registration_id++; /* TODO: overflow etc. */
4549 ei->user_data = user_data;
4550 ei->user_data_free_func = user_data_free_func;
4551 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
4552 ei->interface_info = g_dbus_interface_info_ref (interface_info);
4553 ei->interface_name = g_strdup (interface_info->name);
4554 ei->context = g_main_context_get_thread_default ();
4555 if (ei->context != NULL)
4556 g_main_context_ref (ei->context);
4558 g_hash_table_insert (eo->map_if_name_to_ei,
4559 (gpointer) ei->interface_name,
4561 g_hash_table_insert (connection->map_id_to_ei,
4562 GUINT_TO_POINTER (ei->id),
4568 CONNECTION_UNLOCK (connection);
4574 * g_dbus_connection_unregister_object:
4575 * @connection: A #GDBusConnection.
4576 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
4578 * Unregisters an object.
4580 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
4585 g_dbus_connection_unregister_object (GDBusConnection *connection,
4586 guint registration_id)
4588 ExportedInterface *ei;
4592 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4596 CONNECTION_LOCK (connection);
4598 ei = g_hash_table_lookup (connection->map_id_to_ei,
4599 GUINT_TO_POINTER (registration_id));
4605 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
4606 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
4607 /* unregister object path if we have no more exported interfaces */
4608 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
4609 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
4615 CONNECTION_UNLOCK (connection);
4620 /* ---------------------------------------------------------------------------------------------------- */
4623 * g_dbus_connection_emit_signal:
4624 * @connection: A #GDBusConnection.
4625 * @destination_bus_name: The unique bus name for the destination for the signal or %NULL to emit to all listeners.
4626 * @object_path: Path of remote object.
4627 * @interface_name: D-Bus interface to emit a signal on.
4628 * @signal_name: The name of the signal to emit.
4629 * @parameters: A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
4630 * @error: Return location for error or %NULL.
4634 * If the parameters GVariant is floating, it is consumed.
4636 * This can only fail if @parameters is not compatible with the D-Bus protocol.
4638 * Returns: %TRUE unless @error is set.
4643 g_dbus_connection_emit_signal (GDBusConnection *connection,
4644 const gchar *destination_bus_name,
4645 const gchar *object_path,
4646 const gchar *interface_name,
4647 const gchar *signal_name,
4648 GVariant *parameters,
4651 GDBusMessage *message;
4657 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4658 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
4659 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
4660 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
4661 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
4662 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
4664 if (G_UNLIKELY (_g_dbus_debug_emission ()))
4666 _g_dbus_debug_print_lock ();
4667 g_print ("========================================================================\n"
4668 "GDBus-debug:Emission:\n"
4669 " >>>> SIGNAL EMISSION %s.%s()\n"
4671 " destination %s\n",
4672 interface_name, signal_name,
4674 destination_bus_name != NULL ? destination_bus_name : "(none)");
4675 _g_dbus_debug_print_unlock ();
4678 message = g_dbus_message_new_signal (object_path,
4682 if (destination_bus_name != NULL)
4683 g_dbus_message_set_header (message,
4684 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
4685 g_variant_new_string (destination_bus_name));
4687 if (parameters != NULL)
4688 g_dbus_message_set_body (message, parameters);
4690 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
4691 g_object_unref (message);
4697 add_call_flags (GDBusMessage *message,
4698 GDBusCallFlags flags)
4700 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
4701 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
4705 decode_method_reply (GDBusMessage *reply,
4706 const gchar *method_name,
4707 const GVariantType *reply_type,
4713 switch (g_dbus_message_get_message_type (reply))
4715 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
4716 result = g_dbus_message_get_body (reply);
4719 result = g_variant_new ("()");
4720 g_variant_ref_sink (result);
4724 g_variant_ref (result);
4727 if (!g_variant_is_of_type (result, reply_type))
4729 gchar *type_string = g_variant_type_dup_string (reply_type);
4733 G_IO_ERROR_INVALID_ARGUMENT,
4734 _("Method `%s' returned type `%s', but expected `%s'"),
4735 method_name, g_variant_get_type_string (result), type_string);
4737 g_variant_unref (result);
4738 g_free (type_string);
4743 case G_DBUS_MESSAGE_TYPE_ERROR:
4744 g_dbus_message_to_gerror (reply, error);
4748 g_assert_not_reached ();
4758 GSimpleAsyncResult *simple;
4759 GVariantType *reply_type;
4760 gchar *method_name; /* for error message */
4765 g_dbus_connection_call_done (GObject *source,
4766 GAsyncResult *result,
4769 GDBusConnection *connection = G_DBUS_CONNECTION (source);
4770 CallState *state = user_data;
4772 GDBusMessage *reply;
4776 reply = g_dbus_connection_send_message_with_reply_finish (connection,
4780 if (G_UNLIKELY (_g_dbus_debug_call ()))
4782 _g_dbus_debug_print_lock ();
4783 g_print ("========================================================================\n"
4784 "GDBus-debug:Call:\n"
4785 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
4791 g_print ("SUCCESS\n");
4795 g_print ("FAILED: %s\n",
4798 _g_dbus_debug_print_unlock ();
4804 value = decode_method_reply (reply, state->method_name,
4805 state->reply_type, &error);
4806 g_object_unref (reply);
4813 g_simple_async_result_set_from_error (state->simple, error);
4814 g_error_free (error);
4817 g_simple_async_result_set_op_res_gpointer (state->simple, value,
4818 (GDestroyNotify) g_variant_unref);
4820 g_simple_async_result_complete (state->simple);
4821 g_variant_type_free (state->reply_type);
4822 g_object_unref (state->simple);
4823 g_free (state->method_name);
4825 g_slice_free (CallState, state);
4829 * g_dbus_connection_call:
4830 * @connection: A #GDBusConnection.
4831 * @bus_name: A unique or well-known bus name or %NULL if @connection is not a message bus connection.
4832 * @object_path: Path of remote object.
4833 * @interface_name: D-Bus interface to invoke method on.
4834 * @method_name: The name of the method to invoke.
4835 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4836 * @reply_type: The expected type of the reply, or %NULL.
4837 * @flags: Flags from the #GDBusCallFlags enumeration.
4838 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4839 * @cancellable: A #GCancellable or %NULL.
4840 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
4841 * care about the result of the method invocation.
4842 * @user_data: The data to pass to @callback.
4844 * Asynchronously invokes the @method_name method on the
4845 * @interface_name D-Bus interface on the remote object at
4846 * @object_path owned by @bus_name.
4848 * If @connection is closed then the operation will fail with
4849 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
4850 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
4851 * not compatible with the D-Bus protocol, the operation fails with
4852 * %G_IO_ERROR_INVALID_ARGUMENT.
4854 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
4855 * error will be raised if it does not match. Said another way, if you give a @reply_type
4856 * then any non-%NULL return value will be of this type.
4858 * If the @parameters #GVariant is floating, it is consumed. This allows
4859 * convenient 'inline' use of g_variant_new(), e.g.:
4861 * g_dbus_connection_call (connection,
4862 * "org.freedesktop.StringThings",
4863 * "/org/freedesktop/StringThings",
4864 * "org.freedesktop.StringThings",
4866 * g_variant_new ("(ss)",
4870 * G_DBUS_CALL_FLAGS_NONE,
4873 * (GAsyncReadyCallback) two_strings_done,
4877 * This is an asynchronous method. When the operation is finished, @callback will be invoked
4878 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
4879 * of the thread you are calling this method from. You can then call
4880 * g_dbus_connection_call_finish() to get the result of the operation.
4881 * See g_dbus_connection_call_sync() for the synchronous version of this
4887 g_dbus_connection_call (GDBusConnection *connection,
4888 const gchar *bus_name,
4889 const gchar *object_path,
4890 const gchar *interface_name,
4891 const gchar *method_name,
4892 GVariant *parameters,
4893 const GVariantType *reply_type,
4894 GDBusCallFlags flags,
4896 GCancellable *cancellable,
4897 GAsyncReadyCallback callback,
4900 GDBusMessage *message;
4903 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4904 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
4905 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
4906 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
4907 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
4908 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
4909 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
4911 state = g_slice_new (CallState);
4912 state->simple = g_simple_async_result_new (G_OBJECT (connection),
4913 callback, user_data,
4914 g_dbus_connection_call);
4915 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
4917 if (reply_type == NULL)
4918 reply_type = G_VARIANT_TYPE_ANY;
4920 state->reply_type = g_variant_type_copy (reply_type);
4922 message = g_dbus_message_new_method_call (bus_name,
4926 add_call_flags (message, flags);
4927 if (parameters != NULL)
4928 g_dbus_message_set_body (message, parameters);
4930 g_dbus_connection_send_message_with_reply (connection,
4932 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
4936 g_dbus_connection_call_done,
4939 if (G_UNLIKELY (_g_dbus_debug_call ()))
4941 _g_dbus_debug_print_lock ();
4942 g_print ("========================================================================\n"
4943 "GDBus-debug:Call:\n"
4944 " >>>> ASYNC %s.%s()\n"
4946 " owned by name %s (serial %d)\n",
4950 bus_name != NULL ? bus_name : "(none)",
4952 _g_dbus_debug_print_unlock ();
4955 if (message != NULL)
4956 g_object_unref (message);
4960 * g_dbus_connection_call_finish:
4961 * @connection: A #GDBusConnection.
4962 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
4963 * @error: Return location for error or %NULL.
4965 * Finishes an operation started with g_dbus_connection_call().
4967 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4968 * return values. Free with g_variant_unref().
4973 g_dbus_connection_call_finish (GDBusConnection *connection,
4977 GSimpleAsyncResult *simple;
4979 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4980 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
4981 g_dbus_connection_call), NULL);
4982 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4984 simple = G_SIMPLE_ASYNC_RESULT (res);
4986 if (g_simple_async_result_propagate_error (simple, error))
4989 return g_variant_ref (g_simple_async_result_get_op_res_gpointer (simple));
4992 /* ---------------------------------------------------------------------------------------------------- */
4995 * g_dbus_connection_call_sync:
4996 * @connection: A #GDBusConnection.
4997 * @bus_name: A unique or well-known bus name.
4998 * @object_path: Path of remote object.
4999 * @interface_name: D-Bus interface to invoke method on.
5000 * @method_name: The name of the method to invoke.
5001 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
5002 * @reply_type: The expected type of the reply, or %NULL.
5003 * @flags: Flags from the #GDBusCallFlags enumeration.
5004 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
5005 * @cancellable: A #GCancellable or %NULL.
5006 * @error: Return location for error or %NULL.
5008 * Synchronously invokes the @method_name method on the
5009 * @interface_name D-Bus interface on the remote object at
5010 * @object_path owned by @bus_name.
5012 * If @connection is closed then the operation will fail with
5013 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
5014 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
5015 * contains a value not compatible with the D-Bus protocol, the operation
5016 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
5018 * If @reply_type is non-%NULL then the reply will be checked for having
5019 * this type and an error will be raised if it does not match. Said
5020 * another way, if you give a @reply_type then any non-%NULL return
5021 * value will be of this type.
5023 * If the @parameters #GVariant is floating, it is consumed.
5024 * This allows convenient 'inline' use of g_variant_new(), e.g.:
5026 * g_dbus_connection_call_sync (connection,
5027 * "org.freedesktop.StringThings",
5028 * "/org/freedesktop/StringThings",
5029 * "org.freedesktop.StringThings",
5031 * g_variant_new ("(ss)",
5035 * G_DBUS_CALL_FLAGS_NONE,
5041 * The calling thread is blocked until a reply is received. See
5042 * g_dbus_connection_call() for the asynchronous version of
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_sync (GDBusConnection *connection,
5052 const gchar *bus_name,
5053 const gchar *object_path,
5054 const gchar *interface_name,
5055 const gchar *method_name,
5056 GVariant *parameters,
5057 const GVariantType *reply_type,
5058 GDBusCallFlags flags,
5060 GCancellable *cancellable,
5063 GDBusMessage *message;
5064 GDBusMessage *reply;
5066 GError *local_error;
5072 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5073 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5074 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5075 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5076 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5077 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5078 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5080 if (reply_type == NULL)
5081 reply_type = G_VARIANT_TYPE_ANY;
5083 message = g_dbus_message_new_method_call (bus_name,
5087 add_call_flags (message, flags);
5088 if (parameters != NULL)
5089 g_dbus_message_set_body (message, parameters);
5091 if (G_UNLIKELY (_g_dbus_debug_call ()))
5093 _g_dbus_debug_print_lock ();
5094 g_print ("========================================================================\n"
5095 "GDBus-debug:Call:\n"
5096 " >>>> SYNC %s.%s()\n"
5098 " owned by name %s\n",
5102 bus_name != NULL ? bus_name : "(none)");
5103 _g_dbus_debug_print_unlock ();
5107 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5109 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5111 NULL, /* volatile guint32 *out_serial */
5115 if (G_UNLIKELY (_g_dbus_debug_call ()))
5117 _g_dbus_debug_print_lock ();
5118 g_print ("========================================================================\n"
5119 "GDBus-debug:Call:\n"
5120 " <<<< SYNC COMPLETE %s.%s()\n"
5126 g_print ("SUCCESS\n");
5130 g_print ("FAILED: %s\n",
5131 local_error->message);
5133 _g_dbus_debug_print_unlock ();
5139 *error = local_error;
5141 g_error_free (local_error);
5145 result = decode_method_reply (reply, method_name, reply_type, error);
5148 if (message != NULL)
5149 g_object_unref (message);
5151 g_object_unref (reply);
5156 /* ---------------------------------------------------------------------------------------------------- */
5158 struct ExportedSubtree
5162 GDBusConnection *connection;
5163 GDBusSubtreeVTable *vtable;
5164 GDBusSubtreeFlags flags;
5166 GMainContext *context;
5168 GDestroyNotify user_data_free_func;
5172 exported_subtree_free (ExportedSubtree *es)
5174 if (es->user_data_free_func != NULL)
5175 /* TODO: push to thread-default mainloop */
5176 es->user_data_free_func (es->user_data);
5178 if (es->context != NULL)
5179 g_main_context_unref (es->context);
5181 _g_dbus_subtree_vtable_free (es->vtable);
5182 g_free (es->object_path);
5186 /* called without lock held */
5188 handle_subtree_introspect (GDBusConnection *connection,
5189 ExportedSubtree *es,
5190 GDBusMessage *message)
5194 GDBusMessage *reply;
5197 const gchar *sender;
5198 const gchar *requested_object_path;
5199 const gchar *requested_node;
5200 GDBusInterfaceInfo **interfaces;
5202 gchar **subnode_paths;
5206 requested_object_path = g_dbus_message_get_path (message);
5207 sender = g_dbus_message_get_sender (message);
5208 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5210 s = g_string_new (NULL);
5211 introspect_append_header (s);
5213 /* Strictly we don't need the children in dynamic mode, but we avoid the
5214 * conditionals to preserve code clarity
5216 children = es->vtable->enumerate (es->connection,
5223 requested_node = strrchr (requested_object_path, '/') + 1;
5225 /* Assert existence of object if we are not dynamic */
5226 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
5227 !_g_strv_has_string ((const gchar * const *) children, requested_node))
5232 requested_node = NULL;
5235 interfaces = es->vtable->introspect (es->connection,
5240 if (interfaces != NULL)
5242 introspect_append_standard_interfaces (s);
5244 for (n = 0; interfaces[n] != NULL; n++)
5246 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
5247 g_dbus_interface_info_unref (interfaces[n]);
5249 g_free (interfaces);
5252 /* then include <node> entries from the Subtree for the root */
5255 for (n = 0; children != NULL && children[n] != NULL; n++)
5256 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
5259 /* finally include nodes registered below us */
5260 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
5261 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
5262 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
5263 g_strfreev (subnode_paths);
5265 g_string_append (s, "</node>\n");
5267 reply = g_dbus_message_new_method_reply (message);
5268 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5269 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5270 g_object_unref (reply);
5275 g_string_free (s, TRUE);
5276 g_strfreev (children);
5280 /* called without lock held */
5282 handle_subtree_method_invocation (GDBusConnection *connection,
5283 ExportedSubtree *es,
5284 GDBusMessage *message)
5287 const gchar *sender;
5288 const gchar *interface_name;
5289 const gchar *member;
5290 const gchar *signature;
5291 const gchar *requested_object_path;
5292 const gchar *requested_node;
5294 GDBusInterfaceInfo *interface_info;
5295 const GDBusInterfaceVTable *interface_vtable;
5296 gpointer interface_user_data;
5298 GDBusInterfaceInfo **interfaces;
5299 gboolean is_property_get;
5300 gboolean is_property_set;
5301 gboolean is_property_get_all;
5306 requested_object_path = g_dbus_message_get_path (message);
5307 sender = g_dbus_message_get_sender (message);
5308 interface_name = g_dbus_message_get_interface (message);
5309 member = g_dbus_message_get_member (message);
5310 signature = g_dbus_message_get_signature (message);
5311 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5313 is_property_get = FALSE;
5314 is_property_set = FALSE;
5315 is_property_get_all = FALSE;
5316 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
5318 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
5319 is_property_get = TRUE;
5320 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
5321 is_property_set = TRUE;
5322 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
5323 is_property_get_all = TRUE;
5328 requested_node = strrchr (requested_object_path, '/') + 1;
5330 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
5332 /* We don't want to dispatch to unenumerated
5333 * nodes, so ensure that the child exists.
5338 children = es->vtable->enumerate (es->connection,
5343 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
5344 g_strfreev (children);
5352 requested_node = NULL;
5355 /* get introspection data for the node */
5356 interfaces = es->vtable->introspect (es->connection,
5358 requested_object_path,
5362 if (interfaces == NULL)
5365 interface_info = NULL;
5366 for (n = 0; interfaces[n] != NULL; n++)
5368 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
5369 interface_info = interfaces[n];
5372 /* dispatch the call if the user wants to handle it */
5373 if (interface_info != NULL)
5375 /* figure out where to dispatch the method call */
5376 interface_user_data = NULL;
5377 interface_vtable = es->vtable->dispatch (es->connection,
5382 &interface_user_data,
5384 if (interface_vtable == NULL)
5387 CONNECTION_LOCK (connection);
5388 handled = validate_and_maybe_schedule_method_call (es->connection,
5395 interface_user_data);
5396 CONNECTION_UNLOCK (connection);
5398 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
5399 else if (is_property_get || is_property_set || is_property_get_all)
5401 if (is_property_get)
5402 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
5403 else if (is_property_set)
5404 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
5405 else if (is_property_get_all)
5406 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
5408 g_assert_not_reached ();
5410 /* see if the object supports this interface at all */
5411 for (n = 0; interfaces[n] != NULL; n++)
5413 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
5414 interface_info = interfaces[n];
5417 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
5418 * claims it won't support the interface
5420 if (interface_info == NULL)
5422 GDBusMessage *reply;
5423 reply = g_dbus_message_new_method_error (message,
5424 "org.freedesktop.DBus.Error.InvalidArgs",
5425 _("No such interface `%s'"),
5427 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5428 g_object_unref (reply);
5433 /* figure out where to dispatch the property get/set/getall calls */
5434 interface_user_data = NULL;
5435 interface_vtable = es->vtable->dispatch (es->connection,
5440 &interface_user_data,
5442 if (interface_vtable == NULL)
5444 g_warning ("The subtree introspection function indicates that '%s' "
5445 "is a valid interface name, but calling the dispatch "
5446 "function on that interface gave us NULL", interface_name);
5450 if (is_property_get || is_property_set)
5452 CONNECTION_LOCK (connection);
5453 handled = validate_and_maybe_schedule_property_getset (es->connection,
5461 interface_user_data);
5462 CONNECTION_UNLOCK (connection);
5464 else if (is_property_get_all)
5466 CONNECTION_LOCK (connection);
5467 handled = validate_and_maybe_schedule_property_get_all (es->connection,
5474 interface_user_data);
5475 CONNECTION_UNLOCK (connection);
5480 if (interfaces != NULL)
5482 for (n = 0; interfaces[n] != NULL; n++)
5483 g_dbus_interface_info_unref (interfaces[n]);
5484 g_free (interfaces);
5492 GDBusMessage *message;
5493 ExportedSubtree *es;
5494 } SubtreeDeferredData;
5497 subtree_deferred_data_free (SubtreeDeferredData *data)
5499 g_object_unref (data->message);
5503 /* called without lock held in the thread where the caller registered the subtree */
5505 process_subtree_vtable_message_in_idle_cb (gpointer _data)
5507 SubtreeDeferredData *data = _data;
5512 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
5513 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
5514 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
5515 handled = handle_subtree_introspect (data->es->connection,
5519 handled = handle_subtree_method_invocation (data->es->connection,
5525 CONNECTION_LOCK (data->es->connection);
5526 handled = handle_generic_unlocked (data->es->connection, data->message);
5527 CONNECTION_UNLOCK (data->es->connection);
5530 /* if we couldn't handle the request, just bail with the UnknownMethod error */
5533 GDBusMessage *reply;
5534 reply = g_dbus_message_new_method_error (data->message,
5535 "org.freedesktop.DBus.Error.UnknownMethod",
5536 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
5537 g_dbus_message_get_member (data->message),
5538 g_dbus_message_get_interface (data->message),
5539 g_dbus_message_get_signature (data->message));
5540 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5541 g_object_unref (reply);
5547 /* called in message handler thread with lock held */
5549 subtree_message_func (GDBusConnection *connection,
5550 ExportedSubtree *es,
5551 GDBusMessage *message)
5553 GSource *idle_source;
5554 SubtreeDeferredData *data;
5556 data = g_new0 (SubtreeDeferredData, 1);
5557 data->message = g_object_ref (message);
5560 /* defer this call to an idle handler in the right thread */
5561 idle_source = g_idle_source_new ();
5562 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
5563 g_source_set_callback (idle_source,
5564 process_subtree_vtable_message_in_idle_cb,
5566 (GDestroyNotify) subtree_deferred_data_free);
5567 g_source_attach (idle_source, es->context);
5568 g_source_unref (idle_source);
5570 /* since we own the entire subtree, handlers for objects not in the subtree have been
5571 * tried already by libdbus-1 - so we just need to ensure that we're always going
5572 * to reply to the message
5578 * g_dbus_connection_register_subtree:
5579 * @connection: A #GDBusConnection.
5580 * @object_path: The object path to register the subtree at.
5581 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
5582 * @flags: Flags used to fine tune the behavior of the subtree.
5583 * @user_data: Data to pass to functions in @vtable.
5584 * @user_data_free_func: Function to call when the subtree is unregistered.
5585 * @error: Return location for error or %NULL.
5587 * Registers a whole subtree of <quote>dynamic</quote> objects.
5589 * The @enumerate and @introspection functions in @vtable are used to
5590 * convey, to remote callers, what nodes exist in the subtree rooted
5593 * When handling remote calls into any node in the subtree, first the
5594 * @enumerate function is used to check if the node exists. If the node exists
5595 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
5596 * the @introspection function is used to check if the node supports the
5597 * requested method. If so, the @dispatch function is used to determine
5598 * where to dispatch the call. The collected #GDBusInterfaceVTable and
5599 * #gpointer will be used to call into the interface vtable for processing
5602 * All calls into user-provided code will be invoked in the <link
5603 * linkend="g-main-context-push-thread-default">thread-default main
5604 * loop</link> of the thread you are calling this method from.
5606 * If an existing subtree is already registered at @object_path or
5607 * then @error is set to #G_IO_ERROR_EXISTS.
5609 * Note that it is valid to register regular objects (using
5610 * g_dbus_connection_register_object()) in a subtree registered with
5611 * g_dbus_connection_register_subtree() - if so, the subtree handler
5612 * is tried as the last resort. One way to think about a subtree
5613 * handler is to consider it a <quote>fallback handler</quote>
5614 * for object paths not registered via g_dbus_connection_register_object()
5615 * or other bindings.
5617 * Note that @vtable will be copied so you cannot change it after
5620 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
5622 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
5623 * that can be used with g_dbus_connection_unregister_subtree() .
5628 g_dbus_connection_register_subtree (GDBusConnection *connection,
5629 const gchar *object_path,
5630 const GDBusSubtreeVTable *vtable,
5631 GDBusSubtreeFlags flags,
5633 GDestroyNotify user_data_free_func,
5637 ExportedSubtree *es;
5639 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5640 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5641 g_return_val_if_fail (vtable != NULL, 0);
5642 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5646 CONNECTION_LOCK (connection);
5648 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
5654 _("A subtree is already exported for %s"),
5659 es = g_new0 (ExportedSubtree, 1);
5660 es->object_path = g_strdup (object_path);
5661 es->connection = connection;
5663 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
5665 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
5666 es->user_data = user_data;
5667 es->user_data_free_func = user_data_free_func;
5668 es->context = g_main_context_get_thread_default ();
5669 if (es->context != NULL)
5670 g_main_context_ref (es->context);
5672 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
5673 g_hash_table_insert (connection->map_id_to_es,
5674 GUINT_TO_POINTER (es->id),
5680 CONNECTION_UNLOCK (connection);
5685 /* ---------------------------------------------------------------------------------------------------- */
5688 * g_dbus_connection_unregister_subtree:
5689 * @connection: A #GDBusConnection.
5690 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
5692 * Unregisters a subtree.
5694 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
5699 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
5700 guint registration_id)
5702 ExportedSubtree *es;
5705 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5709 CONNECTION_LOCK (connection);
5711 es = g_hash_table_lookup (connection->map_id_to_es,
5712 GUINT_TO_POINTER (registration_id));
5716 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
5717 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
5722 CONNECTION_UNLOCK (connection);
5727 /* ---------------------------------------------------------------------------------------------------- */
5729 /* must be called with lock held */
5731 handle_generic_ping_unlocked (GDBusConnection *connection,
5732 const gchar *object_path,
5733 GDBusMessage *message)
5735 GDBusMessage *reply;
5736 reply = g_dbus_message_new_method_reply (message);
5737 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5738 g_object_unref (reply);
5741 /* must be called with lock held */
5743 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
5744 const gchar *object_path,
5745 GDBusMessage *message)
5747 GDBusMessage *reply;
5750 if (connection->machine_id == NULL)
5755 connection->machine_id = _g_dbus_get_machine_id (&error);
5756 if (connection->machine_id == NULL)
5758 reply = g_dbus_message_new_method_error_literal (message,
5759 "org.freedesktop.DBus.Error.Failed",
5761 g_error_free (error);
5767 reply = g_dbus_message_new_method_reply (message);
5768 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
5770 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5771 g_object_unref (reply);
5774 /* must be called with lock held */
5776 handle_generic_introspect_unlocked (GDBusConnection *connection,
5777 const gchar *object_path,
5778 GDBusMessage *message)
5783 GDBusMessage *reply;
5785 /* first the header */
5786 s = g_string_new (NULL);
5787 introspect_append_header (s);
5789 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
5790 for (n = 0; registered != NULL && registered[n] != NULL; n++)
5791 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
5792 g_strfreev (registered);
5793 g_string_append (s, "</node>\n");
5795 reply = g_dbus_message_new_method_reply (message);
5796 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5797 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5798 g_object_unref (reply);
5799 g_string_free (s, TRUE);
5802 /* must be called with lock held */
5804 handle_generic_unlocked (GDBusConnection *connection,
5805 GDBusMessage *message)
5808 const gchar *interface_name;
5809 const gchar *member;
5810 const gchar *signature;
5813 CONNECTION_ENSURE_LOCK (connection);
5817 interface_name = g_dbus_message_get_interface (message);
5818 member = g_dbus_message_get_member (message);
5819 signature = g_dbus_message_get_signature (message);
5820 path = g_dbus_message_get_path (message);
5822 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5823 g_strcmp0 (member, "Introspect") == 0 &&
5824 g_strcmp0 (signature, "") == 0)
5826 handle_generic_introspect_unlocked (connection, path, message);
5829 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5830 g_strcmp0 (member, "Ping") == 0 &&
5831 g_strcmp0 (signature, "") == 0)
5833 handle_generic_ping_unlocked (connection, path, message);
5836 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5837 g_strcmp0 (member, "GetMachineId") == 0 &&
5838 g_strcmp0 (signature, "") == 0)
5840 handle_generic_get_machine_id_unlocked (connection, path, message);
5847 /* ---------------------------------------------------------------------------------------------------- */
5849 /* called in message handler thread with lock held */
5851 distribute_method_call (GDBusConnection *connection,
5852 GDBusMessage *message)
5854 GDBusMessage *reply;
5856 ExportedSubtree *es;
5857 const gchar *object_path;
5858 const gchar *interface_name;
5859 const gchar *member;
5860 const gchar *signature;
5862 gchar *subtree_path;
5865 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
5867 interface_name = g_dbus_message_get_interface (message);
5868 member = g_dbus_message_get_member (message);
5869 signature = g_dbus_message_get_signature (message);
5870 path = g_dbus_message_get_path (message);
5871 subtree_path = g_strdup (path);
5872 needle = strrchr (subtree_path, '/');
5873 if (needle != NULL && needle != subtree_path)
5879 g_free (subtree_path);
5880 subtree_path = NULL;
5884 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
5886 _g_dbus_debug_print_lock ();
5887 g_print ("========================================================================\n"
5888 "GDBus-debug:Incoming:\n"
5889 " <<<< METHOD INVOCATION %s.%s()\n"
5891 " invoked by name %s\n",
5892 interface_name, member,
5894 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)");
5895 _g_dbus_debug_print_unlock ();
5899 g_debug ("interface = `%s'", interface_name);
5900 g_debug ("member = `%s'", member);
5901 g_debug ("signature = `%s'", signature);
5902 g_debug ("path = `%s'", path);
5903 g_debug ("subtree_path = `%s'", subtree_path != NULL ? subtree_path : "N/A");
5906 object_path = g_dbus_message_get_path (message);
5907 g_assert (object_path != NULL);
5909 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5912 if (obj_message_func (connection, eo, message))
5916 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
5919 if (subtree_message_func (connection, es, message))
5923 if (subtree_path != NULL)
5925 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
5928 if (subtree_message_func (connection, es, message))
5933 if (handle_generic_unlocked (connection, message))
5936 /* if we end up here, the message has not been not handled - so return an error saying this */
5937 reply = g_dbus_message_new_method_error (message,
5938 "org.freedesktop.DBus.Error.UnknownMethod",
5939 _("No such interface `%s' on object at path %s"),
5942 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5943 g_object_unref (reply);
5946 g_free (subtree_path);
5949 /* ---------------------------------------------------------------------------------------------------- */
5951 static GDBusConnection **
5952 message_bus_get_singleton (GBusType bus_type,
5955 GDBusConnection **ret;
5956 const gchar *starter_bus;
5962 case G_BUS_TYPE_SESSION:
5963 ret = &the_session_bus;
5966 case G_BUS_TYPE_SYSTEM:
5967 ret = &the_system_bus;
5970 case G_BUS_TYPE_STARTER:
5971 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
5972 if (g_strcmp0 (starter_bus, "session") == 0)
5974 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
5977 else if (g_strcmp0 (starter_bus, "system") == 0)
5979 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
5984 if (starter_bus != NULL)
5988 G_IO_ERROR_INVALID_ARGUMENT,
5989 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
5990 " - unknown value `%s'"),
5995 g_set_error_literal (error,
5997 G_IO_ERROR_INVALID_ARGUMENT,
5998 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
5999 "variable is not set"));
6005 g_assert_not_reached ();
6013 static GDBusConnection *
6014 get_uninitialized_connection (GBusType bus_type,
6015 GCancellable *cancellable,
6018 GDBusConnection **singleton;
6019 GDBusConnection *ret;
6023 G_LOCK (message_bus_lock);
6024 singleton = message_bus_get_singleton (bus_type, error);
6025 if (singleton == NULL)
6028 if (*singleton == NULL)
6031 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
6032 if (address == NULL)
6034 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
6036 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
6037 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
6038 "exit-on-close", TRUE,
6044 ret = g_object_ref (*singleton);
6047 g_assert (ret != NULL);
6050 G_UNLOCK (message_bus_lock);
6056 * @bus_type: A #GBusType.
6057 * @cancellable: A #GCancellable or %NULL.
6058 * @error: Return location for error or %NULL.
6060 * Synchronously connects to the message bus specified by @bus_type.
6061 * Note that the returned object may shared with other callers,
6062 * e.g. if two separate parts of a process calls this function with
6063 * the same @bus_type, they will share the same object.
6065 * This is a synchronous failable function. See g_bus_get() and
6066 * g_bus_get_finish() for the asynchronous version.
6068 * The returned object is a singleton, that is, shared with other
6069 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6070 * event that you need a private message bus connection, use
6071 * g_dbus_address_get_for_bus_sync() and
6072 * g_dbus_connection_new_for_address().
6074 * Note that the returned #GDBusConnection object will (usually) have
6075 * the #GDBusConnection:exit-on-close property set to %TRUE.
6077 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6082 g_bus_get_sync (GBusType bus_type,
6083 GCancellable *cancellable,
6086 GDBusConnection *connection;
6088 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6090 connection = get_uninitialized_connection (bus_type, cancellable, error);
6091 if (connection == NULL)
6094 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
6096 g_object_unref (connection);
6105 bus_get_async_initable_cb (GObject *source_object,
6109 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
6113 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
6117 g_assert (error != NULL);
6118 g_simple_async_result_set_from_error (simple, error);
6119 g_error_free (error);
6120 g_object_unref (source_object);
6124 g_simple_async_result_set_op_res_gpointer (simple,
6128 g_simple_async_result_complete_in_idle (simple);
6129 g_object_unref (simple);
6134 * @bus_type: A #GBusType.
6135 * @cancellable: A #GCancellable or %NULL.
6136 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
6137 * @user_data: The data to pass to @callback.
6139 * Asynchronously connects to the message bus specified by @bus_type.
6141 * When the operation is finished, @callback will be invoked. You can
6142 * then call g_bus_get_finish() to get the result of the operation.
6144 * This is a asynchronous failable function. See g_bus_get_sync() for
6145 * the synchronous version.
6150 g_bus_get (GBusType bus_type,
6151 GCancellable *cancellable,
6152 GAsyncReadyCallback callback,
6155 GDBusConnection *connection;
6156 GSimpleAsyncResult *simple;
6159 simple = g_simple_async_result_new (NULL,
6165 connection = get_uninitialized_connection (bus_type, cancellable, &error);
6166 if (connection == NULL)
6168 g_assert (error != NULL);
6169 g_simple_async_result_set_from_error (simple, error);
6170 g_error_free (error);
6171 g_simple_async_result_complete_in_idle (simple);
6172 g_object_unref (simple);
6176 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
6179 bus_get_async_initable_cb,
6186 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
6187 * @error: Return location for error or %NULL.
6189 * Finishes an operation started with g_bus_get().
6191 * The returned object is a singleton, that is, shared with other
6192 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6193 * event that you need a private message bus connection, use
6194 * g_dbus_address_get_for_bus() and
6195 * g_dbus_connection_new_for_address().
6197 * Note that the returned #GDBusConnection object will (usually) have
6198 * the #GDBusConnection:exit-on-close property set to %TRUE.
6200 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6205 g_bus_get_finish (GAsyncResult *res,
6208 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
6210 GDBusConnection *ret;
6212 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6214 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
6218 if (g_simple_async_result_propagate_error (simple, error))
6221 object = g_simple_async_result_get_op_res_gpointer (simple);
6222 g_assert (object != NULL);
6223 ret = g_object_ref (G_DBUS_CONNECTION (object));
6229 /* ---------------------------------------------------------------------------------------------------- */