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)
556 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
562 g_dbus_connection_class_init (GDBusConnectionClass *klass)
564 GObjectClass *gobject_class;
566 gobject_class = G_OBJECT_CLASS (klass);
568 gobject_class->finalize = g_dbus_connection_finalize;
569 gobject_class->dispose = g_dbus_connection_dispose;
570 gobject_class->set_property = g_dbus_connection_set_property;
571 gobject_class->get_property = g_dbus_connection_get_property;
573 klass->closed = g_dbus_connection_real_closed;
576 * GDBusConnection:stream:
578 * The underlying #GIOStream used for I/O.
582 g_object_class_install_property (gobject_class,
584 g_param_spec_object ("stream",
586 P_("The underlying streams used for I/O"),
590 G_PARAM_CONSTRUCT_ONLY |
591 G_PARAM_STATIC_NAME |
592 G_PARAM_STATIC_BLURB |
593 G_PARAM_STATIC_NICK));
596 * GDBusConnection:address:
598 * A D-Bus address specifying potential endpoints that can be used
599 * when establishing the connection.
603 g_object_class_install_property (gobject_class,
605 g_param_spec_string ("address",
607 P_("D-Bus address specifying potential socket endpoints"),
610 G_PARAM_CONSTRUCT_ONLY |
611 G_PARAM_STATIC_NAME |
612 G_PARAM_STATIC_BLURB |
613 G_PARAM_STATIC_NICK));
616 * GDBusConnection:flags:
618 * Flags from the #GDBusConnectionFlags enumeration.
622 g_object_class_install_property (gobject_class,
624 g_param_spec_flags ("flags",
627 G_TYPE_DBUS_CONNECTION_FLAGS,
628 G_DBUS_CONNECTION_FLAGS_NONE,
630 G_PARAM_CONSTRUCT_ONLY |
631 G_PARAM_STATIC_NAME |
632 G_PARAM_STATIC_BLURB |
633 G_PARAM_STATIC_NICK));
636 * GDBusConnection:guid:
638 * The GUID of the peer performing the role of server when
641 * If you are constructing a #GDBusConnection and pass
642 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
643 * #GDBusConnection:flags property then you MUST also set this
644 * property to a valid guid.
646 * If you are constructing a #GDBusConnection and pass
647 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
648 * #GDBusConnection:flags property you will be able to read the GUID
649 * of the other peer here after the connection has been successfully
654 g_object_class_install_property (gobject_class,
656 g_param_spec_string ("guid",
658 P_("GUID of the server peer"),
662 G_PARAM_CONSTRUCT_ONLY |
663 G_PARAM_STATIC_NAME |
664 G_PARAM_STATIC_BLURB |
665 G_PARAM_STATIC_NICK));
668 * GDBusConnection:unique-name:
670 * The unique name as assigned by the message bus or %NULL if the
671 * connection is not open or not a message bus connection.
675 g_object_class_install_property (gobject_class,
677 g_param_spec_string ("unique-name",
679 P_("Unique name of bus connection"),
682 G_PARAM_STATIC_NAME |
683 G_PARAM_STATIC_BLURB |
684 G_PARAM_STATIC_NICK));
687 * GDBusConnection:closed:
689 * A boolean specifying whether the connection has been closed.
693 g_object_class_install_property (gobject_class,
695 g_param_spec_boolean ("closed",
697 P_("Whether the connection is closed"),
700 G_PARAM_STATIC_NAME |
701 G_PARAM_STATIC_BLURB |
702 G_PARAM_STATIC_NICK));
705 * GDBusConnection:exit-on-close:
707 * A boolean specifying whether the process will be terminated (by
708 * calling <literal>raise(SIGTERM)</literal>) if the connection
709 * is closed by the remote peer.
713 g_object_class_install_property (gobject_class,
715 g_param_spec_boolean ("exit-on-close",
717 P_("Whether the process is terminated when the connection is closed"),
721 G_PARAM_STATIC_NAME |
722 G_PARAM_STATIC_BLURB |
723 G_PARAM_STATIC_NICK));
726 * GDBusConnection:capabilities:
728 * Flags from the #GDBusCapabilityFlags enumeration
729 * representing connection features negotiated with the other peer.
733 g_object_class_install_property (gobject_class,
734 PROP_CAPABILITY_FLAGS,
735 g_param_spec_flags ("capabilities",
738 G_TYPE_DBUS_CAPABILITY_FLAGS,
739 G_DBUS_CAPABILITY_FLAGS_NONE,
741 G_PARAM_STATIC_NAME |
742 G_PARAM_STATIC_BLURB |
743 G_PARAM_STATIC_NICK));
746 * GDBusConnection:authentication-observer:
748 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
752 g_object_class_install_property (gobject_class,
753 PROP_AUTHENTICATION_OBSERVER,
754 g_param_spec_object ("authentication-observer",
755 P_("Authentication Observer"),
756 P_("Object used to assist in the authentication process"),
757 G_TYPE_DBUS_AUTH_OBSERVER,
759 G_PARAM_CONSTRUCT_ONLY |
760 G_PARAM_STATIC_NAME |
761 G_PARAM_STATIC_BLURB |
762 G_PARAM_STATIC_NICK));
765 * GDBusConnection::closed:
766 * @connection: The #GDBusConnection emitting the signal.
767 * @remote_peer_vanished: %TRUE if @connection is closed because the
768 * remote peer closed its end of the connection.
769 * @error: A #GError with more details about the event or %NULL.
771 * Emitted when the connection is closed.
773 * The cause of this event can be
776 * If g_dbus_connection_close() is called. In this case
777 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
780 * If the remote peer closes the connection. In this case
781 * @remote_peer_vanished is set to %TRUE and @error is set.
784 * If the remote peer sends invalid or malformed data. In this
785 * case @remote_peer_vanished is set to %FALSE and @error
790 * Upon receiving this signal, you should give up your reference to
791 * @connection. You are guaranteed that this signal is emitted only
796 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
797 G_TYPE_DBUS_CONNECTION,
799 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
802 _gio_marshal_VOID__BOOLEAN_BOXED,
810 g_dbus_connection_init (GDBusConnection *connection)
812 connection->lock = g_mutex_new ();
813 connection->init_lock = g_mutex_new ();
815 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
817 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
819 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
821 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
826 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
829 (GDestroyNotify) exported_object_free);
831 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
834 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
837 (GDestroyNotify) exported_subtree_free);
839 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
842 connection->main_context_at_construction = g_main_context_get_thread_default ();
843 if (connection->main_context_at_construction != NULL)
844 g_main_context_ref (connection->main_context_at_construction);
846 connection->filters = g_ptr_array_new ();
850 * g_dbus_connection_get_stream:
851 * @connection: a #GDBusConnection
853 * Gets the underlying stream used for IO.
855 * Returns: the stream used for IO
860 g_dbus_connection_get_stream (GDBusConnection *connection)
862 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
863 return connection->stream;
867 * g_dbus_connection_start_message_processing:
868 * @connection: A #GDBusConnection.
870 * If @connection was created with
871 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
872 * starts processing messages. Does nothing on if @connection wasn't
873 * created with this flag or if the method has already been called.
878 g_dbus_connection_start_message_processing (GDBusConnection *connection)
880 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
881 _g_dbus_worker_unfreeze (connection->worker);
885 * g_dbus_connection_is_closed:
886 * @connection: A #GDBusConnection.
888 * Gets whether @connection is closed.
890 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
895 g_dbus_connection_is_closed (GDBusConnection *connection)
897 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
898 return connection->closed;
902 * g_dbus_connection_get_capabilities:
903 * @connection: A #GDBusConnection.
905 * Gets the capabilities negotiated with the remote peer
907 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
912 g_dbus_connection_get_capabilities (GDBusConnection *connection)
914 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
915 return connection->capabilities;
918 /* ---------------------------------------------------------------------------------------------------- */
921 flush_in_thread_func (GSimpleAsyncResult *res,
923 GCancellable *cancellable)
928 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
932 g_simple_async_result_set_from_error (res, error);
933 g_error_free (error);
938 * g_dbus_connection_flush:
939 * @connection: A #GDBusConnection.
940 * @cancellable: A #GCancellable or %NULL.
941 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
942 * care about the result.
943 * @user_data: The data to pass to @callback.
945 * Asynchronously flushes @connection, that is, writes all queued
946 * outgoing message to the transport and then flushes the transport
947 * (using g_output_stream_flush_async()). This is useful in programs
948 * that wants to emit a D-Bus signal and then exit
949 * immediately. Without flushing the connection, there is no guarantee
950 * that the message has been sent to the networking buffers in the OS
953 * This is an asynchronous method. When the operation is finished,
954 * @callback will be invoked in the <link
955 * linkend="g-main-context-push-thread-default">thread-default main
956 * loop</link> of the thread you are calling this method from. You can
957 * then call g_dbus_connection_flush_finish() to get the result of the
958 * operation. See g_dbus_connection_flush_sync() for the synchronous
964 g_dbus_connection_flush (GDBusConnection *connection,
965 GCancellable *cancellable,
966 GAsyncReadyCallback callback,
969 GSimpleAsyncResult *simple;
971 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
973 simple = g_simple_async_result_new (G_OBJECT (connection),
976 g_dbus_connection_flush);
977 g_simple_async_result_run_in_thread (simple,
978 flush_in_thread_func,
981 g_object_unref (simple);
985 * g_dbus_connection_flush_finish:
986 * @connection: A #GDBusConnection.
987 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_flush().
988 * @error: Return location for error or %NULL.
990 * Finishes an operation started with g_dbus_connection_flush().
992 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
997 g_dbus_connection_flush_finish (GDBusConnection *connection,
1001 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1006 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1007 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1008 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1010 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1012 if (g_simple_async_result_propagate_error (simple, error))
1022 * g_dbus_connection_flush_sync:
1023 * @connection: A #GDBusConnection.
1024 * @cancellable: A #GCancellable or %NULL.
1025 * @error: Return location for error or %NULL.
1027 * Synchronously flushes @connection. The calling thread is blocked
1028 * until this is done. See g_dbus_connection_flush() for the
1029 * asynchronous version of this method and more details about what it
1032 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1037 g_dbus_connection_flush_sync (GDBusConnection *connection,
1038 GCancellable *cancellable,
1043 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1044 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1048 if (connection->closed)
1050 g_set_error_literal (error,
1053 _("The connection is closed"));
1057 ret = _g_dbus_worker_flush_sync (connection->worker,
1065 /* ---------------------------------------------------------------------------------------------------- */
1069 GDBusConnection *connection;
1071 gboolean remote_peer_vanished;
1075 emit_closed_data_free (EmitClosedData *data)
1077 g_object_unref (data->connection);
1078 if (data->error != NULL)
1079 g_error_free (data->error);
1084 emit_closed_in_idle (gpointer user_data)
1086 EmitClosedData *data = user_data;
1089 g_object_notify (G_OBJECT (data->connection), "closed");
1090 g_signal_emit (data->connection,
1091 signals[CLOSED_SIGNAL],
1093 data->remote_peer_vanished,
1099 /* Can be called from any thread, must hold lock */
1101 set_closed_unlocked (GDBusConnection *connection,
1102 gboolean remote_peer_vanished,
1105 GSource *idle_source;
1106 EmitClosedData *data;
1108 CONNECTION_ENSURE_LOCK (connection);
1110 g_assert (!connection->closed);
1112 connection->closed = TRUE;
1114 data = g_new0 (EmitClosedData, 1);
1115 data->connection = g_object_ref (connection);
1116 data->remote_peer_vanished = remote_peer_vanished;
1117 data->error = error != NULL ? g_error_copy (error) : NULL;
1119 idle_source = g_idle_source_new ();
1120 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1121 g_source_set_callback (idle_source,
1122 emit_closed_in_idle,
1124 (GDestroyNotify) emit_closed_data_free);
1125 g_source_attach (idle_source, connection->main_context_at_construction);
1126 g_source_unref (idle_source);
1129 /* ---------------------------------------------------------------------------------------------------- */
1132 close_in_thread_func (GSimpleAsyncResult *res,
1134 GCancellable *cancellable)
1139 if (!g_dbus_connection_close_sync (G_DBUS_CONNECTION (object),
1143 g_simple_async_result_set_from_error (res, error);
1144 g_error_free (error);
1149 * g_dbus_connection_close:
1150 * @connection: A #GDBusConnection.
1151 * @cancellable: A #GCancellable or %NULL.
1152 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1153 * care about the result.
1154 * @user_data: The data to pass to @callback.
1156 * Closes @connection. Note that this never causes the process to
1157 * exit (this might only happen if the other end of a shared message
1158 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1160 * Once the connection is closed, operations such as sending a message
1161 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1162 * will not automatically flush the connection so queued messages may
1163 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1165 * If @connection is already closed, this method fails with
1166 * %G_IO_ERROR_CLOSED.
1168 * When @connection has been closed, the #GDBusConnection::closed
1169 * signal is emitted in the <link
1170 * linkend="g-main-context-push-thread-default">thread-default main
1171 * loop</link> of the thread that @connection was constructed in.
1173 * This is an asynchronous method. When the operation is finished,
1174 * @callback will be invoked in the <link
1175 * linkend="g-main-context-push-thread-default">thread-default main
1176 * loop</link> of the thread you are calling this method from. You can
1177 * then call g_dbus_connection_close_finish() to get the result of the
1178 * operation. See g_dbus_connection_close_sync() for the synchronous
1184 g_dbus_connection_close (GDBusConnection *connection,
1185 GCancellable *cancellable,
1186 GAsyncReadyCallback callback,
1189 GSimpleAsyncResult *simple;
1191 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1193 simple = g_simple_async_result_new (G_OBJECT (connection),
1196 g_dbus_connection_close);
1197 g_simple_async_result_run_in_thread (simple,
1198 close_in_thread_func,
1201 g_object_unref (simple);
1205 * g_dbus_connection_close_finish:
1206 * @connection: A #GDBusConnection.
1207 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_close().
1208 * @error: Return location for error or %NULL.
1210 * Finishes an operation started with g_dbus_connection_close().
1212 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1217 g_dbus_connection_close_finish (GDBusConnection *connection,
1221 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1226 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1227 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1228 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1230 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1232 if (g_simple_async_result_propagate_error (simple, error))
1242 * g_dbus_connection_close_sync:
1243 * @connection: A #GDBusConnection.
1244 * @cancellable: A #GCancellable or %NULL.
1245 * @error: Return location for error or %NULL.
1247 * Synchronously closees @connection. The calling thread is blocked
1248 * until this is done. See g_dbus_connection_close() for the
1249 * asynchronous version of this method and more details about what it
1252 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1257 g_dbus_connection_close_sync (GDBusConnection *connection,
1258 GCancellable *cancellable,
1263 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1264 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1268 CONNECTION_LOCK (connection);
1269 if (!connection->closed)
1271 ret = g_io_stream_close (connection->stream,
1275 set_closed_unlocked (connection, FALSE, NULL);
1279 g_set_error_literal (error,
1282 _("The connection is closed"));
1284 CONNECTION_UNLOCK (connection);
1289 /* ---------------------------------------------------------------------------------------------------- */
1292 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1293 GDBusMessage *message,
1294 GDBusSendMessageFlags flags,
1295 volatile guint32 *out_serial,
1300 guint32 serial_to_use;
1303 CONNECTION_ENSURE_LOCK (connection);
1305 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1306 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1308 /* TODO: check all necessary headers are present */
1313 if (out_serial != NULL)
1316 if (connection->closed)
1318 g_set_error_literal (error,
1321 _("The connection is closed"));
1325 blob = g_dbus_message_to_blob (message,
1327 connection->capabilities,
1332 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1333 serial_to_use = g_dbus_message_get_serial (message);
1335 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1340 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1343 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1346 g_assert_not_reached ();
1351 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1352 blob_size, serial_to_use, connection);
1353 g_printerr ("----\n");
1354 hexdump (blob, blob_size);
1355 g_printerr ("----\n");
1358 /* TODO: use connection->auth to encode the blob */
1360 if (out_serial != NULL)
1361 *out_serial = serial_to_use;
1363 g_dbus_message_set_serial (message, serial_to_use);
1365 _g_dbus_worker_send_message (connection->worker,
1369 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1380 * g_dbus_connection_send_message:
1381 * @connection: A #GDBusConnection.
1382 * @message: A #GDBusMessage
1383 * @flags: Flags affecting how the message is sent.
1384 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1385 * @error: Return location for error or %NULL.
1387 * Asynchronously sends @message to the peer represented by @connection.
1389 * Unless @flags contain the
1390 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1391 * will be assigned by @connection and set on @message via
1392 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1393 * serial number used will be written to this location prior to
1394 * submitting the message to the underlying transport.
1396 * If @connection is closed then the operation will fail with
1397 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1398 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1400 * See <xref linkend="gdbus-server"/> and <xref
1401 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1402 * low-level API to send and receive UNIX file descriptors.
1404 * Returns: %TRUE if the message was well-formed and queued for
1405 * transmission, %FALSE if @error is set.
1410 g_dbus_connection_send_message (GDBusConnection *connection,
1411 GDBusMessage *message,
1412 GDBusSendMessageFlags flags,
1413 volatile guint32 *out_serial,
1418 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1419 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1420 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1422 CONNECTION_LOCK (connection);
1423 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1424 CONNECTION_UNLOCK (connection);
1428 /* ---------------------------------------------------------------------------------------------------- */
1432 volatile gint ref_count;
1433 GDBusConnection *connection;
1435 GSimpleAsyncResult *simple;
1437 GMainContext *main_context;
1439 GCancellable *cancellable;
1441 gulong cancellable_handler_id;
1443 GSource *timeout_source;
1448 static SendMessageData *
1449 send_message_data_ref (SendMessageData *data)
1451 g_atomic_int_inc (&data->ref_count);
1456 send_message_data_unref (SendMessageData *data)
1458 if (g_atomic_int_dec_and_test (&data->ref_count))
1460 g_assert (data->timeout_source == NULL);
1461 g_assert (data->simple == NULL);
1462 g_assert (data->cancellable_handler_id == 0);
1463 g_object_unref (data->connection);
1464 if (data->cancellable != NULL)
1465 g_object_unref (data->cancellable);
1466 if (data->main_context != NULL)
1467 g_main_context_unref (data->main_context);
1472 /* ---------------------------------------------------------------------------------------------------- */
1474 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1476 send_message_with_reply_deliver (SendMessageData *data)
1478 CONNECTION_ENSURE_LOCK (data->connection);
1480 g_assert (!data->delivered);
1482 data->delivered = TRUE;
1484 g_simple_async_result_complete_in_idle (data->simple);
1485 g_object_unref (data->simple);
1486 data->simple = NULL;
1488 if (data->timeout_source != NULL)
1490 g_source_destroy (data->timeout_source);
1491 data->timeout_source = NULL;
1493 if (data->cancellable_handler_id > 0)
1495 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1496 data->cancellable_handler_id = 0;
1499 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
1500 GUINT_TO_POINTER (data->serial)));
1502 send_message_data_unref (data);
1505 /* ---------------------------------------------------------------------------------------------------- */
1507 /* must hold lock */
1509 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1510 GDBusMessage *reply)
1512 if (data->delivered)
1515 g_simple_async_result_set_op_res_gpointer (data->simple,
1516 g_object_ref (reply),
1519 send_message_with_reply_deliver (data);
1525 /* ---------------------------------------------------------------------------------------------------- */
1528 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1530 SendMessageData *data = user_data;
1532 CONNECTION_LOCK (data->connection);
1533 if (data->delivered)
1536 g_simple_async_result_set_error (data->simple,
1538 G_IO_ERROR_CANCELLED,
1539 _("Operation was cancelled"));
1541 send_message_with_reply_deliver (data);
1544 CONNECTION_UNLOCK (data->connection);
1548 /* Can be called from any thread with or without lock held */
1550 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1553 SendMessageData *data = user_data;
1554 GSource *idle_source;
1556 /* postpone cancellation to idle handler since we may be called directly
1557 * via g_cancellable_connect() (e.g. holding lock)
1559 idle_source = g_idle_source_new ();
1560 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1561 g_source_set_callback (idle_source,
1562 send_message_with_reply_cancelled_idle_cb,
1563 send_message_data_ref (data),
1564 (GDestroyNotify) send_message_data_unref);
1565 g_source_attach (idle_source, data->main_context);
1566 g_source_unref (idle_source);
1569 /* ---------------------------------------------------------------------------------------------------- */
1572 send_message_with_reply_timeout_cb (gpointer user_data)
1574 SendMessageData *data = user_data;
1576 CONNECTION_LOCK (data->connection);
1577 if (data->delivered)
1580 g_simple_async_result_set_error (data->simple,
1582 G_IO_ERROR_TIMED_OUT,
1583 _("Timeout was reached"));
1585 send_message_with_reply_deliver (data);
1588 CONNECTION_UNLOCK (data->connection);
1593 /* ---------------------------------------------------------------------------------------------------- */
1596 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1597 GDBusMessage *message,
1598 GDBusSendMessageFlags flags,
1600 volatile guint32 *out_serial,
1601 GCancellable *cancellable,
1602 GAsyncReadyCallback callback,
1605 GSimpleAsyncResult *simple;
1606 SendMessageData *data;
1608 volatile guint32 serial;
1612 if (out_serial == NULL)
1613 out_serial = &serial;
1615 if (timeout_msec == -1)
1616 timeout_msec = 25 * 1000;
1618 simple = g_simple_async_result_new (G_OBJECT (connection),
1621 g_dbus_connection_send_message_with_reply);
1623 if (g_cancellable_is_cancelled (cancellable))
1625 g_simple_async_result_set_error (simple,
1627 G_IO_ERROR_CANCELLED,
1628 _("Operation was cancelled"));
1629 g_simple_async_result_complete_in_idle (simple);
1630 g_object_unref (simple);
1634 if (connection->closed)
1636 g_simple_async_result_set_error (simple,
1639 _("The connection is closed"));
1640 g_simple_async_result_complete_in_idle (simple);
1641 g_object_unref (simple);
1646 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1648 g_simple_async_result_set_from_error (simple, error);
1649 g_simple_async_result_complete_in_idle (simple);
1650 g_object_unref (simple);
1654 data = g_new0 (SendMessageData, 1);
1655 data->ref_count = 1;
1656 data->connection = g_object_ref (connection);
1657 data->simple = simple;
1658 data->serial = *out_serial;
1659 data->main_context = g_main_context_get_thread_default ();
1660 if (data->main_context != NULL)
1661 g_main_context_ref (data->main_context);
1663 if (cancellable != NULL)
1665 data->cancellable = g_object_ref (cancellable);
1666 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1667 G_CALLBACK (send_message_with_reply_cancelled_cb),
1668 send_message_data_ref (data),
1669 (GDestroyNotify) send_message_data_unref);
1670 g_object_set_data_full (G_OBJECT (simple),
1672 g_object_ref (cancellable),
1673 (GDestroyNotify) g_object_unref);
1676 data->timeout_source = g_timeout_source_new (timeout_msec);
1677 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1678 g_source_set_callback (data->timeout_source,
1679 send_message_with_reply_timeout_cb,
1680 send_message_data_ref (data),
1681 (GDestroyNotify) send_message_data_unref);
1682 g_source_attach (data->timeout_source, data->main_context);
1683 g_source_unref (data->timeout_source);
1685 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
1686 GUINT_TO_POINTER (*out_serial),
1694 * g_dbus_connection_send_message_with_reply:
1695 * @connection: A #GDBusConnection.
1696 * @message: A #GDBusMessage.
1697 * @flags: Flags affecting how the message is sent.
1698 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1699 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1700 * @cancellable: A #GCancellable or %NULL.
1701 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1702 * care about the result.
1703 * @user_data: The data to pass to @callback.
1705 * Asynchronously sends @message to the peer represented by @connection.
1707 * Unless @flags contain the
1708 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1709 * will be assigned by @connection and set on @message via
1710 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1711 * serial number used will be written to this location prior to
1712 * submitting the message to the underlying transport.
1714 * If @connection is closed then the operation will fail with
1715 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1716 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1717 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1719 * This is an asynchronous method. When the operation is finished, @callback will be invoked
1720 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
1721 * of the thread you are calling this method from. You can then call
1722 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1723 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
1725 * See <xref linkend="gdbus-server"/> and <xref
1726 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1727 * low-level API to send and receive UNIX file descriptors.
1732 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
1733 GDBusMessage *message,
1734 GDBusSendMessageFlags flags,
1736 volatile guint32 *out_serial,
1737 GCancellable *cancellable,
1738 GAsyncReadyCallback callback,
1741 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1742 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1743 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
1745 CONNECTION_LOCK (connection);
1746 g_dbus_connection_send_message_with_reply_unlocked (connection,
1754 CONNECTION_UNLOCK (connection);
1758 * g_dbus_connection_send_message_with_reply_finish:
1759 * @connection: a #GDBusConnection
1760 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
1761 * @error: Return location for error or %NULL.
1763 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
1765 * Note that @error is only set if a local in-process error
1766 * occured. That is to say that the returned #GDBusMessage object may
1767 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1768 * g_dbus_message_to_gerror() to transcode this to a #GError.
1770 * See <xref linkend="gdbus-server"/> and <xref
1771 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1772 * low-level API to send and receive UNIX file descriptors.
1774 * Returns: A #GDBusMessage or %NULL if @error is set.
1779 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
1783 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1784 GDBusMessage *reply;
1785 GCancellable *cancellable;
1787 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1788 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1792 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
1794 if (g_simple_async_result_propagate_error (simple, error))
1797 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
1798 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
1799 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
1801 g_object_unref (reply);
1803 g_set_error_literal (error,
1805 G_IO_ERROR_CANCELLED,
1806 _("Operation was cancelled"));
1812 /* ---------------------------------------------------------------------------------------------------- */
1817 GMainContext *context;
1819 } SendMessageSyncData;
1822 send_message_with_reply_sync_cb (GDBusConnection *connection,
1826 SendMessageSyncData *data = user_data;
1827 data->res = g_object_ref (res);
1828 g_main_loop_quit (data->loop);
1832 * g_dbus_connection_send_message_with_reply_sync:
1833 * @connection: A #GDBusConnection.
1834 * @message: A #GDBusMessage.
1835 * @flags: Flags affecting how the message is sent.
1836 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1837 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1838 * @cancellable: A #GCancellable or %NULL.
1839 * @error: Return location for error or %NULL.
1841 * Synchronously sends @message to the peer represented by @connection
1842 * and blocks the calling thread until a reply is received or the
1843 * timeout is reached. See g_dbus_connection_send_message_with_reply()
1844 * for the asynchronous version of this method.
1846 * Unless @flags contain the
1847 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1848 * will be assigned by @connection and set on @message via
1849 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1850 * serial number used will be written to this location prior to
1851 * submitting the message to the underlying transport.
1853 * If @connection is closed then the operation will fail with
1854 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1855 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1856 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1858 * Note that @error is only set if a local in-process error
1859 * occured. That is to say that the returned #GDBusMessage object may
1860 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1861 * g_dbus_message_to_gerror() to transcode this to a #GError.
1863 * See <xref linkend="gdbus-server"/> and <xref
1864 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1865 * low-level API to send and receive UNIX file descriptors.
1867 * Returns: A #GDBusMessage that is the reply to @message or %NULL if @error is set.
1872 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
1873 GDBusMessage *message,
1874 GDBusSendMessageFlags flags,
1876 volatile guint32 *out_serial,
1877 GCancellable *cancellable,
1880 SendMessageSyncData *data;
1881 GDBusMessage *reply;
1883 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1884 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
1885 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1886 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1888 data = g_new0 (SendMessageSyncData, 1);
1889 data->context = g_main_context_new ();
1890 data->loop = g_main_loop_new (data->context, FALSE);
1892 g_main_context_push_thread_default (data->context);
1894 g_dbus_connection_send_message_with_reply (connection,
1900 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
1902 g_main_loop_run (data->loop);
1903 reply = g_dbus_connection_send_message_with_reply_finish (connection,
1907 g_main_context_pop_thread_default (data->context);
1909 g_main_context_unref (data->context);
1910 g_main_loop_unref (data->loop);
1911 g_object_unref (data->res);
1917 /* ---------------------------------------------------------------------------------------------------- */
1921 GDBusMessageFilterFunction func;
1928 GDBusMessageFilterFunction filter_function;
1930 GDestroyNotify user_data_free_func;
1933 /* Called in worker's thread - we must not block */
1935 on_worker_message_received (GDBusWorker *worker,
1936 GDBusMessage *message,
1939 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1940 FilterCallback *filters;
1941 gboolean consumed_by_filter;
1945 //g_debug ("in on_worker_message_received");
1947 g_object_ref (connection);
1949 /* First collect the set of callback functions */
1950 CONNECTION_LOCK (connection);
1951 num_filters = connection->filters->len;
1952 filters = g_new0 (FilterCallback, num_filters);
1953 for (n = 0; n < num_filters; n++)
1955 FilterData *data = connection->filters->pdata[n];
1956 filters[n].func = data->filter_function;
1957 filters[n].user_data = data->user_data;
1959 CONNECTION_UNLOCK (connection);
1961 /* the call the filters in order (without holding the lock) */
1962 consumed_by_filter = FALSE;
1963 for (n = 0; n < num_filters; n++)
1965 consumed_by_filter = filters[n].func (connection,
1968 filters[n].user_data);
1969 if (consumed_by_filter)
1973 /* Standard dispatch unless the filter ate the message */
1974 if (!consumed_by_filter)
1976 GDBusMessageType message_type;
1978 message_type = g_dbus_message_get_message_type (message);
1979 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
1981 guint32 reply_serial;
1982 SendMessageData *send_message_data;
1984 reply_serial = g_dbus_message_get_reply_serial (message);
1985 CONNECTION_LOCK (connection);
1986 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
1987 GUINT_TO_POINTER (reply_serial));
1988 if (send_message_data != NULL)
1990 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
1991 send_message_data_deliver_reply_unlocked (send_message_data, message);
1995 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
1997 CONNECTION_UNLOCK (connection);
1999 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2001 CONNECTION_LOCK (connection);
2002 distribute_signals (connection, message);
2003 CONNECTION_UNLOCK (connection);
2005 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2007 CONNECTION_LOCK (connection);
2008 distribute_method_call (connection, message);
2009 CONNECTION_UNLOCK (connection);
2013 g_object_unref (connection);
2017 /* Called in worker's thread */
2019 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2020 GDBusMessage *message,
2023 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
2024 FilterCallback *filters;
2025 gboolean consumed_by_filter;
2029 //g_debug ("in on_worker_message_about_to_be_sent");
2031 g_object_ref (connection);
2033 /* First collect the set of callback functions */
2034 CONNECTION_LOCK (connection);
2035 num_filters = connection->filters->len;
2036 filters = g_new0 (FilterCallback, num_filters);
2037 for (n = 0; n < num_filters; n++)
2039 FilterData *data = connection->filters->pdata[n];
2040 filters[n].func = data->filter_function;
2041 filters[n].user_data = data->user_data;
2043 CONNECTION_UNLOCK (connection);
2045 /* the call the filters in order (without holding the lock) */
2046 consumed_by_filter = FALSE;
2047 for (n = 0; n < num_filters; n++)
2049 consumed_by_filter = filters[n].func (connection,
2052 filters[n].user_data);
2053 if (consumed_by_filter)
2057 g_object_unref (connection);
2060 return consumed_by_filter;
2063 /* Called in worker's thread - we must not block */
2065 on_worker_closed (GDBusWorker *worker,
2066 gboolean remote_peer_vanished,
2070 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
2072 //g_debug ("in on_worker_closed: %s", error->message);
2074 CONNECTION_LOCK (connection);
2075 if (!connection->closed)
2076 set_closed_unlocked (connection, remote_peer_vanished, error);
2077 CONNECTION_UNLOCK (connection);
2080 /* ---------------------------------------------------------------------------------------------------- */
2082 /* Determines the biggest set of capabilities we can support on this connection */
2083 static GDBusCapabilityFlags
2084 get_offered_capabilities_max (GDBusConnection *connection)
2086 GDBusCapabilityFlags ret;
2087 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2089 if (G_IS_UNIX_CONNECTION (connection->stream))
2090 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2096 initable_init (GInitable *initable,
2097 GCancellable *cancellable,
2100 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2103 /* This method needs to be idempotent to work with the singleton
2104 * pattern. See the docs for g_initable_init(). We implement this by
2107 * Unfortunately we can't use the main lock since the on_worker_*()
2108 * callbacks above needs the lock during initialization (for message
2109 * bus connections we do a synchronous Hello() call on the bus).
2111 g_mutex_lock (connection->init_lock);
2115 if (connection->is_initialized)
2117 if (connection->stream != NULL)
2120 g_assert (connection->initialization_error != NULL);
2123 g_assert (connection->initialization_error == NULL);
2125 /* The user can pass multiple (but mutally exclusive) construct
2128 * - stream (of type GIOStream)
2129 * - address (of type gchar*)
2131 * At the end of the day we end up with a non-NULL GIOStream
2132 * object in connection->stream.
2134 if (connection->address != NULL)
2136 g_assert (connection->stream == NULL);
2138 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2139 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2141 g_set_error_literal (error,
2143 G_IO_ERROR_INVALID_ARGUMENT,
2144 _("Unsupported flags encountered when constructing a client-side connection"));
2148 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2149 NULL, /* TODO: out_guid */
2151 &connection->initialization_error);
2152 if (connection->stream == NULL)
2155 else if (connection->stream != NULL)
2161 g_assert_not_reached ();
2164 /* Authenticate the connection */
2165 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2167 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2168 g_assert (connection->guid != NULL);
2169 connection->auth = _g_dbus_auth_new (connection->stream);
2170 if (!_g_dbus_auth_run_server (connection->auth,
2171 connection->authentication_observer,
2173 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2174 get_offered_capabilities_max (connection),
2175 &connection->capabilities,
2176 &connection->credentials,
2178 &connection->initialization_error))
2181 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2183 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2184 g_assert (connection->guid == NULL);
2185 connection->auth = _g_dbus_auth_new (connection->stream);
2186 connection->guid = _g_dbus_auth_run_client (connection->auth,
2187 get_offered_capabilities_max (connection),
2188 &connection->capabilities,
2190 &connection->initialization_error);
2191 if (connection->guid == NULL)
2195 if (connection->authentication_observer != NULL)
2197 g_object_unref (connection->authentication_observer);
2198 connection->authentication_observer = NULL;
2201 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2203 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2208 * https://bugzilla.gnome.org/show_bug.cgi?id=616458
2212 if (G_IS_SOCKET_CONNECTION (connection->stream))
2214 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2218 connection->worker = _g_dbus_worker_new (connection->stream,
2219 connection->capabilities,
2220 (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING),
2221 on_worker_message_received,
2222 on_worker_message_about_to_be_sent,
2226 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2227 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2229 GVariant *hello_result;
2231 /* we could lift this restriction by adding code in gdbusprivate.c */
2232 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2234 g_set_error_literal (&connection->initialization_error,
2237 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2241 hello_result = g_dbus_connection_call_sync (connection,
2242 "org.freedesktop.DBus", /* name */
2243 "/org/freedesktop/DBus", /* path */
2244 "org.freedesktop.DBus", /* interface */
2246 NULL, /* parameters */
2247 G_VARIANT_TYPE ("(s)"),
2248 G_DBUS_CALL_FLAGS_NONE,
2250 NULL, /* TODO: cancellable */
2251 &connection->initialization_error);
2252 if (hello_result == NULL)
2255 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2256 g_variant_unref (hello_result);
2257 //g_debug ("unique name is `%s'", connection->bus_unique_name);
2260 connection->is_initialized = TRUE;
2266 g_assert (connection->initialization_error != NULL);
2267 g_propagate_error (error, g_error_copy (connection->initialization_error));
2270 g_mutex_unlock (connection->init_lock);
2276 initable_iface_init (GInitableIface *initable_iface)
2278 initable_iface->init = initable_init;
2281 /* ---------------------------------------------------------------------------------------------------- */
2284 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2289 /* ---------------------------------------------------------------------------------------------------- */
2292 * g_dbus_connection_new:
2293 * @stream: A #GIOStream.
2294 * @guid: The GUID to use if a authenticating as a server or %NULL.
2295 * @flags: Flags describing how to make the connection.
2296 * @observer: A #GDBusAuthObserver or %NULL.
2297 * @cancellable: A #GCancellable or %NULL.
2298 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2299 * @user_data: The data to pass to @callback.
2301 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2302 * with the end represented by @stream.
2304 * If @observer is not %NULL it may be used to control the
2305 * authentication process.
2307 * When the operation is finished, @callback will be invoked. You can
2308 * then call g_dbus_connection_new_finish() to get the result of the
2311 * This is a asynchronous failable constructor. See
2312 * g_dbus_connection_new_sync() for the synchronous
2318 g_dbus_connection_new (GIOStream *stream,
2320 GDBusConnectionFlags flags,
2321 GDBusAuthObserver *observer,
2322 GCancellable *cancellable,
2323 GAsyncReadyCallback callback,
2326 g_return_if_fail (G_IS_IO_STREAM (stream));
2327 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2335 "authentication-observer", observer,
2340 * g_dbus_connection_new_finish:
2341 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2342 * @error: Return location for error or %NULL.
2344 * Finishes an operation started with g_dbus_connection_new().
2346 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2351 g_dbus_connection_new_finish (GAsyncResult *res,
2355 GObject *source_object;
2357 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2358 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2360 source_object = g_async_result_get_source_object (res);
2361 g_assert (source_object != NULL);
2362 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2365 g_object_unref (source_object);
2367 return G_DBUS_CONNECTION (object);
2373 * g_dbus_connection_new_sync:
2374 * @stream: A #GIOStream.
2375 * @guid: The GUID to use if a authenticating as a server or %NULL.
2376 * @flags: Flags describing how to make the connection.
2377 * @observer: A #GDBusAuthObserver or %NULL.
2378 * @cancellable: A #GCancellable or %NULL.
2379 * @error: Return location for error or %NULL.
2381 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2382 * with the end represented by @stream.
2384 * If @observer is not %NULL it may be used to control the
2385 * authentication process.
2387 * This is a synchronous failable constructor. See
2388 * g_dbus_connection_new() for the asynchronous version.
2390 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2395 g_dbus_connection_new_sync (GIOStream *stream,
2397 GDBusConnectionFlags flags,
2398 GDBusAuthObserver *observer,
2399 GCancellable *cancellable,
2402 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2403 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2404 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2410 "authentication-observer", observer,
2414 /* ---------------------------------------------------------------------------------------------------- */
2417 * g_dbus_connection_new_for_address:
2418 * @address: A D-Bus address.
2419 * @flags: Flags describing how to make the connection.
2420 * @observer: A #GDBusAuthObserver or %NULL.
2421 * @cancellable: A #GCancellable or %NULL.
2422 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2423 * @user_data: The data to pass to @callback.
2425 * Asynchronously connects and sets up a D-Bus client connection for
2426 * exchanging D-Bus messages with an endpoint specified by @address
2427 * which must be in the D-Bus address format.
2429 * This constructor can only be used to initiate client-side
2430 * connections - use g_dbus_connection_new() if you need to act as the
2431 * server. In particular, @flags cannot contain the
2432 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2433 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2435 * When the operation is finished, @callback will be invoked. You can
2436 * then call g_dbus_connection_new_finish() to get the result of the
2439 * If @observer is not %NULL it may be used to control the
2440 * authentication process.
2442 * This is a asynchronous failable constructor. See
2443 * g_dbus_connection_new_for_address_sync() for the synchronous
2449 g_dbus_connection_new_for_address (const gchar *address,
2450 GDBusConnectionFlags flags,
2451 GDBusAuthObserver *observer,
2452 GCancellable *cancellable,
2453 GAsyncReadyCallback callback,
2456 g_return_if_fail (address != NULL);
2457 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2464 "authentication-observer", observer,
2469 * g_dbus_connection_new_for_address_finish:
2470 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2471 * @error: Return location for error or %NULL.
2473 * Finishes an operation started with g_dbus_connection_new_for_address().
2475 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2480 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2484 GObject *source_object;
2486 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2487 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2489 source_object = g_async_result_get_source_object (res);
2490 g_assert (source_object != NULL);
2491 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2494 g_object_unref (source_object);
2496 return G_DBUS_CONNECTION (object);
2502 * g_dbus_connection_new_for_address_sync:
2503 * @address: A D-Bus address.
2504 * @flags: Flags describing how to make the connection.
2505 * @observer: A #GDBusAuthObserver or %NULL.
2506 * @cancellable: A #GCancellable or %NULL.
2507 * @error: Return location for error or %NULL.
2509 * Synchronously connects and sets up a D-Bus client connection for
2510 * exchanging D-Bus messages with an endpoint specified by @address
2511 * which must be in the D-Bus address format.
2513 * This constructor can only be used to initiate client-side
2514 * connections - use g_dbus_connection_new_sync() if you need to act
2515 * as the server. In particular, @flags cannot contain the
2516 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2517 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2519 * This is a synchronous failable constructor. See
2520 * g_dbus_connection_new_for_address() for the asynchronous version.
2522 * If @observer is not %NULL it may be used to control the
2523 * authentication process.
2525 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2530 g_dbus_connection_new_for_address_sync (const gchar *address,
2531 GDBusConnectionFlags flags,
2532 GDBusAuthObserver *observer,
2533 GCancellable *cancellable,
2536 g_return_val_if_fail (address != NULL, NULL);
2537 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2538 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2543 "authentication-observer", observer,
2547 /* ---------------------------------------------------------------------------------------------------- */
2550 * g_dbus_connection_set_exit_on_close:
2551 * @connection: A #GDBusConnection.
2552 * @exit_on_close: Whether the process should be terminated
2553 * when @connection is closed by the remote peer.
2555 * Sets whether the process should be terminated when @connection is
2556 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2562 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2563 gboolean exit_on_close)
2565 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2566 connection->exit_on_close = exit_on_close;
2570 * g_dbus_connection_get_exit_on_close:
2571 * @connection: A #GDBusConnection.
2573 * Gets whether the process is terminated when @connection is
2574 * closed by the remote peer. See
2575 * #GDBusConnection:exit-on-close for more details.
2577 * Returns: Whether the process is terminated when @connection is
2578 * closed by the remote peer.
2583 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2585 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2586 return connection->exit_on_close;
2590 * g_dbus_connection_get_guid:
2591 * @connection: A #GDBusConnection.
2593 * The GUID of the peer performing the role of server when
2594 * authenticating. See #GDBusConnection:guid for more details.
2596 * Returns: The GUID. Do not free this string, it is owned by
2602 g_dbus_connection_get_guid (GDBusConnection *connection)
2604 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2605 return connection->guid;
2609 * g_dbus_connection_get_unique_name:
2610 * @connection: A #GDBusConnection.
2612 * Gets the unique name of @connection as assigned by the message
2613 * bus. This can also be used to figure out if @connection is a
2614 * message bus connection.
2616 * Returns: The unique name or %NULL if @connection is not a message
2617 * bus connection. Do not free this string, it is owned by
2623 g_dbus_connection_get_unique_name (GDBusConnection *connection)
2625 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2626 return connection->bus_unique_name;
2630 * g_dbus_connection_get_peer_credentials:
2631 * @connection: A #GDBusConnection.
2633 * Gets the credentials of the authenticated peer. This will always
2634 * return %NULL unless @connection acted as a server
2635 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
2636 * when set up and the client passed credentials as part of the
2637 * authentication process.
2639 * In a message bus setup, the message bus is always the server and
2640 * each application is a client. So this method will always return
2641 * %NULL for message bus clients.
2643 * Returns: A #GCredentials or %NULL if not available. Do not free
2644 * this object, it is owned by @connection.
2649 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
2651 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2652 return connection->credentials;
2655 /* ---------------------------------------------------------------------------------------------------- */
2657 static guint _global_filter_id = 1;
2660 * g_dbus_connection_add_filter:
2661 * @connection: A #GDBusConnection.
2662 * @filter_function: A filter function.
2663 * @user_data: User data to pass to @filter_function.
2664 * @user_data_free_func: Function to free @user_data with when filter
2665 * is removed or %NULL.
2667 * Adds a message filter. Filters are handlers that are run on all
2668 * incoming and outgoing messages, prior to standard dispatch. Filters
2669 * are run in the order that they were added. The same handler can be
2670 * added as a filter more than once, in which case it will be run more
2671 * than once. Filters added during a filter callback won't be run on
2672 * the message being processed.
2674 * Note that filters are run in a dedicated message handling thread so
2675 * they can't block and, generally, can't do anything but signal a
2676 * worker thread. Also note that filters are rarely needed - use API
2677 * such as g_dbus_connection_send_message_with_reply(),
2678 * g_dbus_connection_signal_subscribe() or
2679 * g_dbus_connection_call() instead.
2681 * If a filter consumes an incoming message (by returning %TRUE), the
2682 * message is not dispatched anywhere else - not even the standard
2683 * dispatch machinery (that API such as
2684 * g_dbus_connection_signal_subscribe() and
2685 * g_dbus_connection_send_message_with_reply() relies on) will see the
2686 * message. Similary, if a filter consumes an outgoing message, the
2687 * message will not be sent to the other peer.
2689 * Returns: A filter identifier that can be used with
2690 * g_dbus_connection_remove_filter().
2695 g_dbus_connection_add_filter (GDBusConnection *connection,
2696 GDBusMessageFilterFunction filter_function,
2698 GDestroyNotify user_data_free_func)
2702 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2703 g_return_val_if_fail (filter_function != NULL, 0);
2705 CONNECTION_LOCK (connection);
2706 data = g_new0 (FilterData, 1);
2707 data->id = _global_filter_id++; /* TODO: overflow etc. */
2708 data->filter_function = filter_function;
2709 data->user_data = user_data;
2710 data->user_data_free_func = user_data_free_func;
2711 g_ptr_array_add (connection->filters, data);
2712 CONNECTION_UNLOCK (connection);
2717 /* only called from finalize(), removes all filters */
2719 purge_all_filters (GDBusConnection *connection)
2722 for (n = 0; n < connection->filters->len; n++)
2724 FilterData *data = connection->filters->pdata[n];
2725 if (data->user_data_free_func != NULL)
2726 data->user_data_free_func (data->user_data);
2732 * g_dbus_connection_remove_filter:
2733 * @connection: a #GDBusConnection
2734 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
2741 g_dbus_connection_remove_filter (GDBusConnection *connection,
2745 FilterData *to_destroy;
2747 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2749 CONNECTION_LOCK (connection);
2751 for (n = 0; n < connection->filters->len; n++)
2753 FilterData *data = connection->filters->pdata[n];
2754 if (data->id == filter_id)
2756 g_ptr_array_remove_index (connection->filters, n);
2761 CONNECTION_UNLOCK (connection);
2763 /* do free without holding lock */
2764 if (to_destroy != NULL)
2766 if (to_destroy->user_data_free_func != NULL)
2767 to_destroy->user_data_free_func (to_destroy->user_data);
2768 g_free (to_destroy);
2772 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
2776 /* ---------------------------------------------------------------------------------------------------- */
2782 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
2783 gchar *interface_name;
2787 GArray *subscribers;
2792 GDBusSignalCallback callback;
2794 GDestroyNotify user_data_free_func;
2796 GMainContext *context;
2800 signal_data_free (SignalData *signal_data)
2802 g_free (signal_data->rule);
2803 g_free (signal_data->sender);
2804 g_free (signal_data->sender_unique_name);
2805 g_free (signal_data->interface_name);
2806 g_free (signal_data->member);
2807 g_free (signal_data->object_path);
2808 g_free (signal_data->arg0);
2809 g_array_free (signal_data->subscribers, TRUE);
2810 g_free (signal_data);
2814 args_to_rule (const gchar *sender,
2815 const gchar *interface_name,
2816 const gchar *member,
2817 const gchar *object_path,
2822 rule = g_string_new ("type='signal'");
2824 g_string_append_printf (rule, ",sender='%s'", sender);
2825 if (interface_name != NULL)
2826 g_string_append_printf (rule, ",interface='%s'", interface_name);
2828 g_string_append_printf (rule, ",member='%s'", member);
2829 if (object_path != NULL)
2830 g_string_append_printf (rule, ",path='%s'", object_path);
2832 g_string_append_printf (rule, ",arg0='%s'", arg0);
2834 return g_string_free (rule, FALSE);
2837 static guint _global_subscriber_id = 1;
2838 static guint _global_registration_id = 1;
2839 static guint _global_subtree_registration_id = 1;
2841 /* ---------------------------------------------------------------------------------------------------- */
2843 /* must hold lock when calling */
2845 add_match_rule (GDBusConnection *connection,
2846 const gchar *match_rule)
2849 GDBusMessage *message;
2851 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2852 "/org/freedesktop/DBus", /* path */
2853 "org.freedesktop.DBus", /* interface */
2855 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2857 if (!g_dbus_connection_send_message_unlocked (connection,
2859 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
2863 g_critical ("Error while sending AddMatch() message: %s", error->message);
2864 g_error_free (error);
2866 g_object_unref (message);
2869 /* ---------------------------------------------------------------------------------------------------- */
2871 /* must hold lock when calling */
2873 remove_match_rule (GDBusConnection *connection,
2874 const gchar *match_rule)
2877 GDBusMessage *message;
2879 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2880 "/org/freedesktop/DBus", /* path */
2881 "org.freedesktop.DBus", /* interface */
2883 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2886 if (!g_dbus_connection_send_message_unlocked (connection,
2888 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
2892 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
2893 g_error_free (error);
2895 g_object_unref (message);
2898 /* ---------------------------------------------------------------------------------------------------- */
2901 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
2903 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
2904 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
2905 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
2906 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
2907 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
2910 /* ---------------------------------------------------------------------------------------------------- */
2913 * g_dbus_connection_signal_subscribe:
2914 * @connection: A #GDBusConnection.
2915 * @sender: Sender name to match on (unique or well-known name) or %NULL to listen from all senders.
2916 * @interface_name: D-Bus interface name to match on or %NULL to match on all interfaces.
2917 * @member: D-Bus signal name to match on or %NULL to match on all signals.
2918 * @object_path: Object path to match on or %NULL to match on all object paths.
2919 * @arg0: Contents of first string argument to match on or %NULL to match on all kinds of arguments.
2920 * @flags: Flags describing how to subscribe to the signal (currently unused).
2921 * @callback: Callback to invoke when there is a signal matching the requested data.
2922 * @user_data: User data to pass to @callback.
2923 * @user_data_free_func: Function to free @user_data with when subscription is removed or %NULL.
2925 * Subscribes to signals on @connection and invokes @callback with a
2926 * whenever the signal is received. Note that @callback
2927 * will be invoked in the <link
2928 * linkend="g-main-context-push-thread-default">thread-default main
2929 * loop</link> of the thread you are calling this method from.
2931 * If @connection is not a message bus connection, @sender must be
2934 * If @sender is a well-known name note that @callback is invoked with
2935 * the unique name for the owner of @sender, not the well-known name
2936 * as one would expect. This is because the message bus rewrites the
2937 * name. As such, to avoid certain race conditions, users should be
2938 * tracking the name owner of the well-known name and use that when
2939 * processing the received signal.
2941 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
2946 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
2947 const gchar *sender,
2948 const gchar *interface_name,
2949 const gchar *member,
2950 const gchar *object_path,
2952 GDBusSignalFlags flags,
2953 GDBusSignalCallback callback,
2955 GDestroyNotify user_data_free_func)
2958 SignalData *signal_data;
2959 SignalSubscriber subscriber;
2960 GPtrArray *signal_data_array;
2961 const gchar *sender_unique_name;
2963 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
2964 * an OOM condition. We might want to change that but that would involve making
2965 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
2966 * handle that. And there's really no sensible way of handling this short of retrying
2967 * to add the match rule... and then there's the little thing that, hey, maybe there's
2968 * a reason the bus in an OOM condition.
2970 * Doable, but not really sure it's worth it...
2973 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2974 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
2975 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
2976 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
2977 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
2978 g_return_val_if_fail (callback != NULL, 0);
2980 CONNECTION_LOCK (connection);
2982 rule = args_to_rule (sender, interface_name, member, object_path, arg0);
2984 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
2985 sender_unique_name = sender;
2987 sender_unique_name = "";
2989 subscriber.callback = callback;
2990 subscriber.user_data = user_data;
2991 subscriber.user_data_free_func = user_data_free_func;
2992 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
2993 subscriber.context = g_main_context_get_thread_default ();
2994 if (subscriber.context != NULL)
2995 g_main_context_ref (subscriber.context);
2997 /* see if we've already have this rule */
2998 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
2999 if (signal_data != NULL)
3001 g_array_append_val (signal_data->subscribers, subscriber);
3006 signal_data = g_new0 (SignalData, 1);
3007 signal_data->rule = rule;
3008 signal_data->sender = g_strdup (sender);
3009 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3010 signal_data->interface_name = g_strdup (interface_name);
3011 signal_data->member = g_strdup (member);
3012 signal_data->object_path = g_strdup (object_path);
3013 signal_data->arg0 = g_strdup (arg0);
3014 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3015 g_array_append_val (signal_data->subscribers, subscriber);
3017 g_hash_table_insert (connection->map_rule_to_signal_data,
3021 /* Add the match rule to the bus...
3023 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3024 * always send such messages to us.
3026 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3028 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3029 add_match_rule (connection, signal_data->rule);
3032 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3033 signal_data->sender_unique_name);
3034 if (signal_data_array == NULL)
3036 signal_data_array = g_ptr_array_new ();
3037 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3038 g_strdup (signal_data->sender_unique_name),
3041 g_ptr_array_add (signal_data_array, signal_data);
3044 g_hash_table_insert (connection->map_id_to_signal_data,
3045 GUINT_TO_POINTER (subscriber.id),
3048 CONNECTION_UNLOCK (connection);
3050 return subscriber.id;
3053 /* ---------------------------------------------------------------------------------------------------- */
3055 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3057 unsubscribe_id_internal (GDBusConnection *connection,
3058 guint subscription_id,
3059 GArray *out_removed_subscribers)
3061 SignalData *signal_data;
3062 GPtrArray *signal_data_array;
3065 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3066 GUINT_TO_POINTER (subscription_id));
3067 if (signal_data == NULL)
3069 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3073 for (n = 0; n < signal_data->subscribers->len; n++)
3075 SignalSubscriber *subscriber;
3077 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3078 if (subscriber->id != subscription_id)
3081 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3082 GUINT_TO_POINTER (subscription_id)));
3083 g_array_append_val (out_removed_subscribers, *subscriber);
3084 g_array_remove_index (signal_data->subscribers, n);
3086 if (signal_data->subscribers->len == 0)
3088 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3090 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3091 signal_data->sender_unique_name);
3092 g_warn_if_fail (signal_data_array != NULL);
3093 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3095 if (signal_data_array->len == 0)
3097 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3098 signal_data->sender_unique_name));
3101 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3102 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3104 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3105 if (!connection->closed && !connection->finalizing)
3106 remove_match_rule (connection, signal_data->rule);
3108 signal_data_free (signal_data);
3114 g_assert_not_reached ();
3121 * g_dbus_connection_signal_unsubscribe:
3122 * @connection: A #GDBusConnection.
3123 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
3125 * Unsubscribes from signals.
3130 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3131 guint subscription_id)
3133 GArray *subscribers;
3136 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3138 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3140 CONNECTION_LOCK (connection);
3141 unsubscribe_id_internal (connection,
3144 CONNECTION_UNLOCK (connection);
3147 g_assert (subscribers->len == 0 || subscribers->len == 1);
3149 /* call GDestroyNotify without lock held */
3150 for (n = 0; n < subscribers->len; n++)
3152 SignalSubscriber *subscriber;
3153 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3154 if (subscriber->user_data_free_func != NULL)
3155 subscriber->user_data_free_func (subscriber->user_data);
3156 if (subscriber->context != NULL)
3157 g_main_context_unref (subscriber->context);
3160 g_array_free (subscribers, TRUE);
3163 /* ---------------------------------------------------------------------------------------------------- */
3167 guint subscription_id;
3168 GDBusSignalCallback callback;
3170 GDBusMessage *message;
3171 GDBusConnection *connection;
3172 const gchar *sender;
3174 const gchar *interface;
3175 const gchar *member;
3178 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3182 emit_signal_instance_in_idle_cb (gpointer data)
3184 SignalInstance *signal_instance = data;
3185 GVariant *parameters;
3186 gboolean has_subscription;
3188 parameters = g_dbus_message_get_body (signal_instance->message);
3189 if (parameters == NULL)
3191 parameters = g_variant_new ("()");
3192 g_variant_ref_sink (parameters);
3196 g_variant_ref_sink (parameters);
3200 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3201 signal_instance->subscription_id,
3202 signal_instance->sender,
3203 signal_instance->path,
3204 signal_instance->interface,
3205 signal_instance->member,
3206 g_variant_print (parameters, TRUE));
3209 /* Careful here, don't do the callback if we no longer has the subscription */
3210 CONNECTION_LOCK (signal_instance->connection);
3211 has_subscription = FALSE;
3212 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3213 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3214 has_subscription = TRUE;
3215 CONNECTION_UNLOCK (signal_instance->connection);
3217 if (has_subscription)
3218 signal_instance->callback (signal_instance->connection,
3219 signal_instance->sender,
3220 signal_instance->path,
3221 signal_instance->interface,
3222 signal_instance->member,
3224 signal_instance->user_data);
3226 if (parameters != NULL)
3227 g_variant_unref (parameters);
3233 signal_instance_free (SignalInstance *signal_instance)
3235 g_object_unref (signal_instance->message);
3236 g_object_unref (signal_instance->connection);
3237 g_free (signal_instance);
3240 /* called in message handler thread WITH lock held */
3242 schedule_callbacks (GDBusConnection *connection,
3243 GPtrArray *signal_data_array,
3244 GDBusMessage *message,
3245 const gchar *sender)
3248 const gchar *interface;
3249 const gchar *member;
3258 interface = g_dbus_message_get_interface (message);
3259 member = g_dbus_message_get_member (message);
3260 path = g_dbus_message_get_path (message);
3261 arg0 = g_dbus_message_get_arg0 (message);
3264 g_print ("In schedule_callbacks:\n"
3266 " interface = `%s'\n"
3277 /* TODO: if this is slow, then we can change signal_data_array into
3278 * map_object_path_to_signal_data_array or something.
3280 for (n = 0; n < signal_data_array->len; n++)
3282 SignalData *signal_data = signal_data_array->pdata[n];
3284 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3287 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3290 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3293 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
3296 for (m = 0; m < signal_data->subscribers->len; m++)
3298 SignalSubscriber *subscriber;
3299 GSource *idle_source;
3300 SignalInstance *signal_instance;
3302 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3304 signal_instance = g_new0 (SignalInstance, 1);
3305 signal_instance->subscription_id = subscriber->id;
3306 signal_instance->callback = subscriber->callback;
3307 signal_instance->user_data = subscriber->user_data;
3308 signal_instance->message = g_object_ref (message);
3309 signal_instance->connection = g_object_ref (connection);
3310 signal_instance->sender = sender;
3311 signal_instance->path = path;
3312 signal_instance->interface = interface;
3313 signal_instance->member = member;
3315 idle_source = g_idle_source_new ();
3316 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3317 g_source_set_callback (idle_source,
3318 emit_signal_instance_in_idle_cb,
3320 (GDestroyNotify) signal_instance_free);
3321 g_source_attach (idle_source, subscriber->context);
3322 g_source_unref (idle_source);
3327 /* called in message handler thread with lock held */
3329 distribute_signals (GDBusConnection *connection,
3330 GDBusMessage *message)
3332 GPtrArray *signal_data_array;
3333 const gchar *sender;
3335 sender = g_dbus_message_get_sender (message);
3337 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3339 _g_dbus_debug_print_lock ();
3340 g_print ("========================================================================\n"
3341 "GDBus-debug:Signal:\n"
3342 " >>>> SIGNAL %s.%s\n"
3344 " sent by name %s\n",
3345 g_dbus_message_get_interface (message),
3346 g_dbus_message_get_member (message),
3347 g_dbus_message_get_path (message),
3348 sender != NULL ? sender : "(none)");
3349 _g_dbus_debug_print_unlock ();
3352 /* collect subscribers that match on sender */
3355 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3356 if (signal_data_array != NULL)
3357 schedule_callbacks (connection, signal_data_array, message, sender);
3360 /* collect subscribers not matching on sender */
3361 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3362 if (signal_data_array != NULL)
3363 schedule_callbacks (connection, signal_data_array, message, sender);
3366 /* ---------------------------------------------------------------------------------------------------- */
3368 /* only called from finalize(), removes all subscriptions */
3370 purge_all_signal_subscriptions (GDBusConnection *connection)
3372 GHashTableIter iter;
3375 GArray *subscribers;
3378 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3379 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3380 while (g_hash_table_iter_next (&iter, &key, NULL))
3382 guint subscription_id = GPOINTER_TO_UINT (key);
3383 g_array_append_val (ids, subscription_id);
3386 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3387 for (n = 0; n < ids->len; n++)
3389 guint subscription_id = g_array_index (ids, guint, n);
3390 unsubscribe_id_internal (connection,
3394 g_array_free (ids, TRUE);
3396 /* call GDestroyNotify without lock held */
3397 for (n = 0; n < subscribers->len; n++)
3399 SignalSubscriber *subscriber;
3400 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3401 if (subscriber->user_data_free_func != NULL)
3402 subscriber->user_data_free_func (subscriber->user_data);
3403 if (subscriber->context != NULL)
3404 g_main_context_unref (subscriber->context);
3407 g_array_free (subscribers, TRUE);
3410 /* ---------------------------------------------------------------------------------------------------- */
3412 static GDBusInterfaceVTable *
3413 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3415 /* Don't waste memory by copying padding - remember to update this
3416 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3418 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3422 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
3427 /* ---------------------------------------------------------------------------------------------------- */
3429 static GDBusSubtreeVTable *
3430 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
3432 /* Don't waste memory by copying padding - remember to update this
3433 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
3435 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3439 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
3444 /* ---------------------------------------------------------------------------------------------------- */
3446 struct ExportedObject
3449 GDBusConnection *connection;
3451 /* maps gchar* -> ExportedInterface* */
3452 GHashTable *map_if_name_to_ei;
3455 /* only called with lock held */
3457 exported_object_free (ExportedObject *eo)
3459 g_free (eo->object_path);
3460 g_hash_table_unref (eo->map_if_name_to_ei);
3469 gchar *interface_name;
3470 GDBusInterfaceVTable *vtable;
3471 GDBusInterfaceInfo *interface_info;
3473 GMainContext *context;
3475 GDestroyNotify user_data_free_func;
3476 } ExportedInterface;
3478 /* called with lock held */
3480 exported_interface_free (ExportedInterface *ei)
3482 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
3484 if (ei->user_data_free_func != NULL)
3485 /* TODO: push to thread-default mainloop */
3486 ei->user_data_free_func (ei->user_data);
3488 if (ei->context != NULL)
3489 g_main_context_unref (ei->context);
3491 g_free (ei->interface_name);
3492 _g_dbus_interface_vtable_free (ei->vtable);
3496 /* ---------------------------------------------------------------------------------------------------- */
3498 /* Convenience function to check if @registration_id (if not zero) or
3499 * @subtree_registration_id (if not zero) has been unregistered. If
3500 * so, returns %TRUE.
3502 * Caller must *not* hold lock.
3505 has_object_been_unregistered (GDBusConnection *connection,
3506 guint registration_id,
3507 guint subtree_registration_id)
3511 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3515 CONNECTION_LOCK (connection);
3516 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
3517 GUINT_TO_POINTER (registration_id)) == NULL)
3521 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
3522 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
3526 CONNECTION_UNLOCK (connection);
3531 /* ---------------------------------------------------------------------------------------------------- */
3535 GDBusConnection *connection;
3536 GDBusMessage *message;
3538 const gchar *property_name;
3539 const GDBusInterfaceVTable *vtable;
3540 GDBusInterfaceInfo *interface_info;
3541 const GDBusPropertyInfo *property_info;
3542 guint registration_id;
3543 guint subtree_registration_id;
3547 property_data_free (PropertyData *data)
3549 g_object_unref (data->connection);
3550 g_object_unref (data->message);
3554 /* called in thread where object was registered - no locks held */
3556 invoke_get_property_in_idle_cb (gpointer _data)
3558 PropertyData *data = _data;
3561 GDBusMessage *reply;
3563 if (has_object_been_unregistered (data->connection,
3564 data->registration_id,
3565 data->subtree_registration_id))
3567 reply = g_dbus_message_new_method_error (data->message,
3568 "org.freedesktop.DBus.Error.UnknownMethod",
3569 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
3570 g_dbus_message_get_path (data->message));
3571 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3572 g_object_unref (reply);
3577 value = data->vtable->get_property (data->connection,
3578 g_dbus_message_get_sender (data->message),
3579 g_dbus_message_get_path (data->message),
3580 data->interface_info->name,
3581 data->property_name,
3588 g_assert_no_error (error);
3590 g_variant_ref_sink (value);
3591 reply = g_dbus_message_new_method_reply (data->message);
3592 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
3593 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3594 g_variant_unref (value);
3595 g_object_unref (reply);
3599 gchar *dbus_error_name;
3600 g_assert (error != NULL);
3601 dbus_error_name = g_dbus_error_encode_gerror (error);
3602 reply = g_dbus_message_new_method_error_literal (data->message,
3605 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3606 g_free (dbus_error_name);
3607 g_error_free (error);
3608 g_object_unref (reply);
3615 /* called in thread where object was registered - no locks held */
3617 invoke_set_property_in_idle_cb (gpointer _data)
3619 PropertyData *data = _data;
3621 GDBusMessage *reply;
3627 g_variant_get (g_dbus_message_get_body (data->message),
3633 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
3634 * of the given value is wrong
3636 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
3638 reply = g_dbus_message_new_method_error (data->message,
3639 "org.freedesktop.DBus.Error.InvalidArgs",
3640 _("Error setting property `%s': Expected type `%s' but got `%s'"),
3641 data->property_info->name,
3642 data->property_info->signature,
3643 g_variant_get_type_string (value));
3647 if (!data->vtable->set_property (data->connection,
3648 g_dbus_message_get_sender (data->message),
3649 g_dbus_message_get_path (data->message),
3650 data->interface_info->name,
3651 data->property_name,
3656 gchar *dbus_error_name;
3657 g_assert (error != NULL);
3658 dbus_error_name = g_dbus_error_encode_gerror (error);
3659 reply = g_dbus_message_new_method_error_literal (data->message,
3662 g_free (dbus_error_name);
3663 g_error_free (error);
3667 reply = g_dbus_message_new_method_reply (data->message);
3671 g_assert (reply != NULL);
3672 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3673 g_object_unref (reply);
3678 /* called with lock held */
3680 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
3681 GDBusMessage *message,
3682 guint registration_id,
3683 guint subtree_registration_id,
3685 GDBusInterfaceInfo *interface_info,
3686 const GDBusInterfaceVTable *vtable,
3687 GMainContext *main_context,
3691 const char *interface_name;
3692 const char *property_name;
3693 const GDBusPropertyInfo *property_info;
3694 GSource *idle_source;
3695 PropertyData *property_data;
3696 GDBusMessage *reply;
3701 g_variant_get (g_dbus_message_get_body (message),
3706 g_variant_get (g_dbus_message_get_body (message),
3715 if (vtable == NULL || vtable->get_property == NULL)
3720 if (vtable == NULL || vtable->set_property == NULL)
3724 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
3726 property_info = NULL;
3728 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3729 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
3730 if (property_info == NULL)
3732 reply = g_dbus_message_new_method_error (message,
3733 "org.freedesktop.DBus.Error.InvalidArgs",
3734 _("No such property `%s'"),
3736 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3737 g_object_unref (reply);
3742 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3744 reply = g_dbus_message_new_method_error (message,
3745 "org.freedesktop.DBus.Error.InvalidArgs",
3746 _("Property `%s' is not readable"),
3748 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3749 g_object_unref (reply);
3753 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
3755 reply = g_dbus_message_new_method_error (message,
3756 "org.freedesktop.DBus.Error.InvalidArgs",
3757 _("Property `%s' is not writable"),
3759 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3760 g_object_unref (reply);
3765 /* ok, got the property info - call user code in an idle handler */
3766 property_data = g_new0 (PropertyData, 1);
3767 property_data->connection = g_object_ref (connection);
3768 property_data->message = g_object_ref (message);
3769 property_data->user_data = user_data;
3770 property_data->property_name = property_name;
3771 property_data->vtable = vtable;
3772 property_data->interface_info = interface_info;
3773 property_data->property_info = property_info;
3774 property_data->registration_id = registration_id;
3775 property_data->subtree_registration_id = subtree_registration_id;
3777 idle_source = g_idle_source_new ();
3778 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3779 g_source_set_callback (idle_source,
3780 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
3782 (GDestroyNotify) property_data_free);
3783 g_source_attach (idle_source, main_context);
3784 g_source_unref (idle_source);
3792 /* called with lock held */
3794 handle_getset_property (GDBusConnection *connection,
3796 GDBusMessage *message,
3799 ExportedInterface *ei;
3801 const char *interface_name;
3802 const char *property_name;
3807 g_variant_get (g_dbus_message_get_body (message),
3812 g_variant_get (g_dbus_message_get_body (message),
3818 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3819 * no such interface registered
3821 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3824 GDBusMessage *reply;
3825 reply = g_dbus_message_new_method_error (message,
3826 "org.freedesktop.DBus.Error.InvalidArgs",
3827 _("No such interface `%s'"),
3829 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3830 g_object_unref (reply);
3835 handled = validate_and_maybe_schedule_property_getset (eo->connection,
3848 /* ---------------------------------------------------------------------------------------------------- */
3852 GDBusConnection *connection;
3853 GDBusMessage *message;
3855 const GDBusInterfaceVTable *vtable;
3856 GDBusInterfaceInfo *interface_info;
3857 guint registration_id;
3858 guint subtree_registration_id;
3859 } PropertyGetAllData;
3862 property_get_all_data_free (PropertyData *data)
3864 g_object_unref (data->connection);
3865 g_object_unref (data->message);
3869 /* called in thread where object was registered - no locks held */
3871 invoke_get_all_properties_in_idle_cb (gpointer _data)
3873 PropertyGetAllData *data = _data;
3874 GVariantBuilder builder;
3876 GDBusMessage *reply;
3879 if (has_object_been_unregistered (data->connection,
3880 data->registration_id,
3881 data->subtree_registration_id))
3883 reply = g_dbus_message_new_method_error (data->message,
3884 "org.freedesktop.DBus.Error.UnknownMethod",
3885 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
3886 g_dbus_message_get_path (data->message));
3887 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3888 g_object_unref (reply);
3894 /* TODO: Right now we never fail this call - we just omit values if
3895 * a get_property() call is failing.
3897 * We could fail the whole call if just a single get_property() call
3898 * returns an error. We need clarification in the D-Bus spec about this.
3900 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
3901 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
3902 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
3904 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
3907 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3910 value = data->vtable->get_property (data->connection,
3911 g_dbus_message_get_sender (data->message),
3912 g_dbus_message_get_path (data->message),
3913 data->interface_info->name,
3914 property_info->name,
3921 g_variant_builder_add (&builder,
3923 property_info->name,
3926 g_variant_builder_close (&builder);
3928 reply = g_dbus_message_new_method_reply (data->message);
3929 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
3930 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3931 g_object_unref (reply);
3937 /* called with lock held */
3939 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
3940 GDBusMessage *message,
3941 guint registration_id,
3942 guint subtree_registration_id,
3943 GDBusInterfaceInfo *interface_info,
3944 const GDBusInterfaceVTable *vtable,
3945 GMainContext *main_context,
3949 const char *interface_name;
3950 GSource *idle_source;
3951 PropertyGetAllData *property_get_all_data;
3955 g_variant_get (g_dbus_message_get_body (message),
3959 if (vtable == NULL || vtable->get_property == NULL)
3962 /* ok, got the property info - call user in an idle handler */
3963 property_get_all_data = g_new0 (PropertyGetAllData, 1);
3964 property_get_all_data->connection = g_object_ref (connection);
3965 property_get_all_data->message = g_object_ref (message);
3966 property_get_all_data->user_data = user_data;
3967 property_get_all_data->vtable = vtable;
3968 property_get_all_data->interface_info = interface_info;
3969 property_get_all_data->registration_id = registration_id;
3970 property_get_all_data->subtree_registration_id = subtree_registration_id;
3972 idle_source = g_idle_source_new ();
3973 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3974 g_source_set_callback (idle_source,
3975 invoke_get_all_properties_in_idle_cb,
3976 property_get_all_data,
3977 (GDestroyNotify) property_get_all_data_free);
3978 g_source_attach (idle_source, main_context);
3979 g_source_unref (idle_source);
3987 /* called with lock held */
3989 handle_get_all_properties (GDBusConnection *connection,
3991 GDBusMessage *message)
3993 ExportedInterface *ei;
3995 const char *interface_name;
3999 g_variant_get (g_dbus_message_get_body (message),
4003 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4004 * no such interface registered
4006 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4009 GDBusMessage *reply;
4010 reply = g_dbus_message_new_method_error (message,
4011 "org.freedesktop.DBus.Error.InvalidArgs",
4012 _("No such interface"),
4014 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4015 g_object_unref (reply);
4020 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4032 /* ---------------------------------------------------------------------------------------------------- */
4034 static const gchar introspect_header[] =
4035 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4036 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4037 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4040 static const gchar introspect_tail[] =
4043 static const gchar introspect_standard_interfaces[] =
4044 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4045 " <method name=\"Get\">\n"
4046 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4047 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4048 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4050 " <method name=\"GetAll\">\n"
4051 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4052 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4054 " <method name=\"Set\">\n"
4055 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4056 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4057 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4059 " <signal name=\"PropertiesChanged\">\n"
4060 " <arg type=\"s\" name=\"interface_name\"/>\n"
4061 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4062 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4065 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4066 " <method name=\"Introspect\">\n"
4067 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4070 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4071 " <method name=\"Ping\"/>\n"
4072 " <method name=\"GetMachineId\">\n"
4073 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4078 introspect_append_header (GString *s)
4080 g_string_append (s, introspect_header);
4084 introspect_append_standard_interfaces (GString *s)
4086 g_string_append (s, introspect_standard_interfaces);
4090 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4092 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4098 begin = object_path + path_len;
4099 end = strchr (begin, '/');
4101 s = g_strndup (begin, end - begin);
4103 s = g_strdup (begin);
4105 if (g_hash_table_lookup (set, s) == NULL)
4106 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
4112 /* TODO: we want a nicer public interface for this */
4114 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4119 GHashTableIter hash_iter;
4120 const gchar *object_path;
4126 CONNECTION_ENSURE_LOCK (connection);
4128 path_len = strlen (path);
4132 set = g_hash_table_new (g_str_hash, g_str_equal);
4134 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4135 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4136 maybe_add_path (path, path_len, object_path, set);
4138 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4139 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4140 maybe_add_path (path, path_len, object_path, set);
4142 p = g_ptr_array_new ();
4143 keys = g_hash_table_get_keys (set);
4144 for (l = keys; l != NULL; l = l->next)
4145 g_ptr_array_add (p, l->data);
4146 g_hash_table_unref (set);
4149 g_ptr_array_add (p, NULL);
4150 ret = (gchar **) g_ptr_array_free (p, FALSE);
4155 g_dbus_connection_list_registered (GDBusConnection *connection,
4159 CONNECTION_LOCK (connection);
4160 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4161 CONNECTION_UNLOCK (connection);
4165 /* called in message handler thread with lock held */
4167 handle_introspect (GDBusConnection *connection,
4169 GDBusMessage *message)
4173 GDBusMessage *reply;
4174 GHashTableIter hash_iter;
4175 ExportedInterface *ei;
4178 /* first the header with the standard interfaces */
4179 s = g_string_sized_new (sizeof (introspect_header) +
4180 sizeof (introspect_standard_interfaces) +
4181 sizeof (introspect_tail));
4182 introspect_append_header (s);
4183 introspect_append_standard_interfaces (s);
4185 /* then include the registered interfaces */
4186 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4187 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4188 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4190 /* finally include nodes registered below us */
4191 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4192 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4193 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4194 g_strfreev (registered);
4195 g_string_append (s, introspect_tail);
4197 reply = g_dbus_message_new_method_reply (message);
4198 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4199 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4200 g_object_unref (reply);
4201 g_string_free (s, TRUE);
4206 /* called in thread where object was registered - no locks held */
4208 call_in_idle_cb (gpointer user_data)
4210 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4211 GDBusInterfaceVTable *vtable;
4212 guint registration_id;
4213 guint subtree_registration_id;
4215 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4216 g_assert (vtable != NULL && vtable->method_call != NULL);
4218 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4219 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4221 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4223 subtree_registration_id))
4225 GDBusMessage *reply;
4226 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4227 "org.freedesktop.DBus.Error.UnknownMethod",
4228 _("No such interface `%s' on object at path %s"),
4229 g_dbus_method_invocation_get_interface_name (invocation),
4230 g_dbus_method_invocation_get_object_path (invocation));
4231 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4232 g_object_unref (reply);
4236 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4237 g_dbus_method_invocation_get_sender (invocation),
4238 g_dbus_method_invocation_get_object_path (invocation),
4239 g_dbus_method_invocation_get_interface_name (invocation),
4240 g_dbus_method_invocation_get_method_name (invocation),
4241 g_dbus_method_invocation_get_parameters (invocation),
4242 g_object_ref (invocation),
4243 g_dbus_method_invocation_get_user_data (invocation));
4249 /* called in message handler thread with lock held */
4251 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4252 GDBusMessage *message,
4253 guint registration_id,
4254 guint subtree_registration_id,
4255 GDBusInterfaceInfo *interface_info,
4256 const GDBusInterfaceVTable *vtable,
4257 GMainContext *main_context,
4260 GDBusMethodInvocation *invocation;
4261 const GDBusMethodInfo *method_info;
4262 GDBusMessage *reply;
4263 GVariant *parameters;
4264 GSource *idle_source;
4266 GVariantType *in_type;
4270 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4271 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4273 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4274 * error to the caller
4276 if (method_info == NULL)
4278 reply = g_dbus_message_new_method_error (message,
4279 "org.freedesktop.DBus.Error.UnknownMethod",
4280 _("No such method `%s'"),
4281 g_dbus_message_get_member (message));
4282 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4283 g_object_unref (reply);
4288 parameters = g_dbus_message_get_body (message);
4289 if (parameters == NULL)
4291 parameters = g_variant_new ("()");
4292 g_variant_ref_sink (parameters);
4296 g_variant_ref (parameters);
4299 /* Check that the incoming args are of the right type - if they are not, return
4300 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4302 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4303 if (!g_variant_is_of_type (parameters, in_type))
4307 type_string = g_variant_type_dup_string (in_type);
4309 reply = g_dbus_message_new_method_error (message,
4310 "org.freedesktop.DBus.Error.InvalidArgs",
4311 _("Type of message, `%s', does not match expected type `%s'"),
4312 g_variant_get_type_string (parameters),
4314 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4315 g_variant_type_free (in_type);
4316 g_variant_unref (parameters);
4317 g_object_unref (reply);
4318 g_free (type_string);
4322 g_variant_type_free (in_type);
4324 /* schedule the call in idle */
4325 invocation = g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4326 g_dbus_message_get_path (message),
4327 g_dbus_message_get_interface (message),
4328 g_dbus_message_get_member (message),
4334 g_variant_unref (parameters);
4336 /* TODO: would be nicer with a real MethodData like we already
4337 * have PropertyData and PropertyGetAllData... */
4338 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4339 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4340 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4342 idle_source = g_idle_source_new ();
4343 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4344 g_source_set_callback (idle_source,
4348 g_source_attach (idle_source, main_context);
4349 g_source_unref (idle_source);
4357 /* ---------------------------------------------------------------------------------------------------- */
4359 /* called in message handler thread with lock held */
4361 obj_message_func (GDBusConnection *connection,
4363 GDBusMessage *message)
4365 const gchar *interface_name;
4366 const gchar *member;
4367 const gchar *signature;
4372 interface_name = g_dbus_message_get_interface (message);
4373 member = g_dbus_message_get_member (message);
4374 signature = g_dbus_message_get_signature (message);
4376 /* see if we have an interface for handling this call */
4377 if (interface_name != NULL)
4379 ExportedInterface *ei;
4380 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4383 /* we do - invoke the handler in idle in the right thread */
4385 /* handle no vtable or handler being present */
4386 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
4389 handled = validate_and_maybe_schedule_method_call (connection,
4401 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4402 g_strcmp0 (member, "Introspect") == 0 &&
4403 g_strcmp0 (signature, "") == 0)
4405 handled = handle_introspect (connection, eo, message);
4408 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4409 g_strcmp0 (member, "Get") == 0 &&
4410 g_strcmp0 (signature, "ss") == 0)
4412 handled = handle_getset_property (connection, eo, message, TRUE);
4415 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4416 g_strcmp0 (member, "Set") == 0 &&
4417 g_strcmp0 (signature, "ssv") == 0)
4419 handled = handle_getset_property (connection, eo, message, FALSE);
4422 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4423 g_strcmp0 (member, "GetAll") == 0 &&
4424 g_strcmp0 (signature, "s") == 0)
4426 handled = handle_get_all_properties (connection, eo, message);
4435 * g_dbus_connection_register_object:
4436 * @connection: A #GDBusConnection.
4437 * @object_path: The object path to register at.
4438 * @interface_info: Introspection data for the interface.
4439 * @vtable: A #GDBusInterfaceVTable to call into or %NULL.
4440 * @user_data: Data to pass to functions in @vtable.
4441 * @user_data_free_func: Function to call when the object path is unregistered.
4442 * @error: Return location for error or %NULL.
4444 * Registers callbacks for exported objects at @object_path with the
4445 * D-Bus interface that is described in @interface_info.
4447 * Calls to functions in @vtable (and @user_data_free_func) will
4448 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
4449 * loop</link> of the thread you are calling this method from.
4451 * Note that all #GVariant values passed to functions in @vtable will match
4452 * the signature given in @interface_info - if a remote caller passes
4453 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
4454 * is returned to the remote caller.
4456 * Additionally, if the remote caller attempts to invoke methods or
4457 * access properties not mentioned in @interface_info the
4458 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
4459 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
4460 * are returned to the caller.
4462 * It is considered a programming error if the
4463 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
4464 * #GVariant of incorrect type.
4466 * If an existing callback is already registered at @object_path and
4467 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
4469 * GDBus automatically implements the standard D-Bus interfaces
4470 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
4471 * and org.freedesktop.Peer, so you don't have to implement those for
4472 * the objects you export. You <emphasis>can</emphasis> implement
4473 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
4474 * and setting of properties asynchronously.
4476 * Note that the reference count on @interface_info will be
4477 * incremented by 1 (unless allocated statically, e.g. if the
4478 * reference count is -1, see g_dbus_interface_info_ref()) for as long
4479 * as the object is exported. Also note that @vtable will be copied.
4481 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
4483 * Returns: 0 if @error is set, otherwise a registration id (never 0)
4484 * that can be used with g_dbus_connection_unregister_object() .
4489 g_dbus_connection_register_object (GDBusConnection *connection,
4490 const gchar *object_path,
4491 GDBusInterfaceInfo *interface_info,
4492 const GDBusInterfaceVTable *vtable,
4494 GDestroyNotify user_data_free_func,
4498 ExportedInterface *ei;
4501 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4502 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4503 g_return_val_if_fail (interface_info != NULL, 0);
4504 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
4505 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4509 CONNECTION_LOCK (connection);
4511 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
4514 eo = g_new0 (ExportedObject, 1);
4515 eo->object_path = g_strdup (object_path);
4516 eo->connection = connection;
4517 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
4520 (GDestroyNotify) exported_interface_free);
4521 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
4524 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
4530 _("An object is already exported for the interface %s at %s"),
4531 interface_info->name,
4536 ei = g_new0 (ExportedInterface, 1);
4537 ei->id = _global_registration_id++; /* TODO: overflow etc. */
4539 ei->user_data = user_data;
4540 ei->user_data_free_func = user_data_free_func;
4541 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
4542 ei->interface_info = g_dbus_interface_info_ref (interface_info);
4543 ei->interface_name = g_strdup (interface_info->name);
4544 ei->context = g_main_context_get_thread_default ();
4545 if (ei->context != NULL)
4546 g_main_context_ref (ei->context);
4548 g_hash_table_insert (eo->map_if_name_to_ei,
4549 (gpointer) ei->interface_name,
4551 g_hash_table_insert (connection->map_id_to_ei,
4552 GUINT_TO_POINTER (ei->id),
4558 CONNECTION_UNLOCK (connection);
4564 * g_dbus_connection_unregister_object:
4565 * @connection: A #GDBusConnection.
4566 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
4568 * Unregisters an object.
4570 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
4575 g_dbus_connection_unregister_object (GDBusConnection *connection,
4576 guint registration_id)
4578 ExportedInterface *ei;
4582 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4586 CONNECTION_LOCK (connection);
4588 ei = g_hash_table_lookup (connection->map_id_to_ei,
4589 GUINT_TO_POINTER (registration_id));
4595 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
4596 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
4597 /* unregister object path if we have no more exported interfaces */
4598 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
4599 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
4605 CONNECTION_UNLOCK (connection);
4610 /* ---------------------------------------------------------------------------------------------------- */
4613 * g_dbus_connection_emit_signal:
4614 * @connection: A #GDBusConnection.
4615 * @destination_bus_name: The unique bus name for the destination for the signal or %NULL to emit to all listeners.
4616 * @object_path: Path of remote object.
4617 * @interface_name: D-Bus interface to emit a signal on.
4618 * @signal_name: The name of the signal to emit.
4619 * @parameters: A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
4620 * @error: Return location for error or %NULL.
4624 * If the parameters GVariant is floating, it is consumed.
4626 * This can only fail if @parameters is not compatible with the D-Bus protocol.
4628 * Returns: %TRUE unless @error is set.
4633 g_dbus_connection_emit_signal (GDBusConnection *connection,
4634 const gchar *destination_bus_name,
4635 const gchar *object_path,
4636 const gchar *interface_name,
4637 const gchar *signal_name,
4638 GVariant *parameters,
4641 GDBusMessage *message;
4647 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4648 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
4649 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
4650 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
4651 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
4652 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
4654 if (G_UNLIKELY (_g_dbus_debug_emission ()))
4656 _g_dbus_debug_print_lock ();
4657 g_print ("========================================================================\n"
4658 "GDBus-debug:Emission:\n"
4659 " >>>> SIGNAL EMISSION %s.%s()\n"
4661 " destination %s\n",
4662 interface_name, signal_name,
4664 destination_bus_name != NULL ? destination_bus_name : "(none)");
4665 _g_dbus_debug_print_unlock ();
4668 message = g_dbus_message_new_signal (object_path,
4672 if (destination_bus_name != NULL)
4673 g_dbus_message_set_header (message,
4674 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
4675 g_variant_new_string (destination_bus_name));
4677 if (parameters != NULL)
4678 g_dbus_message_set_body (message, parameters);
4680 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
4681 g_object_unref (message);
4687 add_call_flags (GDBusMessage *message,
4688 GDBusCallFlags flags)
4690 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
4691 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
4695 decode_method_reply (GDBusMessage *reply,
4696 const gchar *method_name,
4697 const GVariantType *reply_type,
4703 switch (g_dbus_message_get_message_type (reply))
4705 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
4706 result = g_dbus_message_get_body (reply);
4709 result = g_variant_new ("()");
4710 g_variant_ref_sink (result);
4714 g_variant_ref (result);
4717 if (!g_variant_is_of_type (result, reply_type))
4719 gchar *type_string = g_variant_type_dup_string (reply_type);
4723 G_IO_ERROR_INVALID_ARGUMENT,
4724 _("Method `%s' returned type `%s', but expected `%s'"),
4725 method_name, g_variant_get_type_string (result), type_string);
4727 g_variant_unref (result);
4728 g_free (type_string);
4733 case G_DBUS_MESSAGE_TYPE_ERROR:
4734 g_dbus_message_to_gerror (reply, error);
4738 g_assert_not_reached ();
4748 GSimpleAsyncResult *simple;
4749 GVariantType *reply_type;
4750 gchar *method_name; /* for error message */
4755 g_dbus_connection_call_done (GObject *source,
4756 GAsyncResult *result,
4759 GDBusConnection *connection = G_DBUS_CONNECTION (source);
4760 CallState *state = user_data;
4762 GDBusMessage *reply;
4766 reply = g_dbus_connection_send_message_with_reply_finish (connection,
4770 if (G_UNLIKELY (_g_dbus_debug_call ()))
4772 _g_dbus_debug_print_lock ();
4773 g_print ("========================================================================\n"
4774 "GDBus-debug:Call:\n"
4775 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
4781 g_print ("SUCCESS\n");
4785 g_print ("FAILED: %s\n",
4788 _g_dbus_debug_print_unlock ();
4794 value = decode_method_reply (reply, state->method_name,
4795 state->reply_type, &error);
4796 g_object_unref (reply);
4803 g_simple_async_result_set_from_error (state->simple, error);
4804 g_error_free (error);
4807 g_simple_async_result_set_op_res_gpointer (state->simple, value,
4808 (GDestroyNotify) g_variant_unref);
4810 g_simple_async_result_complete (state->simple);
4811 g_variant_type_free (state->reply_type);
4812 g_object_unref (state->simple);
4813 g_free (state->method_name);
4815 g_slice_free (CallState, state);
4819 * g_dbus_connection_call:
4820 * @connection: A #GDBusConnection.
4821 * @bus_name: A unique or well-known bus name or %NULL if @connection is not a message bus connection.
4822 * @object_path: Path of remote object.
4823 * @interface_name: D-Bus interface to invoke method on.
4824 * @method_name: The name of the method to invoke.
4825 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4826 * @reply_type: The expected type of the reply, or %NULL.
4827 * @flags: Flags from the #GDBusCallFlags enumeration.
4828 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4829 * @cancellable: A #GCancellable or %NULL.
4830 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
4831 * care about the result of the method invocation.
4832 * @user_data: The data to pass to @callback.
4834 * Asynchronously invokes the @method_name method on the
4835 * @interface_name D-Bus interface on the remote object at
4836 * @object_path owned by @bus_name.
4838 * If @connection is closed then the operation will fail with
4839 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
4840 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
4841 * not compatible with the D-Bus protocol, the operation fails with
4842 * %G_IO_ERROR_INVALID_ARGUMENT.
4844 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
4845 * error will be raised if it does not match. Said another way, if you give a @reply_type
4846 * then any non-%NULL return value will be of this type.
4848 * If the @parameters #GVariant is floating, it is consumed. This allows
4849 * convenient 'inline' use of g_variant_new(), e.g.:
4851 * g_dbus_connection_call (connection,
4852 * "org.freedesktop.StringThings",
4853 * "/org/freedesktop/StringThings",
4854 * "org.freedesktop.StringThings",
4856 * g_variant_new ("(ss)",
4860 * G_DBUS_CALL_FLAGS_NONE,
4863 * (GAsyncReadyCallback) two_strings_done,
4867 * This is an asynchronous method. When the operation is finished, @callback will be invoked
4868 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
4869 * of the thread you are calling this method from. You can then call
4870 * g_dbus_connection_call_finish() to get the result of the operation.
4871 * See g_dbus_connection_call_sync() for the synchronous version of this
4877 g_dbus_connection_call (GDBusConnection *connection,
4878 const gchar *bus_name,
4879 const gchar *object_path,
4880 const gchar *interface_name,
4881 const gchar *method_name,
4882 GVariant *parameters,
4883 const GVariantType *reply_type,
4884 GDBusCallFlags flags,
4886 GCancellable *cancellable,
4887 GAsyncReadyCallback callback,
4890 GDBusMessage *message;
4893 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4894 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
4895 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
4896 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
4897 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
4898 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
4899 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
4901 state = g_slice_new (CallState);
4902 state->simple = g_simple_async_result_new (G_OBJECT (connection),
4903 callback, user_data,
4904 g_dbus_connection_call);
4905 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
4907 if (reply_type == NULL)
4908 reply_type = G_VARIANT_TYPE_ANY;
4910 state->reply_type = g_variant_type_copy (reply_type);
4912 message = g_dbus_message_new_method_call (bus_name,
4916 add_call_flags (message, flags);
4917 if (parameters != NULL)
4918 g_dbus_message_set_body (message, parameters);
4920 g_dbus_connection_send_message_with_reply (connection,
4922 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
4926 g_dbus_connection_call_done,
4929 if (G_UNLIKELY (_g_dbus_debug_call ()))
4931 _g_dbus_debug_print_lock ();
4932 g_print ("========================================================================\n"
4933 "GDBus-debug:Call:\n"
4934 " >>>> ASYNC %s.%s()\n"
4936 " owned by name %s (serial %d)\n",
4940 bus_name != NULL ? bus_name : "(none)",
4942 _g_dbus_debug_print_unlock ();
4945 if (message != NULL)
4946 g_object_unref (message);
4950 * g_dbus_connection_call_finish:
4951 * @connection: A #GDBusConnection.
4952 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
4953 * @error: Return location for error or %NULL.
4955 * Finishes an operation started with g_dbus_connection_call().
4957 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4958 * return values. Free with g_variant_unref().
4963 g_dbus_connection_call_finish (GDBusConnection *connection,
4967 GSimpleAsyncResult *simple;
4969 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4970 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
4971 g_dbus_connection_call), NULL);
4972 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4974 simple = G_SIMPLE_ASYNC_RESULT (res);
4976 if (g_simple_async_result_propagate_error (simple, error))
4979 return g_variant_ref (g_simple_async_result_get_op_res_gpointer (simple));
4982 /* ---------------------------------------------------------------------------------------------------- */
4985 * g_dbus_connection_call_sync:
4986 * @connection: A #GDBusConnection.
4987 * @bus_name: A unique or well-known bus name.
4988 * @object_path: Path of remote object.
4989 * @interface_name: D-Bus interface to invoke method on.
4990 * @method_name: The name of the method to invoke.
4991 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4992 * @reply_type: The expected type of the reply, or %NULL.
4993 * @flags: Flags from the #GDBusCallFlags enumeration.
4994 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4995 * @cancellable: A #GCancellable or %NULL.
4996 * @error: Return location for error or %NULL.
4998 * Synchronously invokes the @method_name method on the
4999 * @interface_name D-Bus interface on the remote object at
5000 * @object_path owned by @bus_name.
5002 * If @connection is closed then the operation will fail with
5003 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
5004 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
5005 * contains a value not compatible with the D-Bus protocol, the operation
5006 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
5008 * If @reply_type is non-%NULL then the reply will be checked for having
5009 * this type and an error will be raised if it does not match. Said
5010 * another way, if you give a @reply_type then any non-%NULL return
5011 * value will be of this type.
5013 * If the @parameters #GVariant is floating, it is consumed.
5014 * This allows convenient 'inline' use of g_variant_new(), e.g.:
5016 * g_dbus_connection_call_sync (connection,
5017 * "org.freedesktop.StringThings",
5018 * "/org/freedesktop/StringThings",
5019 * "org.freedesktop.StringThings",
5021 * g_variant_new ("(ss)",
5025 * G_DBUS_CALL_FLAGS_NONE,
5031 * The calling thread is blocked until a reply is received. See
5032 * g_dbus_connection_call() for the asynchronous version of
5035 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5036 * return values. Free with g_variant_unref().
5041 g_dbus_connection_call_sync (GDBusConnection *connection,
5042 const gchar *bus_name,
5043 const gchar *object_path,
5044 const gchar *interface_name,
5045 const gchar *method_name,
5046 GVariant *parameters,
5047 const GVariantType *reply_type,
5048 GDBusCallFlags flags,
5050 GCancellable *cancellable,
5053 GDBusMessage *message;
5054 GDBusMessage *reply;
5056 GError *local_error;
5062 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5063 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5064 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5065 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5066 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5067 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5068 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5070 if (reply_type == NULL)
5071 reply_type = G_VARIANT_TYPE_ANY;
5073 message = g_dbus_message_new_method_call (bus_name,
5077 add_call_flags (message, flags);
5078 if (parameters != NULL)
5079 g_dbus_message_set_body (message, parameters);
5081 if (G_UNLIKELY (_g_dbus_debug_call ()))
5083 _g_dbus_debug_print_lock ();
5084 g_print ("========================================================================\n"
5085 "GDBus-debug:Call:\n"
5086 " >>>> SYNC %s.%s()\n"
5088 " owned by name %s\n",
5092 bus_name != NULL ? bus_name : "(none)");
5093 _g_dbus_debug_print_unlock ();
5097 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5099 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5101 NULL, /* volatile guint32 *out_serial */
5105 if (G_UNLIKELY (_g_dbus_debug_call ()))
5107 _g_dbus_debug_print_lock ();
5108 g_print ("========================================================================\n"
5109 "GDBus-debug:Call:\n"
5110 " <<<< SYNC COMPLETE %s.%s()\n"
5116 g_print ("SUCCESS\n");
5120 g_print ("FAILED: %s\n",
5121 local_error->message);
5123 _g_dbus_debug_print_unlock ();
5129 *error = local_error;
5131 g_error_free (local_error);
5135 result = decode_method_reply (reply, method_name, reply_type, error);
5138 if (message != NULL)
5139 g_object_unref (message);
5141 g_object_unref (reply);
5146 /* ---------------------------------------------------------------------------------------------------- */
5148 struct ExportedSubtree
5152 GDBusConnection *connection;
5153 GDBusSubtreeVTable *vtable;
5154 GDBusSubtreeFlags flags;
5156 GMainContext *context;
5158 GDestroyNotify user_data_free_func;
5162 exported_subtree_free (ExportedSubtree *es)
5164 if (es->user_data_free_func != NULL)
5165 /* TODO: push to thread-default mainloop */
5166 es->user_data_free_func (es->user_data);
5168 if (es->context != NULL)
5169 g_main_context_unref (es->context);
5171 _g_dbus_subtree_vtable_free (es->vtable);
5172 g_free (es->object_path);
5176 /* called without lock held */
5178 handle_subtree_introspect (GDBusConnection *connection,
5179 ExportedSubtree *es,
5180 GDBusMessage *message)
5184 GDBusMessage *reply;
5187 const gchar *sender;
5188 const gchar *requested_object_path;
5189 const gchar *requested_node;
5190 GDBusInterfaceInfo **interfaces;
5192 gchar **subnode_paths;
5196 requested_object_path = g_dbus_message_get_path (message);
5197 sender = g_dbus_message_get_sender (message);
5198 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5200 s = g_string_new (NULL);
5201 introspect_append_header (s);
5203 /* Strictly we don't need the children in dynamic mode, but we avoid the
5204 * conditionals to preserve code clarity
5206 children = es->vtable->enumerate (es->connection,
5213 requested_node = strrchr (requested_object_path, '/') + 1;
5215 /* Assert existence of object if we are not dynamic */
5216 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
5217 !_g_strv_has_string ((const gchar * const *) children, requested_node))
5222 requested_node = NULL;
5225 interfaces = es->vtable->introspect (es->connection,
5230 if (interfaces != NULL)
5232 introspect_append_standard_interfaces (s);
5234 for (n = 0; interfaces[n] != NULL; n++)
5236 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
5237 g_dbus_interface_info_unref (interfaces[n]);
5239 g_free (interfaces);
5242 /* then include <node> entries from the Subtree for the root */
5245 for (n = 0; children != NULL && children[n] != NULL; n++)
5246 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
5249 /* finally include nodes registered below us */
5250 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
5251 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
5252 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
5253 g_strfreev (subnode_paths);
5255 g_string_append (s, "</node>\n");
5257 reply = g_dbus_message_new_method_reply (message);
5258 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5259 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5260 g_object_unref (reply);
5265 g_string_free (s, TRUE);
5266 g_strfreev (children);
5270 /* called without lock held */
5272 handle_subtree_method_invocation (GDBusConnection *connection,
5273 ExportedSubtree *es,
5274 GDBusMessage *message)
5277 const gchar *sender;
5278 const gchar *interface_name;
5279 const gchar *member;
5280 const gchar *signature;
5281 const gchar *requested_object_path;
5282 const gchar *requested_node;
5284 GDBusInterfaceInfo *interface_info;
5285 const GDBusInterfaceVTable *interface_vtable;
5286 gpointer interface_user_data;
5288 GDBusInterfaceInfo **interfaces;
5289 gboolean is_property_get;
5290 gboolean is_property_set;
5291 gboolean is_property_get_all;
5296 requested_object_path = g_dbus_message_get_path (message);
5297 sender = g_dbus_message_get_sender (message);
5298 interface_name = g_dbus_message_get_interface (message);
5299 member = g_dbus_message_get_member (message);
5300 signature = g_dbus_message_get_signature (message);
5301 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5303 is_property_get = FALSE;
5304 is_property_set = FALSE;
5305 is_property_get_all = FALSE;
5306 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
5308 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
5309 is_property_get = TRUE;
5310 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
5311 is_property_set = TRUE;
5312 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
5313 is_property_get_all = TRUE;
5318 requested_node = strrchr (requested_object_path, '/') + 1;
5320 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
5322 /* We don't want to dispatch to unenumerated
5323 * nodes, so ensure that the child exists.
5328 children = es->vtable->enumerate (es->connection,
5333 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
5334 g_strfreev (children);
5342 requested_node = NULL;
5345 /* get introspection data for the node */
5346 interfaces = es->vtable->introspect (es->connection,
5348 requested_object_path,
5352 if (interfaces == NULL)
5355 interface_info = NULL;
5356 for (n = 0; interfaces[n] != NULL; n++)
5358 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
5359 interface_info = interfaces[n];
5362 /* dispatch the call if the user wants to handle it */
5363 if (interface_info != NULL)
5365 /* figure out where to dispatch the method call */
5366 interface_user_data = NULL;
5367 interface_vtable = es->vtable->dispatch (es->connection,
5372 &interface_user_data,
5374 if (interface_vtable == NULL)
5377 CONNECTION_LOCK (connection);
5378 handled = validate_and_maybe_schedule_method_call (es->connection,
5385 interface_user_data);
5386 CONNECTION_UNLOCK (connection);
5388 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
5389 else if (is_property_get || is_property_set || is_property_get_all)
5391 if (is_property_get)
5392 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
5393 else if (is_property_set)
5394 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
5395 else if (is_property_get_all)
5396 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
5398 g_assert_not_reached ();
5400 /* see if the object supports this interface at all */
5401 for (n = 0; interfaces[n] != NULL; n++)
5403 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
5404 interface_info = interfaces[n];
5407 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
5408 * claims it won't support the interface
5410 if (interface_info == NULL)
5412 GDBusMessage *reply;
5413 reply = g_dbus_message_new_method_error (message,
5414 "org.freedesktop.DBus.Error.InvalidArgs",
5415 _("No such interface `%s'"),
5417 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5418 g_object_unref (reply);
5423 /* figure out where to dispatch the property get/set/getall calls */
5424 interface_user_data = NULL;
5425 interface_vtable = es->vtable->dispatch (es->connection,
5430 &interface_user_data,
5432 if (interface_vtable == NULL)
5434 g_warning ("The subtree introspection function indicates that '%s' "
5435 "is a valid interface name, but calling the dispatch "
5436 "function on that interface gave us NULL", interface_name);
5440 if (is_property_get || is_property_set)
5442 CONNECTION_LOCK (connection);
5443 handled = validate_and_maybe_schedule_property_getset (es->connection,
5451 interface_user_data);
5452 CONNECTION_UNLOCK (connection);
5454 else if (is_property_get_all)
5456 CONNECTION_LOCK (connection);
5457 handled = validate_and_maybe_schedule_property_get_all (es->connection,
5464 interface_user_data);
5465 CONNECTION_UNLOCK (connection);
5470 if (interfaces != NULL)
5472 for (n = 0; interfaces[n] != NULL; n++)
5473 g_dbus_interface_info_unref (interfaces[n]);
5474 g_free (interfaces);
5482 GDBusMessage *message;
5483 ExportedSubtree *es;
5484 } SubtreeDeferredData;
5487 subtree_deferred_data_free (SubtreeDeferredData *data)
5489 g_object_unref (data->message);
5493 /* called without lock held in the thread where the caller registered the subtree */
5495 process_subtree_vtable_message_in_idle_cb (gpointer _data)
5497 SubtreeDeferredData *data = _data;
5502 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
5503 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
5504 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
5505 handled = handle_subtree_introspect (data->es->connection,
5509 handled = handle_subtree_method_invocation (data->es->connection,
5515 CONNECTION_LOCK (data->es->connection);
5516 handled = handle_generic_unlocked (data->es->connection, data->message);
5517 CONNECTION_UNLOCK (data->es->connection);
5520 /* if we couldn't handle the request, just bail with the UnknownMethod error */
5523 GDBusMessage *reply;
5524 reply = g_dbus_message_new_method_error (data->message,
5525 "org.freedesktop.DBus.Error.UnknownMethod",
5526 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
5527 g_dbus_message_get_member (data->message),
5528 g_dbus_message_get_interface (data->message),
5529 g_dbus_message_get_signature (data->message));
5530 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5531 g_object_unref (reply);
5537 /* called in message handler thread with lock held */
5539 subtree_message_func (GDBusConnection *connection,
5540 ExportedSubtree *es,
5541 GDBusMessage *message)
5543 GSource *idle_source;
5544 SubtreeDeferredData *data;
5546 data = g_new0 (SubtreeDeferredData, 1);
5547 data->message = g_object_ref (message);
5550 /* defer this call to an idle handler in the right thread */
5551 idle_source = g_idle_source_new ();
5552 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
5553 g_source_set_callback (idle_source,
5554 process_subtree_vtable_message_in_idle_cb,
5556 (GDestroyNotify) subtree_deferred_data_free);
5557 g_source_attach (idle_source, es->context);
5558 g_source_unref (idle_source);
5560 /* since we own the entire subtree, handlers for objects not in the subtree have been
5561 * tried already by libdbus-1 - so we just need to ensure that we're always going
5562 * to reply to the message
5568 * g_dbus_connection_register_subtree:
5569 * @connection: A #GDBusConnection.
5570 * @object_path: The object path to register the subtree at.
5571 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
5572 * @flags: Flags used to fine tune the behavior of the subtree.
5573 * @user_data: Data to pass to functions in @vtable.
5574 * @user_data_free_func: Function to call when the subtree is unregistered.
5575 * @error: Return location for error or %NULL.
5577 * Registers a whole subtree of <quote>dynamic</quote> objects.
5579 * The @enumerate and @introspection functions in @vtable are used to
5580 * convey, to remote callers, what nodes exist in the subtree rooted
5583 * When handling remote calls into any node in the subtree, first the
5584 * @enumerate function is used to check if the node exists. If the node exists
5585 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
5586 * the @introspection function is used to check if the node supports the
5587 * requested method. If so, the @dispatch function is used to determine
5588 * where to dispatch the call. The collected #GDBusInterfaceVTable and
5589 * #gpointer will be used to call into the interface vtable for processing
5592 * All calls into user-provided code will be invoked in the <link
5593 * linkend="g-main-context-push-thread-default">thread-default main
5594 * loop</link> of the thread you are calling this method from.
5596 * If an existing subtree is already registered at @object_path or
5597 * then @error is set to #G_IO_ERROR_EXISTS.
5599 * Note that it is valid to register regular objects (using
5600 * g_dbus_connection_register_object()) in a subtree registered with
5601 * g_dbus_connection_register_subtree() - if so, the subtree handler
5602 * is tried as the last resort. One way to think about a subtree
5603 * handler is to consider it a <quote>fallback handler</quote>
5604 * for object paths not registered via g_dbus_connection_register_object()
5605 * or other bindings.
5607 * Note that @vtable will be copied so you cannot change it after
5610 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
5612 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
5613 * that can be used with g_dbus_connection_unregister_subtree() .
5618 g_dbus_connection_register_subtree (GDBusConnection *connection,
5619 const gchar *object_path,
5620 const GDBusSubtreeVTable *vtable,
5621 GDBusSubtreeFlags flags,
5623 GDestroyNotify user_data_free_func,
5627 ExportedSubtree *es;
5629 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5630 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5631 g_return_val_if_fail (vtable != NULL, 0);
5632 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5636 CONNECTION_LOCK (connection);
5638 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
5644 _("A subtree is already exported for %s"),
5649 es = g_new0 (ExportedSubtree, 1);
5650 es->object_path = g_strdup (object_path);
5651 es->connection = connection;
5653 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
5655 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
5656 es->user_data = user_data;
5657 es->user_data_free_func = user_data_free_func;
5658 es->context = g_main_context_get_thread_default ();
5659 if (es->context != NULL)
5660 g_main_context_ref (es->context);
5662 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
5663 g_hash_table_insert (connection->map_id_to_es,
5664 GUINT_TO_POINTER (es->id),
5670 CONNECTION_UNLOCK (connection);
5675 /* ---------------------------------------------------------------------------------------------------- */
5678 * g_dbus_connection_unregister_subtree:
5679 * @connection: A #GDBusConnection.
5680 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
5682 * Unregisters a subtree.
5684 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
5689 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
5690 guint registration_id)
5692 ExportedSubtree *es;
5695 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5699 CONNECTION_LOCK (connection);
5701 es = g_hash_table_lookup (connection->map_id_to_es,
5702 GUINT_TO_POINTER (registration_id));
5706 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
5707 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
5712 CONNECTION_UNLOCK (connection);
5717 /* ---------------------------------------------------------------------------------------------------- */
5719 /* must be called with lock held */
5721 handle_generic_ping_unlocked (GDBusConnection *connection,
5722 const gchar *object_path,
5723 GDBusMessage *message)
5725 GDBusMessage *reply;
5726 reply = g_dbus_message_new_method_reply (message);
5727 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5728 g_object_unref (reply);
5731 /* must be called with lock held */
5733 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
5734 const gchar *object_path,
5735 GDBusMessage *message)
5737 GDBusMessage *reply;
5740 if (connection->machine_id == NULL)
5745 connection->machine_id = _g_dbus_get_machine_id (&error);
5746 if (connection->machine_id == NULL)
5748 reply = g_dbus_message_new_method_error_literal (message,
5749 "org.freedesktop.DBus.Error.Failed",
5751 g_error_free (error);
5757 reply = g_dbus_message_new_method_reply (message);
5758 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
5760 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5761 g_object_unref (reply);
5764 /* must be called with lock held */
5766 handle_generic_introspect_unlocked (GDBusConnection *connection,
5767 const gchar *object_path,
5768 GDBusMessage *message)
5773 GDBusMessage *reply;
5775 /* first the header */
5776 s = g_string_new (NULL);
5777 introspect_append_header (s);
5779 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
5780 for (n = 0; registered != NULL && registered[n] != NULL; n++)
5781 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
5782 g_strfreev (registered);
5783 g_string_append (s, "</node>\n");
5785 reply = g_dbus_message_new_method_reply (message);
5786 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5787 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5788 g_object_unref (reply);
5789 g_string_free (s, TRUE);
5792 /* must be called with lock held */
5794 handle_generic_unlocked (GDBusConnection *connection,
5795 GDBusMessage *message)
5798 const gchar *interface_name;
5799 const gchar *member;
5800 const gchar *signature;
5803 CONNECTION_ENSURE_LOCK (connection);
5807 interface_name = g_dbus_message_get_interface (message);
5808 member = g_dbus_message_get_member (message);
5809 signature = g_dbus_message_get_signature (message);
5810 path = g_dbus_message_get_path (message);
5812 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5813 g_strcmp0 (member, "Introspect") == 0 &&
5814 g_strcmp0 (signature, "") == 0)
5816 handle_generic_introspect_unlocked (connection, path, message);
5819 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5820 g_strcmp0 (member, "Ping") == 0 &&
5821 g_strcmp0 (signature, "") == 0)
5823 handle_generic_ping_unlocked (connection, path, message);
5826 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5827 g_strcmp0 (member, "GetMachineId") == 0 &&
5828 g_strcmp0 (signature, "") == 0)
5830 handle_generic_get_machine_id_unlocked (connection, path, message);
5837 /* ---------------------------------------------------------------------------------------------------- */
5839 /* called in message handler thread with lock held */
5841 distribute_method_call (GDBusConnection *connection,
5842 GDBusMessage *message)
5844 GDBusMessage *reply;
5846 ExportedSubtree *es;
5847 const gchar *object_path;
5848 const gchar *interface_name;
5849 const gchar *member;
5850 const gchar *signature;
5852 gchar *subtree_path;
5855 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
5857 interface_name = g_dbus_message_get_interface (message);
5858 member = g_dbus_message_get_member (message);
5859 signature = g_dbus_message_get_signature (message);
5860 path = g_dbus_message_get_path (message);
5861 subtree_path = g_strdup (path);
5862 needle = strrchr (subtree_path, '/');
5863 if (needle != NULL && needle != subtree_path)
5869 g_free (subtree_path);
5870 subtree_path = NULL;
5874 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
5876 _g_dbus_debug_print_lock ();
5877 g_print ("========================================================================\n"
5878 "GDBus-debug:Incoming:\n"
5879 " >>>> METHOD INVOCATION %s.%s()\n"
5881 " invoked by name %s\n",
5882 interface_name, member,
5884 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)");
5885 _g_dbus_debug_print_unlock ();
5889 g_debug ("interface = `%s'", interface_name);
5890 g_debug ("member = `%s'", member);
5891 g_debug ("signature = `%s'", signature);
5892 g_debug ("path = `%s'", path);
5893 g_debug ("subtree_path = `%s'", subtree_path != NULL ? subtree_path : "N/A");
5896 object_path = g_dbus_message_get_path (message);
5897 g_assert (object_path != NULL);
5899 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5902 if (obj_message_func (connection, eo, message))
5906 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
5909 if (subtree_message_func (connection, es, message))
5913 if (subtree_path != NULL)
5915 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
5918 if (subtree_message_func (connection, es, message))
5923 if (handle_generic_unlocked (connection, message))
5926 /* if we end up here, the message has not been not handled - so return an error saying this */
5927 reply = g_dbus_message_new_method_error (message,
5928 "org.freedesktop.DBus.Error.UnknownMethod",
5929 _("No such interface `%s' on object at path %s"),
5932 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5933 g_object_unref (reply);
5936 g_free (subtree_path);
5939 /* ---------------------------------------------------------------------------------------------------- */
5941 static GDBusConnection **
5942 message_bus_get_singleton (GBusType bus_type,
5945 GDBusConnection **ret;
5946 const gchar *starter_bus;
5952 case G_BUS_TYPE_SESSION:
5953 ret = &the_session_bus;
5956 case G_BUS_TYPE_SYSTEM:
5957 ret = &the_system_bus;
5960 case G_BUS_TYPE_STARTER:
5961 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
5962 if (g_strcmp0 (starter_bus, "session") == 0)
5964 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
5967 else if (g_strcmp0 (starter_bus, "system") == 0)
5969 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
5974 if (starter_bus != NULL)
5978 G_IO_ERROR_INVALID_ARGUMENT,
5979 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
5980 " - unknown value `%s'"),
5985 g_set_error_literal (error,
5987 G_IO_ERROR_INVALID_ARGUMENT,
5988 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
5989 "variable is not set"));
5995 g_assert_not_reached ();
6003 static GDBusConnection *
6004 get_uninitialized_connection (GBusType bus_type,
6005 GCancellable *cancellable,
6008 GDBusConnection **singleton;
6009 GDBusConnection *ret;
6013 G_LOCK (message_bus_lock);
6014 singleton = message_bus_get_singleton (bus_type, error);
6015 if (singleton == NULL)
6018 if (*singleton == NULL)
6021 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
6022 if (address == NULL)
6024 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
6026 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
6027 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
6028 "exit-on-close", TRUE,
6034 ret = g_object_ref (*singleton);
6037 g_assert (ret != NULL);
6040 G_UNLOCK (message_bus_lock);
6046 * @bus_type: A #GBusType.
6047 * @cancellable: A #GCancellable or %NULL.
6048 * @error: Return location for error or %NULL.
6050 * Synchronously connects to the message bus specified by @bus_type.
6051 * Note that the returned object may shared with other callers,
6052 * e.g. if two separate parts of a process calls this function with
6053 * the same @bus_type, they will share the same object.
6055 * This is a synchronous failable function. See g_bus_get() and
6056 * g_bus_get_finish() for the asynchronous version.
6058 * The returned object is a singleton, that is, shared with other
6059 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6060 * event that you need a private message bus connection, use
6061 * g_dbus_address_get_for_bus_sync() and
6062 * g_dbus_connection_new_for_address().
6064 * Note that the returned #GDBusConnection object will (usually) have
6065 * the #GDBusConnection:exit-on-close property set to %TRUE.
6067 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6072 g_bus_get_sync (GBusType bus_type,
6073 GCancellable *cancellable,
6076 GDBusConnection *connection;
6078 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6080 connection = get_uninitialized_connection (bus_type, cancellable, error);
6081 if (connection == NULL)
6084 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
6086 g_object_unref (connection);
6095 bus_get_async_initable_cb (GObject *source_object,
6099 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
6103 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
6107 g_assert (error != NULL);
6108 g_simple_async_result_set_from_error (simple, error);
6109 g_error_free (error);
6110 g_object_unref (source_object);
6114 g_simple_async_result_set_op_res_gpointer (simple,
6118 g_simple_async_result_complete_in_idle (simple);
6119 g_object_unref (simple);
6124 * @bus_type: A #GBusType.
6125 * @cancellable: A #GCancellable or %NULL.
6126 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
6127 * @user_data: The data to pass to @callback.
6129 * Asynchronously connects to the message bus specified by @bus_type.
6131 * When the operation is finished, @callback will be invoked. You can
6132 * then call g_bus_get_finish() to get the result of the operation.
6134 * This is a asynchronous failable function. See g_bus_get_sync() for
6135 * the synchronous version.
6140 g_bus_get (GBusType bus_type,
6141 GCancellable *cancellable,
6142 GAsyncReadyCallback callback,
6145 GDBusConnection *connection;
6146 GSimpleAsyncResult *simple;
6149 simple = g_simple_async_result_new (NULL,
6155 connection = get_uninitialized_connection (bus_type, cancellable, &error);
6156 if (connection == NULL)
6158 g_assert (error != NULL);
6159 g_simple_async_result_set_from_error (simple, error);
6160 g_error_free (error);
6161 g_simple_async_result_complete_in_idle (simple);
6162 g_object_unref (simple);
6166 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
6169 bus_get_async_initable_cb,
6176 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
6177 * @error: Return location for error or %NULL.
6179 * Finishes an operation started with g_bus_get().
6181 * The returned object is a singleton, that is, shared with other
6182 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6183 * event that you need a private message bus connection, use
6184 * g_dbus_address_get_for_bus() and
6185 * g_dbus_connection_new_for_address().
6187 * Note that the returned #GDBusConnection object will (usually) have
6188 * the #GDBusConnection:exit-on-close property set to %TRUE.
6190 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6195 g_bus_get_finish (GAsyncResult *res,
6198 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
6200 GDBusConnection *ret;
6202 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6204 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
6208 if (g_simple_async_result_propagate_error (simple, error))
6211 object = g_simple_async_result_get_op_res_gpointer (simple);
6212 g_assert (object != NULL);
6213 ret = g_object_ref (G_DBUS_CONNECTION (object));
6219 /* ---------------------------------------------------------------------------------------------------- */