1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, write to the
17 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18 * Boston, MA 02111-1307, USA.
20 * Author: David Zeuthen <davidz@redhat.com>
26 * - would be nice to expose GDBusAuthMechanism and an extension point
28 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
29 * the mechanism VFuncs need to be able to set an error.
31 * - Need to document other mechanisms/sources for determining the D-Bus
32 * address of a well-known bus.
34 * - e.g. on Win32 we need code like from here
36 * http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
38 * that was never copied over here because it originally was copy-paste
39 * from the GPLv2 / AFL 2.1 libdbus sources.
41 * - on OS X we need to look in launchd for the address
43 * https://bugs.freedesktop.org/show_bug.cgi?id=14259
45 * - on X11 we need to look in a X11 property on the X server
46 * - (we can also just use dbus-launch(1) from the D-Bus
49 * - (ideally) this requires D-Bus spec work because none of
50 * this has never really been specced out properly (except
53 * - Related to the above, we also need to be able to launch a message bus
54 * instance.... Since we don't want to write our own bus daemon we should
55 * launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
57 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
58 * to specify where the nonce is stored. This will allow people to use
59 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
60 * to easily achieve secure RPC via nonce-tcp.
62 * - need to expose an extension point for resolving D-Bus address and
63 * turning them into GIOStream objects. This will allow us to implement
64 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
66 * - see g_dbus_address_connect() in gdbusaddress.c
68 * - would be cute to use kernel-specific APIs to resolve fds for
69 * debug output when using G_DBUS_DEBUG=message, e.g. in addition to
71 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
73 * maybe we can show more information about what fd 21 really is.
74 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
75 * Initial experiments on Linux 2.6 suggests that the symlink looks
80 * e.g. not of much use.
82 * - GDBus High-Level docs
83 * - Proxy: properties, signals...
84 * - Connection: IOStream based, ::close, connection setup steps
85 * mainloop integration, threading
86 * - Differences from libdbus (extend "Migrating from")
87 * - the message handling thread
88 * - Using GVariant instead of GValue
89 * - Explain why the high-level API is a good thing and what
90 * kind of pitfalls it avoids
91 * - Export objects before claiming names
92 * - Talk about auto-starting services (cf. GBusNameWatcherFlags)
94 * - use abstract sockets in test code
95 * - right now it doesn't work, dbus-daemon(1) fails with
97 * /gdbus/connection/filter: Failed to start message bus: Failed to bind
98 * socket "/tmp/g-dbus-tests-pid-28531": Address already in use
99 * ** WARNING **: Error reading address from dbus daemon, 0 bytes read
108 #include <sys/types.h>
113 #include "gdbusauth.h"
114 #include "gdbusutils.h"
115 #include "gdbusaddress.h"
116 #include "gdbusmessage.h"
117 #include "gdbusconnection.h"
118 #include "gdbuserror.h"
119 #include "gioenumtypes.h"
120 #include "gdbusintrospection.h"
121 #include "gdbusmethodinvocation.h"
122 #include "gdbusprivate.h"
123 #include "gdbusauthobserver.h"
124 #include "ginitable.h"
125 #include "gasyncinitable.h"
126 #include "giostream.h"
127 #include "gasyncresult.h"
128 #include "gsimpleasyncresult.h"
131 #include "gunixconnection.h"
132 #include "gunixfdmessage.h"
135 #include "glibintl.h"
138 * SECTION:gdbusconnection
139 * @short_description: D-Bus Connections
140 * @include: gio/gio.h
142 * The #GDBusConnection type is used for D-Bus connections to remote
143 * peers such as a message buses. It is a low-level API that offers a
144 * lot of flexibility. For instance, it lets you establish a connection
145 * over any transport that can by represented as an #GIOStream.
147 * This class is rarely used directly in D-Bus clients. If you are writing
148 * an D-Bus client, it is often easier to use the g_bus_own_name(),
149 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
151 * <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>
153 * <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>
155 * <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>
157 * <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>
160 /* ---------------------------------------------------------------------------------------------------- */
162 typedef struct _GDBusConnectionClass GDBusConnectionClass;
165 * GDBusConnectionClass:
166 * @closed: Signal class handler for the #GDBusConnection::closed signal.
168 * Class structure for #GDBusConnection.
172 struct _GDBusConnectionClass
175 GObjectClass parent_class;
179 void (*closed) (GDBusConnection *connection,
180 gboolean remote_peer_vanished,
184 G_LOCK_DEFINE_STATIC (message_bus_lock);
186 static GDBusConnection *the_session_bus = NULL;
187 static GDBusConnection *the_system_bus = NULL;
189 /* Extra pseudo-member of GDBusSendMessageFlags.
190 * Set by initable_init() to indicate that despite not being initialized yet,
191 * enough of the only-valid-after-init members are set that we can send a
192 * message, and we're being called from its thread, so no memory barrier is
193 * required before accessing them.
195 #define SEND_MESSAGE_FLAGS_INITIALIZING (1<<31)
197 /* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
198 #define CALL_FLAGS_INITIALIZING (1<<31)
200 /* ---------------------------------------------------------------------------------------------------- */
204 GDestroyNotify callback;
206 GMainContext *context;
207 } CallDestroyNotifyData;
210 call_destroy_notify_data_in_idle (gpointer user_data)
212 CallDestroyNotifyData *data = user_data;
213 data->callback (data->user_data);
218 call_destroy_notify_data_free (CallDestroyNotifyData *data)
220 if (data->context != NULL)
221 g_main_context_unref (data->context);
226 * call_destroy_notify: <internal>
227 * @context: A #GMainContext or %NULL.
228 * @callback: A #GDestroyNotify or %NULL.
229 * @user_data: Data to pass to @callback.
231 * Schedules @callback to run in @context.
234 call_destroy_notify (GMainContext *context,
235 GDestroyNotify callback,
238 GMainContext *current_context;
240 if (callback == NULL)
243 current_context = g_main_context_get_thread_default ();
244 if ((context == current_context) ||
245 (current_context == NULL && context == g_main_context_default ()))
247 callback (user_data);
251 GSource *idle_source;
252 CallDestroyNotifyData *data;
254 data = g_new0 (CallDestroyNotifyData, 1);
255 data->callback = callback;
256 data->user_data = user_data;
257 data->context = context;
258 if (data->context != NULL)
259 g_main_context_ref (data->context);
261 idle_source = g_idle_source_new ();
262 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
263 g_source_set_callback (idle_source,
264 call_destroy_notify_data_in_idle,
266 (GDestroyNotify) call_destroy_notify_data_free);
267 g_source_attach (idle_source, data->context);
268 g_source_unref (idle_source);
275 /* ---------------------------------------------------------------------------------------------------- */
278 _g_strv_has_string (const gchar* const *haystack,
283 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
285 if (g_strcmp0 (haystack[n], needle) == 0)
291 /* ---------------------------------------------------------------------------------------------------- */
294 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
296 // TODO: for some reason this doesn't work on Windows
297 #define CONNECTION_ENSURE_LOCK(obj) do { \
298 if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock))) \
300 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
301 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
306 #define CONNECTION_LOCK(obj) do { \
307 g_mutex_lock (&(obj)->lock); \
310 #define CONNECTION_UNLOCK(obj) do { \
311 g_mutex_unlock (&(obj)->lock); \
314 /* Flags in connection->atomic_flags */
316 FLAG_INITIALIZED = 1 << 0
322 * The #GDBusConnection structure contains only private data and
323 * should only be accessed using the provided API.
327 struct _GDBusConnection
330 GObject parent_instance;
332 /* ------------------------------------------------------------------------ */
333 /* -- General object state ------------------------------------------------ */
334 /* ------------------------------------------------------------------------ */
336 /* object-wide lock */
339 /* A lock used in the init() method of the GInitable interface - see comments
340 * in initable_init() for why a separate lock is needed
344 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
345 * someone calls org.freedesktop.DBus.GetMachineId()
349 /* The underlying stream used for communication
350 * Read-only after initable_init(), so it may be read if you either
351 * hold @init_lock or check for initialization first.
355 /* The object used for authentication (if any).
356 * Read-only after initable_init(), so it may be read if you either
357 * hold @init_lock or check for initialization first.
361 /* Set to TRUE if the connection has been closed */
364 /* Last serial used */
367 /* The object used to send/receive messages.
368 * Read-only after initable_init(), so it may be read if you either
369 * hold @init_lock or check for initialization first.
373 /* If connected to a message bus, this contains the unique name assigned to
374 * us by the bus (e.g. ":1.42").
375 * Read-only after initable_init(), so it may be read if you either
376 * hold @init_lock or check for initialization first.
378 gchar *bus_unique_name;
380 /* The GUID returned by the other side if we authenticed as a client or
381 * the GUID to use if authenticating as a server.
382 * Read-only after initable_init(), so it may be read if you either
383 * hold @init_lock or check for initialization first.
387 /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
388 * Inspect @initialization_error to see whether it succeeded or failed.
390 volatile gint atomic_flags;
392 /* If the connection could not be established during initable_init(),
393 * this GError will be set.
394 * Read-only after initable_init(), so it may be read if you either
395 * hold @init_lock or check for initialization first.
397 GError *initialization_error;
399 /* The result of g_main_context_ref_thread_default() when the object
400 * was created (the GObject _init() function) - this is used for delivery
401 * of the :closed GObject signal.
403 GMainContext *main_context_at_construction;
405 /* construct properties */
407 GDBusConnectionFlags flags;
409 /* Map used for managing method replies */
410 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
412 /* Maps used for managing signal subscription */
413 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
414 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
415 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
417 /* Maps used for managing exported objects and subtrees */
418 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
419 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
420 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
421 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
423 /* Structure used for message filters */
426 /* Whether to exit on close */
427 gboolean exit_on_close;
429 /* Capabilities negotiated during authentication
430 * Read-only after initable_init(), so it may be read without holding a
431 * lock, if you check for initialization first.
433 GDBusCapabilityFlags capabilities;
435 GDBusAuthObserver *authentication_observer;
437 /* Read-only after initable_init(), so it may be read if you either
438 * hold @init_lock or check for initialization first.
440 GCredentials *credentials;
442 /* set to TRUE when finalizing */
446 typedef struct ExportedObject ExportedObject;
447 static void exported_object_free (ExportedObject *eo);
449 typedef struct ExportedSubtree ExportedSubtree;
450 static void exported_subtree_free (ExportedSubtree *es);
468 PROP_CAPABILITY_FLAGS,
469 PROP_AUTHENTICATION_OBSERVER,
472 static void distribute_signals (GDBusConnection *connection,
473 GDBusMessage *message);
475 static void distribute_method_call (GDBusConnection *connection,
476 GDBusMessage *message);
478 static gboolean handle_generic_unlocked (GDBusConnection *connection,
479 GDBusMessage *message);
482 static void purge_all_signal_subscriptions (GDBusConnection *connection);
483 static void purge_all_filters (GDBusConnection *connection);
485 #define _G_ENSURE_LOCK(name) do { \
486 if (G_UNLIKELY (G_TRYLOCK(name))) \
488 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
489 "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
493 static guint signals[LAST_SIGNAL] = { 0 };
495 static void initable_iface_init (GInitableIface *initable_iface);
496 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
498 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
499 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
500 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
504 * Check that all members of @connection that can only be accessed after
505 * the connection is initialized can safely be accessed. If not,
506 * log a critical warning. This function is a memory barrier.
508 * Returns: %TRUE if initialized
511 check_initialized (GDBusConnection *connection)
513 /* The access to @atomic_flags isn't conditional, so that this function
514 * provides a memory barrier for thread-safety even if checks are disabled.
515 * (If you don't want this stricter guarantee, you can call
516 * g_return_if_fail (check_initialized (c)).)
518 * This isn't strictly necessary now that we've decided use of an
519 * uninitialized GDBusConnection is undefined behaviour, but it seems
520 * better to be as deterministic as is feasible.
522 * (Anything that could suffer a crash from seeing undefined values
523 * must have a race condition - thread A initializes the connection while
524 * thread B calls a method without initialization, hoping that thread A will
525 * win the race - so its behaviour is undefined anyway.)
527 gint flags = g_atomic_int_get (&connection->atomic_flags);
529 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
531 /* We can safely access this, due to the memory barrier above */
532 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
537 static GHashTable *alive_connections = NULL;
540 g_dbus_connection_dispose (GObject *object)
542 GDBusConnection *connection = G_DBUS_CONNECTION (object);
544 G_LOCK (message_bus_lock);
545 if (connection == the_session_bus)
547 the_session_bus = NULL;
549 else if (connection == the_system_bus)
551 the_system_bus = NULL;
553 CONNECTION_LOCK (connection);
554 if (connection->worker != NULL)
556 _g_dbus_worker_stop (connection->worker);
557 connection->worker = NULL;
558 if (alive_connections != NULL)
559 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
563 if (alive_connections != NULL)
564 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
566 CONNECTION_UNLOCK (connection);
567 G_UNLOCK (message_bus_lock);
569 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
570 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
574 g_dbus_connection_finalize (GObject *object)
576 GDBusConnection *connection = G_DBUS_CONNECTION (object);
578 connection->finalizing = TRUE;
580 purge_all_signal_subscriptions (connection);
582 purge_all_filters (connection);
583 g_ptr_array_unref (connection->filters);
585 if (connection->authentication_observer != NULL)
586 g_object_unref (connection->authentication_observer);
588 if (connection->auth != NULL)
589 g_object_unref (connection->auth);
591 if (connection->credentials)
592 g_object_unref (connection->credentials);
594 if (connection->stream != NULL)
596 g_object_unref (connection->stream);
597 connection->stream = NULL;
600 g_free (connection->address);
602 g_free (connection->guid);
603 g_free (connection->bus_unique_name);
605 if (connection->initialization_error != NULL)
606 g_error_free (connection->initialization_error);
608 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
610 g_hash_table_unref (connection->map_rule_to_signal_data);
611 g_hash_table_unref (connection->map_id_to_signal_data);
612 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
614 g_hash_table_unref (connection->map_id_to_ei);
615 g_hash_table_unref (connection->map_object_path_to_eo);
616 g_hash_table_unref (connection->map_id_to_es);
617 g_hash_table_unref (connection->map_object_path_to_es);
619 g_main_context_unref (connection->main_context_at_construction);
621 g_free (connection->machine_id);
623 g_mutex_clear (&connection->init_lock);
624 g_mutex_clear (&connection->lock);
626 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
630 g_dbus_connection_get_property (GObject *object,
635 GDBusConnection *connection = G_DBUS_CONNECTION (object);
640 g_value_set_object (value, g_dbus_connection_get_stream (connection));
644 g_value_set_string (value, g_dbus_connection_get_guid (connection));
647 case PROP_UNIQUE_NAME:
648 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
652 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
655 case PROP_EXIT_ON_CLOSE:
656 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
659 case PROP_CAPABILITY_FLAGS:
660 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
664 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
670 g_dbus_connection_set_property (GObject *object,
675 GDBusConnection *connection = G_DBUS_CONNECTION (object);
680 connection->stream = g_value_dup_object (value);
684 connection->guid = g_value_dup_string (value);
688 connection->address = g_value_dup_string (value);
692 connection->flags = g_value_get_flags (value);
695 case PROP_EXIT_ON_CLOSE:
696 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
699 case PROP_AUTHENTICATION_OBSERVER:
700 connection->authentication_observer = g_value_dup_object (value);
704 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
710 g_dbus_connection_real_closed (GDBusConnection *connection,
711 gboolean remote_peer_vanished,
714 gint flags = g_atomic_int_get (&connection->atomic_flags);
716 /* Because atomic int access is a memory barrier, we can safely read
717 * initialization_error without a lock, as long as we do it afterwards.
719 if (remote_peer_vanished && connection->exit_on_close &&
720 (flags & FLAG_INITIALIZED) != 0 &&
721 connection->initialization_error == NULL)
725 g_print ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
728 g_quark_to_string (error->domain), error->code);
732 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
739 g_dbus_connection_class_init (GDBusConnectionClass *klass)
741 GObjectClass *gobject_class;
743 gobject_class = G_OBJECT_CLASS (klass);
745 gobject_class->finalize = g_dbus_connection_finalize;
746 gobject_class->dispose = g_dbus_connection_dispose;
747 gobject_class->set_property = g_dbus_connection_set_property;
748 gobject_class->get_property = g_dbus_connection_get_property;
750 klass->closed = g_dbus_connection_real_closed;
753 * GDBusConnection:stream:
755 * The underlying #GIOStream used for I/O.
757 * If this is passed on construction and is a #GSocketConnection,
758 * then the corresponding #GSocket will be put into non-blocking mode.
760 * While the #GDBusConnection is active, it will interact with this
761 * stream from a worker thread, so it is not safe to interact with
762 * the stream directly.
766 g_object_class_install_property (gobject_class,
768 g_param_spec_object ("stream",
770 P_("The underlying streams used for I/O"),
774 G_PARAM_CONSTRUCT_ONLY |
775 G_PARAM_STATIC_NAME |
776 G_PARAM_STATIC_BLURB |
777 G_PARAM_STATIC_NICK));
780 * GDBusConnection:address:
782 * A D-Bus address specifying potential endpoints that can be used
783 * when establishing the connection.
787 g_object_class_install_property (gobject_class,
789 g_param_spec_string ("address",
791 P_("D-Bus address specifying potential socket endpoints"),
794 G_PARAM_CONSTRUCT_ONLY |
795 G_PARAM_STATIC_NAME |
796 G_PARAM_STATIC_BLURB |
797 G_PARAM_STATIC_NICK));
800 * GDBusConnection:flags:
802 * Flags from the #GDBusConnectionFlags enumeration.
806 g_object_class_install_property (gobject_class,
808 g_param_spec_flags ("flags",
811 G_TYPE_DBUS_CONNECTION_FLAGS,
812 G_DBUS_CONNECTION_FLAGS_NONE,
814 G_PARAM_CONSTRUCT_ONLY |
815 G_PARAM_STATIC_NAME |
816 G_PARAM_STATIC_BLURB |
817 G_PARAM_STATIC_NICK));
820 * GDBusConnection:guid:
822 * The GUID of the peer performing the role of server when
825 * If you are constructing a #GDBusConnection and pass
826 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
827 * #GDBusConnection:flags property then you MUST also set this
828 * property to a valid guid.
830 * If you are constructing a #GDBusConnection and pass
831 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
832 * #GDBusConnection:flags property you will be able to read the GUID
833 * of the other peer here after the connection has been successfully
838 g_object_class_install_property (gobject_class,
840 g_param_spec_string ("guid",
842 P_("GUID of the server peer"),
846 G_PARAM_CONSTRUCT_ONLY |
847 G_PARAM_STATIC_NAME |
848 G_PARAM_STATIC_BLURB |
849 G_PARAM_STATIC_NICK));
852 * GDBusConnection:unique-name:
854 * The unique name as assigned by the message bus or %NULL if the
855 * connection is not open or not a message bus connection.
859 g_object_class_install_property (gobject_class,
861 g_param_spec_string ("unique-name",
863 P_("Unique name of bus connection"),
866 G_PARAM_STATIC_NAME |
867 G_PARAM_STATIC_BLURB |
868 G_PARAM_STATIC_NICK));
871 * GDBusConnection:closed:
873 * A boolean specifying whether the connection has been closed.
877 g_object_class_install_property (gobject_class,
879 g_param_spec_boolean ("closed",
881 P_("Whether the connection is closed"),
884 G_PARAM_STATIC_NAME |
885 G_PARAM_STATIC_BLURB |
886 G_PARAM_STATIC_NICK));
889 * GDBusConnection:exit-on-close:
891 * A boolean specifying whether the process will be terminated (by
892 * calling <literal>raise(SIGTERM)</literal>) if the connection
893 * is closed by the remote peer.
897 g_object_class_install_property (gobject_class,
899 g_param_spec_boolean ("exit-on-close",
901 P_("Whether the process is terminated when the connection is closed"),
905 G_PARAM_STATIC_NAME |
906 G_PARAM_STATIC_BLURB |
907 G_PARAM_STATIC_NICK));
910 * GDBusConnection:capabilities:
912 * Flags from the #GDBusCapabilityFlags enumeration
913 * representing connection features negotiated with the other peer.
917 g_object_class_install_property (gobject_class,
918 PROP_CAPABILITY_FLAGS,
919 g_param_spec_flags ("capabilities",
922 G_TYPE_DBUS_CAPABILITY_FLAGS,
923 G_DBUS_CAPABILITY_FLAGS_NONE,
925 G_PARAM_STATIC_NAME |
926 G_PARAM_STATIC_BLURB |
927 G_PARAM_STATIC_NICK));
930 * GDBusConnection:authentication-observer:
932 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
936 g_object_class_install_property (gobject_class,
937 PROP_AUTHENTICATION_OBSERVER,
938 g_param_spec_object ("authentication-observer",
939 P_("Authentication Observer"),
940 P_("Object used to assist in the authentication process"),
941 G_TYPE_DBUS_AUTH_OBSERVER,
943 G_PARAM_CONSTRUCT_ONLY |
944 G_PARAM_STATIC_NAME |
945 G_PARAM_STATIC_BLURB |
946 G_PARAM_STATIC_NICK));
949 * GDBusConnection::closed:
950 * @connection: The #GDBusConnection emitting the signal.
951 * @remote_peer_vanished: %TRUE if @connection is closed because the
952 * remote peer closed its end of the connection.
953 * @error: A #GError with more details about the event or %NULL.
955 * Emitted when the connection is closed.
957 * The cause of this event can be
960 * If g_dbus_connection_close() is called. In this case
961 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
964 * If the remote peer closes the connection. In this case
965 * @remote_peer_vanished is set to %TRUE and @error is set.
968 * If the remote peer sends invalid or malformed data. In this
969 * case @remote_peer_vanished is set to %FALSE and @error
974 * Upon receiving this signal, you should give up your reference to
975 * @connection. You are guaranteed that this signal is emitted only
980 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
981 G_TYPE_DBUS_CONNECTION,
983 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
994 g_dbus_connection_init (GDBusConnection *connection)
996 g_mutex_init (&connection->lock);
997 g_mutex_init (&connection->init_lock);
999 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
1001 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1003 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1005 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1008 (GDestroyNotify) g_ptr_array_unref);
1010 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1013 (GDestroyNotify) exported_object_free);
1015 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1018 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1021 (GDestroyNotify) exported_subtree_free);
1023 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1026 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1028 connection->filters = g_ptr_array_new ();
1032 * g_dbus_connection_get_stream:
1033 * @connection: a #GDBusConnection
1035 * Gets the underlying stream used for IO.
1037 * While the #GDBusConnection is active, it will interact with this
1038 * stream from a worker thread, so it is not safe to interact with
1039 * the stream directly.
1041 * Returns: (transfer none): the stream used for IO
1046 g_dbus_connection_get_stream (GDBusConnection *connection)
1048 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1050 /* do not use g_return_val_if_fail(), we want the memory barrier */
1051 if (!check_initialized (connection))
1054 return connection->stream;
1058 * g_dbus_connection_start_message_processing:
1059 * @connection: A #GDBusConnection.
1061 * If @connection was created with
1062 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1063 * starts processing messages. Does nothing on if @connection wasn't
1064 * created with this flag or if the method has already been called.
1069 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1071 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1073 /* do not use g_return_val_if_fail(), we want the memory barrier */
1074 if (!check_initialized (connection))
1077 g_assert (connection->worker != NULL);
1078 _g_dbus_worker_unfreeze (connection->worker);
1082 * g_dbus_connection_is_closed:
1083 * @connection: A #GDBusConnection.
1085 * Gets whether @connection is closed.
1087 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
1092 g_dbus_connection_is_closed (GDBusConnection *connection)
1094 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1095 return connection->closed;
1099 * g_dbus_connection_get_capabilities:
1100 * @connection: A #GDBusConnection.
1102 * Gets the capabilities negotiated with the remote peer
1104 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
1108 GDBusCapabilityFlags
1109 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1111 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1113 /* do not use g_return_val_if_fail(), we want the memory barrier */
1114 if (!check_initialized (connection))
1115 return G_DBUS_CAPABILITY_FLAGS_NONE;
1117 return connection->capabilities;
1120 /* ---------------------------------------------------------------------------------------------------- */
1123 flush_in_thread_func (GSimpleAsyncResult *res,
1125 GCancellable *cancellable)
1130 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1133 g_simple_async_result_take_error (res, error);
1137 * g_dbus_connection_flush:
1138 * @connection: A #GDBusConnection.
1139 * @cancellable: A #GCancellable or %NULL.
1140 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1141 * satisfied or %NULL if you don't care about the result.
1142 * @user_data: The data to pass to @callback.
1144 * Asynchronously flushes @connection, that is, writes all queued
1145 * outgoing message to the transport and then flushes the transport
1146 * (using g_output_stream_flush_async()). This is useful in programs
1147 * that wants to emit a D-Bus signal and then exit
1148 * immediately. Without flushing the connection, there is no guarantee
1149 * that the message has been sent to the networking buffers in the OS
1152 * This is an asynchronous method. When the operation is finished,
1153 * @callback will be invoked in the <link
1154 * linkend="g-main-context-push-thread-default">thread-default main
1155 * loop</link> of the thread you are calling this method from. You can
1156 * then call g_dbus_connection_flush_finish() to get the result of the
1157 * operation. See g_dbus_connection_flush_sync() for the synchronous
1163 g_dbus_connection_flush (GDBusConnection *connection,
1164 GCancellable *cancellable,
1165 GAsyncReadyCallback callback,
1168 GSimpleAsyncResult *simple;
1170 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1172 simple = g_simple_async_result_new (G_OBJECT (connection),
1175 g_dbus_connection_flush);
1176 g_simple_async_result_run_in_thread (simple,
1177 flush_in_thread_func,
1180 g_object_unref (simple);
1184 * g_dbus_connection_flush_finish:
1185 * @connection: A #GDBusConnection.
1186 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_flush().
1187 * @error: Return location for error or %NULL.
1189 * Finishes an operation started with g_dbus_connection_flush().
1191 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1196 g_dbus_connection_flush_finish (GDBusConnection *connection,
1200 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1205 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1206 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1207 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1209 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1211 if (g_simple_async_result_propagate_error (simple, error))
1221 * g_dbus_connection_flush_sync:
1222 * @connection: A #GDBusConnection.
1223 * @cancellable: A #GCancellable or %NULL.
1224 * @error: Return location for error or %NULL.
1226 * Synchronously flushes @connection. The calling thread is blocked
1227 * until this is done. See g_dbus_connection_flush() for the
1228 * asynchronous version of this method and more details about what it
1231 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1236 g_dbus_connection_flush_sync (GDBusConnection *connection,
1237 GCancellable *cancellable,
1242 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1243 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1247 /* do not use g_return_val_if_fail(), we want the memory barrier */
1248 if (!check_initialized (connection))
1251 g_assert (connection->worker != NULL);
1253 if (connection->closed)
1255 g_set_error_literal (error,
1258 _("The connection is closed"));
1262 ret = _g_dbus_worker_flush_sync (connection->worker,
1270 /* ---------------------------------------------------------------------------------------------------- */
1274 GDBusConnection *connection;
1276 gboolean remote_peer_vanished;
1280 emit_closed_data_free (EmitClosedData *data)
1282 g_object_unref (data->connection);
1283 if (data->error != NULL)
1284 g_error_free (data->error);
1289 emit_closed_in_idle (gpointer user_data)
1291 EmitClosedData *data = user_data;
1294 g_object_notify (G_OBJECT (data->connection), "closed");
1295 g_signal_emit (data->connection,
1296 signals[CLOSED_SIGNAL],
1298 data->remote_peer_vanished,
1304 /* Can be called from any thread, must hold lock */
1306 set_closed_unlocked (GDBusConnection *connection,
1307 gboolean remote_peer_vanished,
1310 GSource *idle_source;
1311 EmitClosedData *data;
1313 CONNECTION_ENSURE_LOCK (connection);
1315 g_assert (!connection->closed);
1317 connection->closed = TRUE;
1319 data = g_new0 (EmitClosedData, 1);
1320 data->connection = g_object_ref (connection);
1321 data->remote_peer_vanished = remote_peer_vanished;
1322 data->error = error != NULL ? g_error_copy (error) : NULL;
1324 idle_source = g_idle_source_new ();
1325 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1326 g_source_set_callback (idle_source,
1327 emit_closed_in_idle,
1329 (GDestroyNotify) emit_closed_data_free);
1330 g_source_attach (idle_source, connection->main_context_at_construction);
1331 g_source_unref (idle_source);
1334 /* ---------------------------------------------------------------------------------------------------- */
1337 * g_dbus_connection_close:
1338 * @connection: A #GDBusConnection.
1339 * @cancellable: A #GCancellable or %NULL.
1340 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1341 * satisfied or %NULL if you don't care about the result.
1342 * @user_data: The data to pass to @callback.
1344 * Closes @connection. Note that this never causes the process to
1345 * exit (this might only happen if the other end of a shared message
1346 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1348 * Once the connection is closed, operations such as sending a message
1349 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1350 * will not automatically flush the connection so queued messages may
1351 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1353 * If @connection is already closed, this method fails with
1354 * %G_IO_ERROR_CLOSED.
1356 * When @connection has been closed, the #GDBusConnection::closed
1357 * signal is emitted in the <link
1358 * linkend="g-main-context-push-thread-default">thread-default main
1359 * loop</link> of the thread that @connection was constructed in.
1361 * This is an asynchronous method. When the operation is finished,
1362 * @callback will be invoked in the <link
1363 * linkend="g-main-context-push-thread-default">thread-default main
1364 * loop</link> of the thread you are calling this method from. You can
1365 * then call g_dbus_connection_close_finish() to get the result of the
1366 * operation. See g_dbus_connection_close_sync() for the synchronous
1372 g_dbus_connection_close (GDBusConnection *connection,
1373 GCancellable *cancellable,
1374 GAsyncReadyCallback callback,
1377 GSimpleAsyncResult *simple;
1379 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1381 /* do not use g_return_val_if_fail(), we want the memory barrier */
1382 if (!check_initialized (connection))
1385 g_assert (connection->worker != NULL);
1387 simple = g_simple_async_result_new (G_OBJECT (connection),
1390 g_dbus_connection_close);
1391 _g_dbus_worker_close (connection->worker, cancellable, simple);
1392 g_object_unref (simple);
1396 * g_dbus_connection_close_finish:
1397 * @connection: A #GDBusConnection.
1398 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_close().
1399 * @error: Return location for error or %NULL.
1401 * Finishes an operation started with g_dbus_connection_close().
1403 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1408 g_dbus_connection_close_finish (GDBusConnection *connection,
1412 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1417 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1418 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1419 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1421 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1423 if (g_simple_async_result_propagate_error (simple, error))
1434 GAsyncResult *result;
1438 sync_close_cb (GObject *source_object,
1442 SyncCloseData *data = user_data;
1444 data->result = g_object_ref (res);
1445 g_main_loop_quit (data->loop);
1449 * g_dbus_connection_close_sync:
1450 * @connection: A #GDBusConnection.
1451 * @cancellable: A #GCancellable or %NULL.
1452 * @error: Return location for error or %NULL.
1454 * Synchronously closees @connection. The calling thread is blocked
1455 * until this is done. See g_dbus_connection_close() for the
1456 * asynchronous version of this method and more details about what it
1459 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1464 g_dbus_connection_close_sync (GDBusConnection *connection,
1465 GCancellable *cancellable,
1470 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1471 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1475 CONNECTION_LOCK (connection);
1476 if (!connection->closed)
1478 GMainContext *context;
1481 context = g_main_context_new ();
1482 g_main_context_push_thread_default (context);
1483 data.loop = g_main_loop_new (context, TRUE);
1486 CONNECTION_UNLOCK (connection);
1487 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1488 g_main_loop_run (data.loop);
1489 ret = g_dbus_connection_close_finish (connection, data.result, error);
1490 CONNECTION_LOCK (connection);
1492 g_object_unref (data.result);
1493 g_main_loop_unref (data.loop);
1494 g_main_context_pop_thread_default (context);
1495 g_main_context_unref (context);
1499 g_set_error_literal (error,
1502 _("The connection is closed"));
1504 CONNECTION_UNLOCK (connection);
1509 /* ---------------------------------------------------------------------------------------------------- */
1512 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1513 GDBusMessage *message,
1514 GDBusSendMessageFlags flags,
1515 volatile guint32 *out_serial,
1520 guint32 serial_to_use;
1523 CONNECTION_ENSURE_LOCK (connection);
1525 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1526 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1528 /* TODO: check all necessary headers are present */
1533 if (out_serial != NULL)
1536 /* If we're in initable_init(), don't check for being initialized, to avoid
1537 * chicken-and-egg problems. initable_init() is responsible for setting up
1538 * our prerequisites (mainly connection->worker), and only calling us
1539 * from its own thread (so no memory barrier is needed).
1541 * In the case where we're not initializing, do not use
1542 * g_return_val_if_fail() - we want the memory barrier.
1544 if ((flags & SEND_MESSAGE_FLAGS_INITIALIZING) == 0 &&
1545 !check_initialized (connection))
1548 if (connection->closed)
1550 g_set_error_literal (error,
1553 _("The connection is closed"));
1557 blob = g_dbus_message_to_blob (message,
1559 connection->capabilities,
1564 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1565 serial_to_use = g_dbus_message_get_serial (message);
1567 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1572 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1575 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1578 g_assert_not_reached ();
1583 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1584 blob_size, serial_to_use, connection);
1585 g_printerr ("----\n");
1586 hexdump (blob, blob_size);
1587 g_printerr ("----\n");
1590 /* TODO: use connection->auth to encode the blob */
1592 if (out_serial != NULL)
1593 *out_serial = serial_to_use;
1595 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
1596 g_dbus_message_set_serial (message, serial_to_use);
1598 g_dbus_message_lock (message);
1599 _g_dbus_worker_send_message (connection->worker,
1603 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1614 * g_dbus_connection_send_message:
1615 * @connection: A #GDBusConnection.
1616 * @message: A #GDBusMessage
1617 * @flags: Flags affecting how the message is sent.
1618 * @out_serial: (out) (allow-none): Return location for serial number assigned
1619 * to @message when sending it or %NULL.
1620 * @error: Return location for error or %NULL.
1622 * Asynchronously sends @message to the peer represented by @connection.
1624 * Unless @flags contain the
1625 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1626 * will be assigned by @connection and set on @message via
1627 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1628 * serial number used will be written to this location prior to
1629 * submitting the message to the underlying transport.
1631 * If @connection is closed then the operation will fail with
1632 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1633 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1635 * See <xref linkend="gdbus-server"/> and <xref
1636 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1637 * low-level API to send and receive UNIX file descriptors.
1639 * Note that @message must be unlocked, unless @flags contain the
1640 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1642 * Returns: %TRUE if the message was well-formed and queued for
1643 * transmission, %FALSE if @error is set.
1648 g_dbus_connection_send_message (GDBusConnection *connection,
1649 GDBusMessage *message,
1650 GDBusSendMessageFlags flags,
1651 volatile guint32 *out_serial,
1656 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1657 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1658 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1659 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1661 CONNECTION_LOCK (connection);
1662 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1663 CONNECTION_UNLOCK (connection);
1667 /* ---------------------------------------------------------------------------------------------------- */
1671 volatile gint ref_count;
1672 GDBusConnection *connection;
1674 GSimpleAsyncResult *simple;
1676 GMainContext *main_context;
1678 GCancellable *cancellable;
1680 gulong cancellable_handler_id;
1682 GSource *timeout_source;
1687 static SendMessageData *
1688 send_message_data_ref (SendMessageData *data)
1690 g_atomic_int_inc (&data->ref_count);
1695 send_message_data_unref (SendMessageData *data)
1697 if (g_atomic_int_dec_and_test (&data->ref_count))
1699 g_assert (data->timeout_source == NULL);
1700 g_assert (data->simple == NULL);
1701 g_assert (data->cancellable_handler_id == 0);
1702 g_object_unref (data->connection);
1703 if (data->cancellable != NULL)
1704 g_object_unref (data->cancellable);
1705 g_main_context_unref (data->main_context);
1710 /* ---------------------------------------------------------------------------------------------------- */
1712 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1714 send_message_with_reply_deliver (SendMessageData *data, gboolean remove)
1716 CONNECTION_ENSURE_LOCK (data->connection);
1718 g_assert (!data->delivered);
1720 data->delivered = TRUE;
1722 g_simple_async_result_complete_in_idle (data->simple);
1723 g_object_unref (data->simple);
1724 data->simple = NULL;
1726 if (data->timeout_source != NULL)
1728 g_source_destroy (data->timeout_source);
1729 data->timeout_source = NULL;
1731 if (data->cancellable_handler_id > 0)
1733 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1734 data->cancellable_handler_id = 0;
1739 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
1740 GUINT_TO_POINTER (data->serial)));
1743 send_message_data_unref (data);
1746 /* ---------------------------------------------------------------------------------------------------- */
1748 /* must hold lock */
1750 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1751 GDBusMessage *reply)
1753 if (data->delivered)
1756 g_simple_async_result_set_op_res_gpointer (data->simple,
1757 g_object_ref (reply),
1760 send_message_with_reply_deliver (data, TRUE);
1766 /* ---------------------------------------------------------------------------------------------------- */
1769 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1771 SendMessageData *data = user_data;
1773 CONNECTION_LOCK (data->connection);
1774 if (data->delivered)
1777 g_simple_async_result_set_error (data->simple,
1779 G_IO_ERROR_CANCELLED,
1780 _("Operation was cancelled"));
1782 send_message_with_reply_deliver (data, TRUE);
1785 CONNECTION_UNLOCK (data->connection);
1789 /* Can be called from any thread with or without lock held */
1791 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1794 SendMessageData *data = user_data;
1795 GSource *idle_source;
1797 /* postpone cancellation to idle handler since we may be called directly
1798 * via g_cancellable_connect() (e.g. holding lock)
1800 idle_source = g_idle_source_new ();
1801 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1802 g_source_set_callback (idle_source,
1803 send_message_with_reply_cancelled_idle_cb,
1804 send_message_data_ref (data),
1805 (GDestroyNotify) send_message_data_unref);
1806 g_source_attach (idle_source, data->main_context);
1807 g_source_unref (idle_source);
1810 /* ---------------------------------------------------------------------------------------------------- */
1813 send_message_with_reply_timeout_cb (gpointer user_data)
1815 SendMessageData *data = user_data;
1817 CONNECTION_LOCK (data->connection);
1818 if (data->delivered)
1821 g_simple_async_result_set_error (data->simple,
1823 G_IO_ERROR_TIMED_OUT,
1824 _("Timeout was reached"));
1826 send_message_with_reply_deliver (data, TRUE);
1829 CONNECTION_UNLOCK (data->connection);
1834 /* ---------------------------------------------------------------------------------------------------- */
1837 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1838 GDBusMessage *message,
1839 GDBusSendMessageFlags flags,
1841 volatile guint32 *out_serial,
1842 GCancellable *cancellable,
1843 GAsyncReadyCallback callback,
1846 GSimpleAsyncResult *simple;
1847 SendMessageData *data;
1849 volatile guint32 serial;
1853 if (out_serial == NULL)
1854 out_serial = &serial;
1856 if (timeout_msec == -1)
1857 timeout_msec = 25 * 1000;
1859 simple = g_simple_async_result_new (G_OBJECT (connection),
1862 g_dbus_connection_send_message_with_reply);
1864 if (g_cancellable_is_cancelled (cancellable))
1866 g_simple_async_result_set_error (simple,
1868 G_IO_ERROR_CANCELLED,
1869 _("Operation was cancelled"));
1870 g_simple_async_result_complete_in_idle (simple);
1871 g_object_unref (simple);
1875 if (connection->closed)
1877 g_simple_async_result_set_error (simple,
1880 _("The connection is closed"));
1881 g_simple_async_result_complete_in_idle (simple);
1882 g_object_unref (simple);
1887 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1889 g_simple_async_result_take_error (simple, error);
1890 g_simple_async_result_complete_in_idle (simple);
1891 g_object_unref (simple);
1895 data = g_new0 (SendMessageData, 1);
1896 data->ref_count = 1;
1897 data->connection = g_object_ref (connection);
1898 data->simple = simple;
1899 data->serial = *out_serial;
1900 data->main_context = g_main_context_ref_thread_default ();
1902 if (cancellable != NULL)
1904 data->cancellable = g_object_ref (cancellable);
1905 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1906 G_CALLBACK (send_message_with_reply_cancelled_cb),
1907 send_message_data_ref (data),
1908 (GDestroyNotify) send_message_data_unref);
1909 g_object_set_data_full (G_OBJECT (simple),
1911 g_object_ref (cancellable),
1912 (GDestroyNotify) g_object_unref);
1915 if (timeout_msec != G_MAXINT)
1917 data->timeout_source = g_timeout_source_new (timeout_msec);
1918 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1919 g_source_set_callback (data->timeout_source,
1920 send_message_with_reply_timeout_cb,
1921 send_message_data_ref (data),
1922 (GDestroyNotify) send_message_data_unref);
1923 g_source_attach (data->timeout_source, data->main_context);
1924 g_source_unref (data->timeout_source);
1927 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
1928 GUINT_TO_POINTER (*out_serial),
1936 * g_dbus_connection_send_message_with_reply:
1937 * @connection: A #GDBusConnection.
1938 * @message: A #GDBusMessage.
1939 * @flags: Flags affecting how the message is sent.
1940 * @timeout_msec: The timeout in milliseconds, -1 to use the default
1941 * timeout or %G_MAXINT for no timeout.
1942 * @out_serial: (out) (allow-none): Return location for serial number assigned
1943 * to @message when sending it or %NULL.
1944 * @cancellable: A #GCancellable or %NULL.
1945 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1946 * satisfied or %NULL if you don't care about the result.
1947 * @user_data: The data to pass to @callback.
1949 * Asynchronously sends @message to the peer represented by @connection.
1951 * Unless @flags contain the
1952 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1953 * will be assigned by @connection and set on @message via
1954 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1955 * serial number used will be written to this location prior to
1956 * submitting the message to the underlying transport.
1958 * If @connection is closed then the operation will fail with
1959 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1960 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1961 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1963 * This is an asynchronous method. When the operation is finished, @callback will be invoked
1964 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
1965 * of the thread you are calling this method from. You can then call
1966 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1967 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
1969 * Note that @message must be unlocked, unless @flags contain the
1970 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1972 * See <xref linkend="gdbus-server"/> and <xref
1973 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1974 * low-level API to send and receive UNIX file descriptors.
1979 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
1980 GDBusMessage *message,
1981 GDBusSendMessageFlags flags,
1983 volatile guint32 *out_serial,
1984 GCancellable *cancellable,
1985 GAsyncReadyCallback callback,
1988 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1989 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1990 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
1991 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
1993 CONNECTION_LOCK (connection);
1994 g_dbus_connection_send_message_with_reply_unlocked (connection,
2002 CONNECTION_UNLOCK (connection);
2006 * g_dbus_connection_send_message_with_reply_finish:
2007 * @connection: a #GDBusConnection
2008 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
2009 * @error: Return location for error or %NULL.
2011 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2013 * Note that @error is only set if a local in-process error
2014 * occurred. That is to say that the returned #GDBusMessage object may
2015 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2016 * g_dbus_message_to_gerror() to transcode this to a #GError.
2018 * See <xref linkend="gdbus-server"/> and <xref
2019 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2020 * low-level API to send and receive UNIX file descriptors.
2022 * Returns: (transfer full): A locked #GDBusMessage or %NULL if @error is set.
2027 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2031 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2032 GDBusMessage *reply;
2033 GCancellable *cancellable;
2035 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2036 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2040 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
2042 if (g_simple_async_result_propagate_error (simple, error))
2045 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
2046 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
2047 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
2049 g_object_unref (reply);
2051 g_set_error_literal (error,
2053 G_IO_ERROR_CANCELLED,
2054 _("Operation was cancelled"));
2060 /* ---------------------------------------------------------------------------------------------------- */
2065 GMainContext *context;
2067 } SendMessageSyncData;
2070 send_message_with_reply_sync_cb (GDBusConnection *connection,
2074 SendMessageSyncData *data = user_data;
2075 data->res = g_object_ref (res);
2076 g_main_loop_quit (data->loop);
2080 * g_dbus_connection_send_message_with_reply_sync:
2081 * @connection: A #GDBusConnection.
2082 * @message: A #GDBusMessage.
2083 * @flags: Flags affecting how the message is sent.
2084 * @timeout_msec: The timeout in milliseconds, -1 to use the default
2085 * timeout or %G_MAXINT for no timeout.
2086 * @out_serial: (out) (allow-none): Return location for serial number assigned
2087 * to @message when sending it or %NULL.
2088 * @cancellable: A #GCancellable or %NULL.
2089 * @error: Return location for error or %NULL.
2091 * Synchronously sends @message to the peer represented by @connection
2092 * and blocks the calling thread until a reply is received or the
2093 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2094 * for the asynchronous version of this method.
2096 * Unless @flags contain the
2097 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2098 * will be assigned by @connection and set on @message via
2099 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2100 * serial number used will be written to this location prior to
2101 * submitting the message to the underlying transport.
2103 * If @connection is closed then the operation will fail with
2104 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2105 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2106 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2108 * Note that @error is only set if a local in-process error
2109 * occurred. That is to say that the returned #GDBusMessage object may
2110 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2111 * g_dbus_message_to_gerror() to transcode this to a #GError.
2113 * See <xref linkend="gdbus-server"/> and <xref
2114 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2115 * low-level API to send and receive UNIX file descriptors.
2117 * Note that @message must be unlocked, unless @flags contain the
2118 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2120 * Returns: (transfer full): A locked #GDBusMessage that is the reply to @message or %NULL if @error is set.
2125 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2126 GDBusMessage *message,
2127 GDBusSendMessageFlags flags,
2129 volatile guint32 *out_serial,
2130 GCancellable *cancellable,
2133 SendMessageSyncData *data;
2134 GDBusMessage *reply;
2136 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2137 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2138 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2139 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2140 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2142 data = g_new0 (SendMessageSyncData, 1);
2143 data->context = g_main_context_new ();
2144 data->loop = g_main_loop_new (data->context, FALSE);
2146 g_main_context_push_thread_default (data->context);
2148 g_dbus_connection_send_message_with_reply (connection,
2154 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2156 g_main_loop_run (data->loop);
2157 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2161 g_main_context_pop_thread_default (data->context);
2163 g_main_context_unref (data->context);
2164 g_main_loop_unref (data->loop);
2165 g_object_unref (data->res);
2171 /* ---------------------------------------------------------------------------------------------------- */
2175 GDBusMessageFilterFunction func;
2182 GDBusMessageFilterFunction filter_function;
2184 GDestroyNotify user_data_free_func;
2187 /* Called in worker's thread - we must not block */
2189 on_worker_message_received (GDBusWorker *worker,
2190 GDBusMessage *message,
2193 GDBusConnection *connection;
2194 FilterCallback *filters;
2199 G_LOCK (message_bus_lock);
2200 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2203 G_UNLOCK (message_bus_lock);
2206 connection = G_DBUS_CONNECTION (user_data);
2207 g_object_ref (connection);
2208 G_UNLOCK (message_bus_lock);
2210 //g_debug ("in on_worker_message_received");
2212 g_object_ref (message);
2213 g_dbus_message_lock (message);
2215 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2217 /* First collect the set of callback functions */
2218 CONNECTION_LOCK (connection);
2219 num_filters = connection->filters->len;
2220 filters = g_new0 (FilterCallback, num_filters);
2221 for (n = 0; n < num_filters; n++)
2223 FilterData *data = connection->filters->pdata[n];
2224 filters[n].func = data->filter_function;
2225 filters[n].user_data = data->user_data;
2227 CONNECTION_UNLOCK (connection);
2229 /* then call the filters in order (without holding the lock) */
2230 for (n = 0; n < num_filters; n++)
2232 message = filters[n].func (connection,
2235 filters[n].user_data);
2236 if (message == NULL)
2238 g_dbus_message_lock (message);
2241 /* Standard dispatch unless the filter ate the message - no need to
2242 * do anything if the message was altered
2244 if (message != NULL)
2246 GDBusMessageType message_type;
2248 message_type = g_dbus_message_get_message_type (message);
2249 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2251 guint32 reply_serial;
2252 SendMessageData *send_message_data;
2254 reply_serial = g_dbus_message_get_reply_serial (message);
2255 CONNECTION_LOCK (connection);
2256 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2257 GUINT_TO_POINTER (reply_serial));
2258 if (send_message_data != NULL)
2260 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2261 send_message_data_deliver_reply_unlocked (send_message_data, message);
2265 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2267 CONNECTION_UNLOCK (connection);
2269 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2271 CONNECTION_LOCK (connection);
2272 distribute_signals (connection, message);
2273 CONNECTION_UNLOCK (connection);
2275 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2277 CONNECTION_LOCK (connection);
2278 distribute_method_call (connection, message);
2279 CONNECTION_UNLOCK (connection);
2283 if (message != NULL)
2284 g_object_unref (message);
2285 g_object_unref (connection);
2289 /* Called in worker's thread */
2290 static GDBusMessage *
2291 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2292 GDBusMessage *message,
2295 GDBusConnection *connection;
2296 FilterCallback *filters;
2301 G_LOCK (message_bus_lock);
2302 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2305 G_UNLOCK (message_bus_lock);
2308 connection = G_DBUS_CONNECTION (user_data);
2309 g_object_ref (connection);
2310 G_UNLOCK (message_bus_lock);
2312 //g_debug ("in on_worker_message_about_to_be_sent");
2314 /* First collect the set of callback functions */
2315 CONNECTION_LOCK (connection);
2316 num_filters = connection->filters->len;
2317 filters = g_new0 (FilterCallback, num_filters);
2318 for (n = 0; n < num_filters; n++)
2320 FilterData *data = connection->filters->pdata[n];
2321 filters[n].func = data->filter_function;
2322 filters[n].user_data = data->user_data;
2324 CONNECTION_UNLOCK (connection);
2326 /* then call the filters in order (without holding the lock) */
2327 for (n = 0; n < num_filters; n++)
2329 g_dbus_message_lock (message);
2330 message = filters[n].func (connection,
2333 filters[n].user_data);
2334 if (message == NULL)
2338 g_object_unref (connection);
2344 /* called with connection lock held */
2346 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2348 SendMessageData *data = value;
2350 if (data->delivered)
2353 g_simple_async_result_set_error (data->simple,
2356 _("The connection is closed"));
2358 /* Ask send_message_with_reply_deliver not to remove the element from the
2359 * hash table - we're in the middle of a foreach; that would be unsafe.
2360 * Instead, return TRUE from this function so that it gets removed safely.
2362 send_message_with_reply_deliver (data, FALSE);
2366 /* Called in worker's thread - we must not block */
2368 on_worker_closed (GDBusWorker *worker,
2369 gboolean remote_peer_vanished,
2373 GDBusConnection *connection;
2376 G_LOCK (message_bus_lock);
2377 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2380 G_UNLOCK (message_bus_lock);
2383 connection = G_DBUS_CONNECTION (user_data);
2384 g_object_ref (connection);
2385 G_UNLOCK (message_bus_lock);
2387 //g_debug ("in on_worker_closed: %s", error->message);
2389 CONNECTION_LOCK (connection);
2390 if (!connection->closed)
2392 g_hash_table_foreach_remove (connection->map_method_serial_to_send_message_data, cancel_method_on_close, NULL);
2393 set_closed_unlocked (connection, remote_peer_vanished, error);
2395 CONNECTION_UNLOCK (connection);
2397 g_object_unref (connection);
2400 /* ---------------------------------------------------------------------------------------------------- */
2402 /* Determines the biggest set of capabilities we can support on this connection */
2403 static GDBusCapabilityFlags
2404 get_offered_capabilities_max (GDBusConnection *connection)
2406 GDBusCapabilityFlags ret;
2407 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2409 if (G_IS_UNIX_CONNECTION (connection->stream))
2410 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2416 initable_init (GInitable *initable,
2417 GCancellable *cancellable,
2420 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2423 /* This method needs to be idempotent to work with the singleton
2424 * pattern. See the docs for g_initable_init(). We implement this by
2427 * Unfortunately we can't use the main lock since the on_worker_*()
2428 * callbacks above needs the lock during initialization (for message
2429 * bus connections we do a synchronous Hello() call on the bus).
2431 g_mutex_lock (&connection->init_lock);
2435 /* Make this a no-op if we're already initialized (successfully or
2438 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
2440 ret = (connection->initialization_error == NULL);
2444 /* Because of init_lock, we can't get here twice in different threads */
2445 g_assert (connection->initialization_error == NULL);
2447 /* The user can pass multiple (but mutally exclusive) construct
2450 * - stream (of type GIOStream)
2451 * - address (of type gchar*)
2453 * At the end of the day we end up with a non-NULL GIOStream
2454 * object in connection->stream.
2456 if (connection->address != NULL)
2458 g_assert (connection->stream == NULL);
2460 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2461 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2463 g_set_error_literal (error,
2465 G_IO_ERROR_INVALID_ARGUMENT,
2466 _("Unsupported flags encountered when constructing a client-side connection"));
2470 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2471 NULL, /* TODO: out_guid */
2473 &connection->initialization_error);
2474 if (connection->stream == NULL)
2477 else if (connection->stream != NULL)
2483 g_assert_not_reached ();
2486 /* Authenticate the connection */
2487 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2489 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2490 g_assert (connection->guid != NULL);
2491 connection->auth = _g_dbus_auth_new (connection->stream);
2492 if (!_g_dbus_auth_run_server (connection->auth,
2493 connection->authentication_observer,
2495 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2496 get_offered_capabilities_max (connection),
2497 &connection->capabilities,
2498 &connection->credentials,
2500 &connection->initialization_error))
2503 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2505 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2506 g_assert (connection->guid == NULL);
2507 connection->auth = _g_dbus_auth_new (connection->stream);
2508 connection->guid = _g_dbus_auth_run_client (connection->auth,
2509 get_offered_capabilities_max (connection),
2510 &connection->capabilities,
2512 &connection->initialization_error);
2513 if (connection->guid == NULL)
2517 if (connection->authentication_observer != NULL)
2519 g_object_unref (connection->authentication_observer);
2520 connection->authentication_observer = NULL;
2523 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2525 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2528 /* We want all IO operations to be non-blocking since they happen in
2529 * the worker thread which is shared by _all_ connections.
2531 if (G_IS_SOCKET_CONNECTION (connection->stream))
2533 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2537 G_LOCK (message_bus_lock);
2538 if (alive_connections == NULL)
2539 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2540 g_hash_table_insert (alive_connections, connection, connection);
2541 G_UNLOCK (message_bus_lock);
2543 connection->worker = _g_dbus_worker_new (connection->stream,
2544 connection->capabilities,
2545 (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING),
2546 on_worker_message_received,
2547 on_worker_message_about_to_be_sent,
2551 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2552 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2554 GVariant *hello_result;
2556 /* we could lift this restriction by adding code in gdbusprivate.c */
2557 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2559 g_set_error_literal (&connection->initialization_error,
2562 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2566 hello_result = g_dbus_connection_call_sync (connection,
2567 "org.freedesktop.DBus", /* name */
2568 "/org/freedesktop/DBus", /* path */
2569 "org.freedesktop.DBus", /* interface */
2571 NULL, /* parameters */
2572 G_VARIANT_TYPE ("(s)"),
2573 CALL_FLAGS_INITIALIZING,
2575 NULL, /* TODO: cancellable */
2576 &connection->initialization_error);
2577 if (hello_result == NULL)
2580 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2581 g_variant_unref (hello_result);
2582 //g_debug ("unique name is `%s'", connection->bus_unique_name);
2589 g_assert (connection->initialization_error != NULL);
2590 g_propagate_error (error, g_error_copy (connection->initialization_error));
2593 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
2594 g_mutex_unlock (&connection->init_lock);
2600 initable_iface_init (GInitableIface *initable_iface)
2602 initable_iface->init = initable_init;
2605 /* ---------------------------------------------------------------------------------------------------- */
2608 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2613 /* ---------------------------------------------------------------------------------------------------- */
2616 * g_dbus_connection_new:
2617 * @stream: A #GIOStream.
2618 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2619 * @flags: Flags describing how to make the connection.
2620 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2621 * @cancellable: A #GCancellable or %NULL.
2622 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2623 * @user_data: The data to pass to @callback.
2625 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2626 * with the end represented by @stream.
2628 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2629 * will be put into non-blocking mode.
2631 * The D-Bus connection will interact with @stream from a worker thread.
2632 * As a result, the caller should not interact with @stream after this
2633 * method has been called, except by calling g_object_unref() on it.
2635 * If @observer is not %NULL it may be used to control the
2636 * authentication process.
2638 * When the operation is finished, @callback will be invoked. You can
2639 * then call g_dbus_connection_new_finish() to get the result of the
2642 * This is a asynchronous failable constructor. See
2643 * g_dbus_connection_new_sync() for the synchronous
2649 g_dbus_connection_new (GIOStream *stream,
2651 GDBusConnectionFlags flags,
2652 GDBusAuthObserver *observer,
2653 GCancellable *cancellable,
2654 GAsyncReadyCallback callback,
2657 g_return_if_fail (G_IS_IO_STREAM (stream));
2658 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2666 "authentication-observer", observer,
2671 * g_dbus_connection_new_finish:
2672 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2673 * @error: Return location for error or %NULL.
2675 * Finishes an operation started with g_dbus_connection_new().
2677 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2682 g_dbus_connection_new_finish (GAsyncResult *res,
2686 GObject *source_object;
2688 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2689 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2691 source_object = g_async_result_get_source_object (res);
2692 g_assert (source_object != NULL);
2693 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2696 g_object_unref (source_object);
2698 return G_DBUS_CONNECTION (object);
2704 * g_dbus_connection_new_sync:
2705 * @stream: A #GIOStream.
2706 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2707 * @flags: Flags describing how to make the connection.
2708 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2709 * @cancellable: A #GCancellable or %NULL.
2710 * @error: Return location for error or %NULL.
2712 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2713 * with the end represented by @stream.
2715 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2716 * will be put into non-blocking mode.
2718 * The D-Bus connection will interact with @stream from a worker thread.
2719 * As a result, the caller should not interact with @stream after this
2720 * method has been called, except by calling g_object_unref() on it.
2722 * If @observer is not %NULL it may be used to control the
2723 * authentication process.
2725 * This is a synchronous failable constructor. See
2726 * g_dbus_connection_new() for the asynchronous version.
2728 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2733 g_dbus_connection_new_sync (GIOStream *stream,
2735 GDBusConnectionFlags flags,
2736 GDBusAuthObserver *observer,
2737 GCancellable *cancellable,
2740 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2741 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2742 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2748 "authentication-observer", observer,
2752 /* ---------------------------------------------------------------------------------------------------- */
2755 * g_dbus_connection_new_for_address:
2756 * @address: A D-Bus address.
2757 * @flags: Flags describing how to make the connection.
2758 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2759 * @cancellable: A #GCancellable or %NULL.
2760 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2761 * @user_data: The data to pass to @callback.
2763 * Asynchronously connects and sets up a D-Bus client connection for
2764 * exchanging D-Bus messages with an endpoint specified by @address
2765 * which must be in the D-Bus address format.
2767 * This constructor can only be used to initiate client-side
2768 * connections - use g_dbus_connection_new() if you need to act as the
2769 * server. In particular, @flags cannot contain the
2770 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2771 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2773 * When the operation is finished, @callback will be invoked. You can
2774 * then call g_dbus_connection_new_finish() to get the result of the
2777 * If @observer is not %NULL it may be used to control the
2778 * authentication process.
2780 * This is a asynchronous failable constructor. See
2781 * g_dbus_connection_new_for_address_sync() for the synchronous
2787 g_dbus_connection_new_for_address (const gchar *address,
2788 GDBusConnectionFlags flags,
2789 GDBusAuthObserver *observer,
2790 GCancellable *cancellable,
2791 GAsyncReadyCallback callback,
2794 g_return_if_fail (address != NULL);
2795 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2802 "authentication-observer", observer,
2807 * g_dbus_connection_new_for_address_finish:
2808 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2809 * @error: Return location for error or %NULL.
2811 * Finishes an operation started with g_dbus_connection_new_for_address().
2813 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2818 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2822 GObject *source_object;
2824 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2825 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2827 source_object = g_async_result_get_source_object (res);
2828 g_assert (source_object != NULL);
2829 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2832 g_object_unref (source_object);
2834 return G_DBUS_CONNECTION (object);
2840 * g_dbus_connection_new_for_address_sync:
2841 * @address: A D-Bus address.
2842 * @flags: Flags describing how to make the connection.
2843 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2844 * @cancellable: A #GCancellable or %NULL.
2845 * @error: Return location for error or %NULL.
2847 * Synchronously connects and sets up a D-Bus client connection for
2848 * exchanging D-Bus messages with an endpoint specified by @address
2849 * which must be in the D-Bus address format.
2851 * This constructor can only be used to initiate client-side
2852 * connections - use g_dbus_connection_new_sync() if you need to act
2853 * as the server. In particular, @flags cannot contain the
2854 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2855 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2857 * This is a synchronous failable constructor. See
2858 * g_dbus_connection_new_for_address() for the asynchronous version.
2860 * If @observer is not %NULL it may be used to control the
2861 * authentication process.
2863 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2868 g_dbus_connection_new_for_address_sync (const gchar *address,
2869 GDBusConnectionFlags flags,
2870 GDBusAuthObserver *observer,
2871 GCancellable *cancellable,
2874 g_return_val_if_fail (address != NULL, NULL);
2875 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2876 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2881 "authentication-observer", observer,
2885 /* ---------------------------------------------------------------------------------------------------- */
2888 * g_dbus_connection_set_exit_on_close:
2889 * @connection: A #GDBusConnection.
2890 * @exit_on_close: Whether the process should be terminated
2891 * when @connection is closed by the remote peer.
2893 * Sets whether the process should be terminated when @connection is
2894 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2897 * Note that this function should be used with care. Most modern UNIX
2898 * desktops tie the notion of a user session the session bus, and expect
2899 * all of a users applications to quit when their bus connection goes away.
2900 * If you are setting @exit_on_close to %FALSE for the shared session
2901 * bus connection, you should make sure that your application exits
2902 * when the user session ends.
2907 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2908 gboolean exit_on_close)
2910 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2911 connection->exit_on_close = exit_on_close;
2915 * g_dbus_connection_get_exit_on_close:
2916 * @connection: A #GDBusConnection.
2918 * Gets whether the process is terminated when @connection is
2919 * closed by the remote peer. See
2920 * #GDBusConnection:exit-on-close for more details.
2922 * Returns: Whether the process is terminated when @connection is
2923 * closed by the remote peer.
2928 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2930 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2931 return connection->exit_on_close;
2935 * g_dbus_connection_get_guid:
2936 * @connection: A #GDBusConnection.
2938 * The GUID of the peer performing the role of server when
2939 * authenticating. See #GDBusConnection:guid for more details.
2941 * Returns: The GUID. Do not free this string, it is owned by
2947 g_dbus_connection_get_guid (GDBusConnection *connection)
2949 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2950 return connection->guid;
2954 * g_dbus_connection_get_unique_name:
2955 * @connection: A #GDBusConnection.
2957 * Gets the unique name of @connection as assigned by the message
2958 * bus. This can also be used to figure out if @connection is a
2959 * message bus connection.
2961 * Returns: The unique name or %NULL if @connection is not a message
2962 * bus connection. Do not free this string, it is owned by
2968 g_dbus_connection_get_unique_name (GDBusConnection *connection)
2970 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2972 /* do not use g_return_val_if_fail(), we want the memory barrier */
2973 if (!check_initialized (connection))
2976 return connection->bus_unique_name;
2980 * g_dbus_connection_get_peer_credentials:
2981 * @connection: A #GDBusConnection.
2983 * Gets the credentials of the authenticated peer. This will always
2984 * return %NULL unless @connection acted as a server
2985 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
2986 * when set up and the client passed credentials as part of the
2987 * authentication process.
2989 * In a message bus setup, the message bus is always the server and
2990 * each application is a client. So this method will always return
2991 * %NULL for message bus clients.
2993 * Returns: (transfer none): A #GCredentials or %NULL if not available. Do not free
2994 * this object, it is owned by @connection.
2999 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3001 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3003 /* do not use g_return_val_if_fail(), we want the memory barrier */
3004 if (!check_initialized (connection))
3007 return connection->credentials;
3010 /* ---------------------------------------------------------------------------------------------------- */
3012 static guint _global_filter_id = 1;
3015 * g_dbus_connection_add_filter:
3016 * @connection: A #GDBusConnection.
3017 * @filter_function: A filter function.
3018 * @user_data: User data to pass to @filter_function.
3019 * @user_data_free_func: Function to free @user_data with when filter
3020 * is removed or %NULL.
3022 * Adds a message filter. Filters are handlers that are run on all
3023 * incoming and outgoing messages, prior to standard dispatch. Filters
3024 * are run in the order that they were added. The same handler can be
3025 * added as a filter more than once, in which case it will be run more
3026 * than once. Filters added during a filter callback won't be run on
3027 * the message being processed. Filter functions are allowed to modify
3028 * and even drop messages.
3030 * Note that filters are run in a dedicated message handling thread so
3031 * they can't block and, generally, can't do anything but signal a
3032 * worker thread. Also note that filters are rarely needed - use API
3033 * such as g_dbus_connection_send_message_with_reply(),
3034 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3036 * If a filter consumes an incoming message the message is not
3037 * dispatched anywhere else - not even the standard dispatch machinery
3038 * (that API such as g_dbus_connection_signal_subscribe() and
3039 * g_dbus_connection_send_message_with_reply() relies on) will see the
3040 * message. Similary, if a filter consumes an outgoing message, the
3041 * message will not be sent to the other peer.
3043 * Returns: A filter identifier that can be used with
3044 * g_dbus_connection_remove_filter().
3049 g_dbus_connection_add_filter (GDBusConnection *connection,
3050 GDBusMessageFilterFunction filter_function,
3052 GDestroyNotify user_data_free_func)
3056 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3057 g_return_val_if_fail (filter_function != NULL, 0);
3059 CONNECTION_LOCK (connection);
3060 data = g_new0 (FilterData, 1);
3061 data->id = _global_filter_id++; /* TODO: overflow etc. */
3062 data->filter_function = filter_function;
3063 data->user_data = user_data;
3064 data->user_data_free_func = user_data_free_func;
3065 g_ptr_array_add (connection->filters, data);
3066 CONNECTION_UNLOCK (connection);
3071 /* only called from finalize(), removes all filters */
3073 purge_all_filters (GDBusConnection *connection)
3076 for (n = 0; n < connection->filters->len; n++)
3078 FilterData *data = connection->filters->pdata[n];
3079 if (data->user_data_free_func != NULL)
3080 data->user_data_free_func (data->user_data);
3086 * g_dbus_connection_remove_filter:
3087 * @connection: a #GDBusConnection
3088 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3095 g_dbus_connection_remove_filter (GDBusConnection *connection,
3099 FilterData *to_destroy;
3101 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3103 CONNECTION_LOCK (connection);
3105 for (n = 0; n < connection->filters->len; n++)
3107 FilterData *data = connection->filters->pdata[n];
3108 if (data->id == filter_id)
3110 g_ptr_array_remove_index (connection->filters, n);
3115 CONNECTION_UNLOCK (connection);
3117 /* do free without holding lock */
3118 if (to_destroy != NULL)
3120 if (to_destroy->user_data_free_func != NULL)
3121 to_destroy->user_data_free_func (to_destroy->user_data);
3122 g_free (to_destroy);
3126 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3130 /* ---------------------------------------------------------------------------------------------------- */
3136 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3137 gchar *interface_name;
3141 GArray *subscribers;
3146 GDBusSignalCallback callback;
3148 GDestroyNotify user_data_free_func;
3150 GMainContext *context;
3154 signal_data_free (SignalData *signal_data)
3156 g_free (signal_data->rule);
3157 g_free (signal_data->sender);
3158 g_free (signal_data->sender_unique_name);
3159 g_free (signal_data->interface_name);
3160 g_free (signal_data->member);
3161 g_free (signal_data->object_path);
3162 g_free (signal_data->arg0);
3163 g_array_free (signal_data->subscribers, TRUE);
3164 g_free (signal_data);
3168 args_to_rule (const gchar *sender,
3169 const gchar *interface_name,
3170 const gchar *member,
3171 const gchar *object_path,
3177 rule = g_string_new ("type='signal'");
3179 g_string_prepend_c (rule, '-');
3181 g_string_append_printf (rule, ",sender='%s'", sender);
3182 if (interface_name != NULL)
3183 g_string_append_printf (rule, ",interface='%s'", interface_name);
3185 g_string_append_printf (rule, ",member='%s'", member);
3186 if (object_path != NULL)
3187 g_string_append_printf (rule, ",path='%s'", object_path);
3189 g_string_append_printf (rule, ",arg0='%s'", arg0);
3191 return g_string_free (rule, FALSE);
3194 static guint _global_subscriber_id = 1;
3195 static guint _global_registration_id = 1;
3196 static guint _global_subtree_registration_id = 1;
3198 /* ---------------------------------------------------------------------------------------------------- */
3200 /* must hold lock when calling */
3202 add_match_rule (GDBusConnection *connection,
3203 const gchar *match_rule)
3206 GDBusMessage *message;
3208 if (match_rule[0] == '-')
3211 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3212 "/org/freedesktop/DBus", /* path */
3213 "org.freedesktop.DBus", /* interface */
3215 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3217 if (!g_dbus_connection_send_message_unlocked (connection,
3219 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3223 g_critical ("Error while sending AddMatch() message: %s", error->message);
3224 g_error_free (error);
3226 g_object_unref (message);
3229 /* ---------------------------------------------------------------------------------------------------- */
3231 /* must hold lock when calling */
3233 remove_match_rule (GDBusConnection *connection,
3234 const gchar *match_rule)
3237 GDBusMessage *message;
3239 if (match_rule[0] == '-')
3242 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3243 "/org/freedesktop/DBus", /* path */
3244 "org.freedesktop.DBus", /* interface */
3246 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3249 if (!g_dbus_connection_send_message_unlocked (connection,
3251 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3255 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3256 g_error_free (error);
3258 g_object_unref (message);
3261 /* ---------------------------------------------------------------------------------------------------- */
3264 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3266 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3267 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3268 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3269 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3270 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3273 /* ---------------------------------------------------------------------------------------------------- */
3276 * g_dbus_connection_signal_subscribe:
3277 * @connection: A #GDBusConnection.
3278 * @sender: (allow-none): Sender name to match on (unique or well-known name)
3279 * or %NULL to listen from all senders.
3280 * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3281 * match on all interfaces.
3282 * @member: (allow-none): D-Bus signal name to match on or %NULL to match on all signals.
3283 * @object_path: (allow-none): Object path to match on or %NULL to match on all object paths.
3284 * @arg0: (allow-none): Contents of first string argument to match on or %NULL
3285 * to match on all kinds of arguments.
3286 * @flags: Flags describing how to subscribe to the signal (currently unused).
3287 * @callback: Callback to invoke when there is a signal matching the requested data.
3288 * @user_data: User data to pass to @callback.
3289 * @user_data_free_func: (allow-none): Function to free @user_data with when
3290 * subscription is removed or %NULL.
3292 * Subscribes to signals on @connection and invokes @callback with a
3293 * whenever the signal is received. Note that @callback
3294 * will be invoked in the <link
3295 * linkend="g-main-context-push-thread-default">thread-default main
3296 * loop</link> of the thread you are calling this method from.
3298 * If @connection is not a message bus connection, @sender must be
3301 * If @sender is a well-known name note that @callback is invoked with
3302 * the unique name for the owner of @sender, not the well-known name
3303 * as one would expect. This is because the message bus rewrites the
3304 * name. As such, to avoid certain race conditions, users should be
3305 * tracking the name owner of the well-known name and use that when
3306 * processing the received signal.
3308 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
3313 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3314 const gchar *sender,
3315 const gchar *interface_name,
3316 const gchar *member,
3317 const gchar *object_path,
3319 GDBusSignalFlags flags,
3320 GDBusSignalCallback callback,
3322 GDestroyNotify user_data_free_func)
3325 SignalData *signal_data;
3326 SignalSubscriber subscriber;
3327 GPtrArray *signal_data_array;
3328 const gchar *sender_unique_name;
3330 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3331 * an OOM condition. We might want to change that but that would involve making
3332 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3333 * handle that. And there's really no sensible way of handling this short of retrying
3334 * to add the match rule... and then there's the little thing that, hey, maybe there's
3335 * a reason the bus in an OOM condition.
3337 * Doable, but not really sure it's worth it...
3340 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3341 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3342 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3343 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3344 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3345 g_return_val_if_fail (callback != NULL, 0);
3347 CONNECTION_LOCK (connection);
3349 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3350 * with a '-' character to prefix the rule (which will otherwise be
3353 * This allows us to hash the rule and do our lifecycle tracking in
3354 * the usual way, but the '-' prevents the match rule from ever
3355 * actually being send to the bus (either for add or remove).
3357 rule = args_to_rule (sender, interface_name, member, object_path, arg0,
3358 (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE) != 0);
3360 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3361 sender_unique_name = sender;
3363 sender_unique_name = "";
3365 subscriber.callback = callback;
3366 subscriber.user_data = user_data;
3367 subscriber.user_data_free_func = user_data_free_func;
3368 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3369 subscriber.context = g_main_context_ref_thread_default ();
3371 /* see if we've already have this rule */
3372 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3373 if (signal_data != NULL)
3375 g_array_append_val (signal_data->subscribers, subscriber);
3380 signal_data = g_new0 (SignalData, 1);
3381 signal_data->rule = rule;
3382 signal_data->sender = g_strdup (sender);
3383 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3384 signal_data->interface_name = g_strdup (interface_name);
3385 signal_data->member = g_strdup (member);
3386 signal_data->object_path = g_strdup (object_path);
3387 signal_data->arg0 = g_strdup (arg0);
3388 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3389 g_array_append_val (signal_data->subscribers, subscriber);
3391 g_hash_table_insert (connection->map_rule_to_signal_data,
3395 /* Add the match rule to the bus...
3397 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3398 * always send such messages to us.
3400 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3402 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3403 add_match_rule (connection, signal_data->rule);
3406 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3407 signal_data->sender_unique_name);
3408 if (signal_data_array == NULL)
3410 signal_data_array = g_ptr_array_new ();
3411 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3412 g_strdup (signal_data->sender_unique_name),
3415 g_ptr_array_add (signal_data_array, signal_data);
3418 g_hash_table_insert (connection->map_id_to_signal_data,
3419 GUINT_TO_POINTER (subscriber.id),
3422 CONNECTION_UNLOCK (connection);
3424 return subscriber.id;
3427 /* ---------------------------------------------------------------------------------------------------- */
3429 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3431 unsubscribe_id_internal (GDBusConnection *connection,
3432 guint subscription_id,
3433 GArray *out_removed_subscribers)
3435 SignalData *signal_data;
3436 GPtrArray *signal_data_array;
3439 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3440 GUINT_TO_POINTER (subscription_id));
3441 if (signal_data == NULL)
3443 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3447 for (n = 0; n < signal_data->subscribers->len; n++)
3449 SignalSubscriber *subscriber;
3451 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3452 if (subscriber->id != subscription_id)
3455 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3456 GUINT_TO_POINTER (subscription_id)));
3457 g_array_append_val (out_removed_subscribers, *subscriber);
3458 g_array_remove_index (signal_data->subscribers, n);
3460 if (signal_data->subscribers->len == 0)
3462 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3464 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3465 signal_data->sender_unique_name);
3466 g_warn_if_fail (signal_data_array != NULL);
3467 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3469 if (signal_data_array->len == 0)
3471 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3472 signal_data->sender_unique_name));
3475 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3476 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3478 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3479 if (!connection->closed && !connection->finalizing)
3480 remove_match_rule (connection, signal_data->rule);
3482 signal_data_free (signal_data);
3488 g_assert_not_reached ();
3495 * g_dbus_connection_signal_unsubscribe:
3496 * @connection: A #GDBusConnection.
3497 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
3499 * Unsubscribes from signals.
3504 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3505 guint subscription_id)
3507 GArray *subscribers;
3510 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3512 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3514 CONNECTION_LOCK (connection);
3515 unsubscribe_id_internal (connection,
3518 CONNECTION_UNLOCK (connection);
3521 g_assert (subscribers->len == 0 || subscribers->len == 1);
3523 /* call GDestroyNotify without lock held */
3524 for (n = 0; n < subscribers->len; n++)
3526 SignalSubscriber *subscriber;
3527 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3528 call_destroy_notify (subscriber->context,
3529 subscriber->user_data_free_func,
3530 subscriber->user_data);
3531 g_main_context_unref (subscriber->context);
3534 g_array_free (subscribers, TRUE);
3537 /* ---------------------------------------------------------------------------------------------------- */
3541 guint subscription_id;
3542 GDBusSignalCallback callback;
3544 GDBusMessage *message;
3545 GDBusConnection *connection;
3546 const gchar *sender;
3548 const gchar *interface;
3549 const gchar *member;
3552 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3556 emit_signal_instance_in_idle_cb (gpointer data)
3558 SignalInstance *signal_instance = data;
3559 GVariant *parameters;
3560 gboolean has_subscription;
3562 parameters = g_dbus_message_get_body (signal_instance->message);
3563 if (parameters == NULL)
3565 parameters = g_variant_new ("()");
3566 g_variant_ref_sink (parameters);
3570 g_variant_ref_sink (parameters);
3574 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3575 signal_instance->subscription_id,
3576 signal_instance->sender,
3577 signal_instance->path,
3578 signal_instance->interface,
3579 signal_instance->member,
3580 g_variant_print (parameters, TRUE));
3583 /* Careful here, don't do the callback if we no longer has the subscription */
3584 CONNECTION_LOCK (signal_instance->connection);
3585 has_subscription = FALSE;
3586 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3587 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3588 has_subscription = TRUE;
3589 CONNECTION_UNLOCK (signal_instance->connection);
3591 if (has_subscription)
3592 signal_instance->callback (signal_instance->connection,
3593 signal_instance->sender,
3594 signal_instance->path,
3595 signal_instance->interface,
3596 signal_instance->member,
3598 signal_instance->user_data);
3600 g_variant_unref (parameters);
3606 signal_instance_free (SignalInstance *signal_instance)
3608 g_object_unref (signal_instance->message);
3609 g_object_unref (signal_instance->connection);
3610 g_free (signal_instance);
3613 /* called in message handler thread WITH lock held */
3615 schedule_callbacks (GDBusConnection *connection,
3616 GPtrArray *signal_data_array,
3617 GDBusMessage *message,
3618 const gchar *sender)
3621 const gchar *interface;
3622 const gchar *member;
3631 interface = g_dbus_message_get_interface (message);
3632 member = g_dbus_message_get_member (message);
3633 path = g_dbus_message_get_path (message);
3634 arg0 = g_dbus_message_get_arg0 (message);
3637 g_print ("In schedule_callbacks:\n"
3639 " interface = `%s'\n"
3650 /* TODO: if this is slow, then we can change signal_data_array into
3651 * map_object_path_to_signal_data_array or something.
3653 for (n = 0; n < signal_data_array->len; n++)
3655 SignalData *signal_data = signal_data_array->pdata[n];
3657 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3660 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3663 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3666 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
3669 for (m = 0; m < signal_data->subscribers->len; m++)
3671 SignalSubscriber *subscriber;
3672 GSource *idle_source;
3673 SignalInstance *signal_instance;
3675 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3677 signal_instance = g_new0 (SignalInstance, 1);
3678 signal_instance->subscription_id = subscriber->id;
3679 signal_instance->callback = subscriber->callback;
3680 signal_instance->user_data = subscriber->user_data;
3681 signal_instance->message = g_object_ref (message);
3682 signal_instance->connection = g_object_ref (connection);
3683 signal_instance->sender = sender;
3684 signal_instance->path = path;
3685 signal_instance->interface = interface;
3686 signal_instance->member = member;
3688 idle_source = g_idle_source_new ();
3689 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3690 g_source_set_callback (idle_source,
3691 emit_signal_instance_in_idle_cb,
3693 (GDestroyNotify) signal_instance_free);
3694 g_source_attach (idle_source, subscriber->context);
3695 g_source_unref (idle_source);
3700 /* called in message handler thread with lock held */
3702 distribute_signals (GDBusConnection *connection,
3703 GDBusMessage *message)
3705 GPtrArray *signal_data_array;
3706 const gchar *sender;
3708 sender = g_dbus_message_get_sender (message);
3710 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3712 _g_dbus_debug_print_lock ();
3713 g_print ("========================================================================\n"
3714 "GDBus-debug:Signal:\n"
3715 " <<<< RECEIVED SIGNAL %s.%s\n"
3717 " sent by name %s\n",
3718 g_dbus_message_get_interface (message),
3719 g_dbus_message_get_member (message),
3720 g_dbus_message_get_path (message),
3721 sender != NULL ? sender : "(none)");
3722 _g_dbus_debug_print_unlock ();
3725 /* collect subscribers that match on sender */
3728 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3729 if (signal_data_array != NULL)
3730 schedule_callbacks (connection, signal_data_array, message, sender);
3733 /* collect subscribers not matching on sender */
3734 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3735 if (signal_data_array != NULL)
3736 schedule_callbacks (connection, signal_data_array, message, sender);
3739 /* ---------------------------------------------------------------------------------------------------- */
3741 /* only called from finalize(), removes all subscriptions */
3743 purge_all_signal_subscriptions (GDBusConnection *connection)
3745 GHashTableIter iter;
3748 GArray *subscribers;
3751 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3752 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3753 while (g_hash_table_iter_next (&iter, &key, NULL))
3755 guint subscription_id = GPOINTER_TO_UINT (key);
3756 g_array_append_val (ids, subscription_id);
3759 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3760 for (n = 0; n < ids->len; n++)
3762 guint subscription_id = g_array_index (ids, guint, n);
3763 unsubscribe_id_internal (connection,
3767 g_array_free (ids, TRUE);
3769 /* call GDestroyNotify without lock held */
3770 for (n = 0; n < subscribers->len; n++)
3772 SignalSubscriber *subscriber;
3773 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3774 call_destroy_notify (subscriber->context,
3775 subscriber->user_data_free_func,
3776 subscriber->user_data);
3777 g_main_context_unref (subscriber->context);
3780 g_array_free (subscribers, TRUE);
3783 /* ---------------------------------------------------------------------------------------------------- */
3785 static GDBusInterfaceVTable *
3786 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3788 /* Don't waste memory by copying padding - remember to update this
3789 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3791 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3795 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
3800 /* ---------------------------------------------------------------------------------------------------- */
3802 static GDBusSubtreeVTable *
3803 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
3805 /* Don't waste memory by copying padding - remember to update this
3806 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
3808 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3812 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
3817 /* ---------------------------------------------------------------------------------------------------- */
3819 struct ExportedObject
3822 GDBusConnection *connection;
3824 /* maps gchar* -> ExportedInterface* */
3825 GHashTable *map_if_name_to_ei;
3828 /* only called with lock held */
3830 exported_object_free (ExportedObject *eo)
3832 g_free (eo->object_path);
3833 g_hash_table_unref (eo->map_if_name_to_ei);
3842 gchar *interface_name;
3843 GDBusInterfaceVTable *vtable;
3844 GDBusInterfaceInfo *interface_info;
3846 GMainContext *context;
3848 GDestroyNotify user_data_free_func;
3849 } ExportedInterface;
3851 /* called with lock held */
3853 exported_interface_free (ExportedInterface *ei)
3855 g_dbus_interface_info_cache_release (ei->interface_info);
3856 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
3858 call_destroy_notify (ei->context,
3859 ei->user_data_free_func,
3862 g_main_context_unref (ei->context);
3864 g_free (ei->interface_name);
3865 _g_dbus_interface_vtable_free (ei->vtable);
3869 /* ---------------------------------------------------------------------------------------------------- */
3871 /* Convenience function to check if @registration_id (if not zero) or
3872 * @subtree_registration_id (if not zero) has been unregistered. If
3873 * so, returns %TRUE.
3875 * Caller must *not* hold lock.
3878 has_object_been_unregistered (GDBusConnection *connection,
3879 guint registration_id,
3880 guint subtree_registration_id)
3884 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3888 CONNECTION_LOCK (connection);
3889 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
3890 GUINT_TO_POINTER (registration_id)) == NULL)
3894 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
3895 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
3899 CONNECTION_UNLOCK (connection);
3904 /* ---------------------------------------------------------------------------------------------------- */
3908 GDBusConnection *connection;
3909 GDBusMessage *message;
3911 const gchar *property_name;
3912 const GDBusInterfaceVTable *vtable;
3913 GDBusInterfaceInfo *interface_info;
3914 const GDBusPropertyInfo *property_info;
3915 guint registration_id;
3916 guint subtree_registration_id;
3920 property_data_free (PropertyData *data)
3922 g_object_unref (data->connection);
3923 g_object_unref (data->message);
3927 /* called in thread where object was registered - no locks held */
3929 invoke_get_property_in_idle_cb (gpointer _data)
3931 PropertyData *data = _data;
3934 GDBusMessage *reply;
3936 if (has_object_been_unregistered (data->connection,
3937 data->registration_id,
3938 data->subtree_registration_id))
3940 reply = g_dbus_message_new_method_error (data->message,
3941 "org.freedesktop.DBus.Error.UnknownMethod",
3942 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
3943 g_dbus_message_get_path (data->message));
3944 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3945 g_object_unref (reply);
3950 value = data->vtable->get_property (data->connection,
3951 g_dbus_message_get_sender (data->message),
3952 g_dbus_message_get_path (data->message),
3953 data->interface_info->name,
3954 data->property_name,
3961 g_assert_no_error (error);
3963 g_variant_take_ref (value);
3964 reply = g_dbus_message_new_method_reply (data->message);
3965 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
3966 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3967 g_variant_unref (value);
3968 g_object_unref (reply);
3972 gchar *dbus_error_name;
3973 g_assert (error != NULL);
3974 dbus_error_name = g_dbus_error_encode_gerror (error);
3975 reply = g_dbus_message_new_method_error_literal (data->message,
3978 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3979 g_free (dbus_error_name);
3980 g_error_free (error);
3981 g_object_unref (reply);
3988 /* called in thread where object was registered - no locks held */
3990 invoke_set_property_in_idle_cb (gpointer _data)
3992 PropertyData *data = _data;
3994 GDBusMessage *reply;
4000 g_variant_get (g_dbus_message_get_body (data->message),
4006 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4007 * of the given value is wrong
4009 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
4011 reply = g_dbus_message_new_method_error (data->message,
4012 "org.freedesktop.DBus.Error.InvalidArgs",
4013 _("Error setting property `%s': Expected type `%s' but got `%s'"),
4014 data->property_info->name,
4015 data->property_info->signature,
4016 g_variant_get_type_string (value));
4020 if (!data->vtable->set_property (data->connection,
4021 g_dbus_message_get_sender (data->message),
4022 g_dbus_message_get_path (data->message),
4023 data->interface_info->name,
4024 data->property_name,
4029 gchar *dbus_error_name;
4030 g_assert (error != NULL);
4031 dbus_error_name = g_dbus_error_encode_gerror (error);
4032 reply = g_dbus_message_new_method_error_literal (data->message,
4035 g_free (dbus_error_name);
4036 g_error_free (error);
4040 reply = g_dbus_message_new_method_reply (data->message);
4044 g_assert (reply != NULL);
4045 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4046 g_object_unref (reply);
4047 g_variant_unref (value);
4052 /* called with lock held */
4054 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4055 GDBusMessage *message,
4056 guint registration_id,
4057 guint subtree_registration_id,
4059 GDBusInterfaceInfo *interface_info,
4060 const GDBusInterfaceVTable *vtable,
4061 GMainContext *main_context,
4065 const char *interface_name;
4066 const char *property_name;
4067 const GDBusPropertyInfo *property_info;
4068 GSource *idle_source;
4069 PropertyData *property_data;
4070 GDBusMessage *reply;
4075 g_variant_get (g_dbus_message_get_body (message),
4080 g_variant_get (g_dbus_message_get_body (message),
4089 if (vtable == NULL || vtable->get_property == NULL)
4094 if (vtable == NULL || vtable->set_property == NULL)
4098 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4100 property_info = NULL;
4102 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4103 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4104 if (property_info == NULL)
4106 reply = g_dbus_message_new_method_error (message,
4107 "org.freedesktop.DBus.Error.InvalidArgs",
4108 _("No such property `%s'"),
4110 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4111 g_object_unref (reply);
4116 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4118 reply = g_dbus_message_new_method_error (message,
4119 "org.freedesktop.DBus.Error.InvalidArgs",
4120 _("Property `%s' is not readable"),
4122 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4123 g_object_unref (reply);
4127 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4129 reply = g_dbus_message_new_method_error (message,
4130 "org.freedesktop.DBus.Error.InvalidArgs",
4131 _("Property `%s' is not writable"),
4133 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4134 g_object_unref (reply);
4139 /* ok, got the property info - call user code in an idle handler */
4140 property_data = g_new0 (PropertyData, 1);
4141 property_data->connection = g_object_ref (connection);
4142 property_data->message = g_object_ref (message);
4143 property_data->user_data = user_data;
4144 property_data->property_name = property_name;
4145 property_data->vtable = vtable;
4146 property_data->interface_info = interface_info;
4147 property_data->property_info = property_info;
4148 property_data->registration_id = registration_id;
4149 property_data->subtree_registration_id = subtree_registration_id;
4151 idle_source = g_idle_source_new ();
4152 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4153 g_source_set_callback (idle_source,
4154 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4156 (GDestroyNotify) property_data_free);
4157 g_source_attach (idle_source, main_context);
4158 g_source_unref (idle_source);
4166 /* called with lock held */
4168 handle_getset_property (GDBusConnection *connection,
4170 GDBusMessage *message,
4173 ExportedInterface *ei;
4175 const char *interface_name;
4176 const char *property_name;
4181 g_variant_get (g_dbus_message_get_body (message),
4186 g_variant_get (g_dbus_message_get_body (message),
4192 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4193 * no such interface registered
4195 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4198 GDBusMessage *reply;
4199 reply = g_dbus_message_new_method_error (message,
4200 "org.freedesktop.DBus.Error.InvalidArgs",
4201 _("No such interface `%s'"),
4203 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4204 g_object_unref (reply);
4209 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4222 /* ---------------------------------------------------------------------------------------------------- */
4226 GDBusConnection *connection;
4227 GDBusMessage *message;
4229 const GDBusInterfaceVTable *vtable;
4230 GDBusInterfaceInfo *interface_info;
4231 guint registration_id;
4232 guint subtree_registration_id;
4233 } PropertyGetAllData;
4236 property_get_all_data_free (PropertyData *data)
4238 g_object_unref (data->connection);
4239 g_object_unref (data->message);
4243 /* called in thread where object was registered - no locks held */
4245 invoke_get_all_properties_in_idle_cb (gpointer _data)
4247 PropertyGetAllData *data = _data;
4248 GVariantBuilder builder;
4249 GDBusMessage *reply;
4252 if (has_object_been_unregistered (data->connection,
4253 data->registration_id,
4254 data->subtree_registration_id))
4256 reply = g_dbus_message_new_method_error (data->message,
4257 "org.freedesktop.DBus.Error.UnknownMethod",
4258 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
4259 g_dbus_message_get_path (data->message));
4260 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4261 g_object_unref (reply);
4265 /* TODO: Right now we never fail this call - we just omit values if
4266 * a get_property() call is failing.
4268 * We could fail the whole call if just a single get_property() call
4269 * returns an error. We need clarification in the D-Bus spec about this.
4271 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4272 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4273 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4275 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4278 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4281 value = data->vtable->get_property (data->connection,
4282 g_dbus_message_get_sender (data->message),
4283 g_dbus_message_get_path (data->message),
4284 data->interface_info->name,
4285 property_info->name,
4292 g_variant_take_ref (value);
4293 g_variant_builder_add (&builder,
4295 property_info->name,
4297 g_variant_unref (value);
4299 g_variant_builder_close (&builder);
4301 reply = g_dbus_message_new_method_reply (data->message);
4302 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4303 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4304 g_object_unref (reply);
4310 /* called with lock held */
4312 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4313 GDBusMessage *message,
4314 guint registration_id,
4315 guint subtree_registration_id,
4316 GDBusInterfaceInfo *interface_info,
4317 const GDBusInterfaceVTable *vtable,
4318 GMainContext *main_context,
4322 const char *interface_name;
4323 GSource *idle_source;
4324 PropertyGetAllData *property_get_all_data;
4328 g_variant_get (g_dbus_message_get_body (message),
4332 if (vtable == NULL || vtable->get_property == NULL)
4335 /* ok, got the property info - call user in an idle handler */
4336 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4337 property_get_all_data->connection = g_object_ref (connection);
4338 property_get_all_data->message = g_object_ref (message);
4339 property_get_all_data->user_data = user_data;
4340 property_get_all_data->vtable = vtable;
4341 property_get_all_data->interface_info = interface_info;
4342 property_get_all_data->registration_id = registration_id;
4343 property_get_all_data->subtree_registration_id = subtree_registration_id;
4345 idle_source = g_idle_source_new ();
4346 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4347 g_source_set_callback (idle_source,
4348 invoke_get_all_properties_in_idle_cb,
4349 property_get_all_data,
4350 (GDestroyNotify) property_get_all_data_free);
4351 g_source_attach (idle_source, main_context);
4352 g_source_unref (idle_source);
4360 /* called with lock held */
4362 handle_get_all_properties (GDBusConnection *connection,
4364 GDBusMessage *message)
4366 ExportedInterface *ei;
4368 const char *interface_name;
4372 g_variant_get (g_dbus_message_get_body (message),
4376 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4377 * no such interface registered
4379 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4382 GDBusMessage *reply;
4383 reply = g_dbus_message_new_method_error (message,
4384 "org.freedesktop.DBus.Error.InvalidArgs",
4385 _("No such interface"),
4387 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4388 g_object_unref (reply);
4393 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4405 /* ---------------------------------------------------------------------------------------------------- */
4407 static const gchar introspect_header[] =
4408 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4409 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4410 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4413 static const gchar introspect_tail[] =
4416 static const gchar introspect_properties_interface[] =
4417 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4418 " <method name=\"Get\">\n"
4419 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4420 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4421 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4423 " <method name=\"GetAll\">\n"
4424 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4425 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4427 " <method name=\"Set\">\n"
4428 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4429 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4430 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4432 " <signal name=\"PropertiesChanged\">\n"
4433 " <arg type=\"s\" name=\"interface_name\"/>\n"
4434 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4435 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4439 static const gchar introspect_introspectable_interface[] =
4440 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4441 " <method name=\"Introspect\">\n"
4442 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4445 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4446 " <method name=\"Ping\"/>\n"
4447 " <method name=\"GetMachineId\">\n"
4448 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4453 introspect_append_header (GString *s)
4455 g_string_append (s, introspect_header);
4459 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4461 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4467 begin = object_path + path_len;
4468 end = strchr (begin, '/');
4470 s = g_strndup (begin, end - begin);
4472 s = g_strdup (begin);
4474 if (g_hash_table_lookup (set, s) == NULL)
4475 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
4481 /* TODO: we want a nicer public interface for this */
4483 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4488 GHashTableIter hash_iter;
4489 const gchar *object_path;
4495 CONNECTION_ENSURE_LOCK (connection);
4497 path_len = strlen (path);
4501 set = g_hash_table_new (g_str_hash, g_str_equal);
4503 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4504 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4505 maybe_add_path (path, path_len, object_path, set);
4507 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4508 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4509 maybe_add_path (path, path_len, object_path, set);
4511 p = g_ptr_array_new ();
4512 keys = g_hash_table_get_keys (set);
4513 for (l = keys; l != NULL; l = l->next)
4514 g_ptr_array_add (p, l->data);
4515 g_hash_table_unref (set);
4518 g_ptr_array_add (p, NULL);
4519 ret = (gchar **) g_ptr_array_free (p, FALSE);
4524 g_dbus_connection_list_registered (GDBusConnection *connection,
4528 CONNECTION_LOCK (connection);
4529 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4530 CONNECTION_UNLOCK (connection);
4534 /* called in message handler thread with lock held */
4536 handle_introspect (GDBusConnection *connection,
4538 GDBusMessage *message)
4542 GDBusMessage *reply;
4543 GHashTableIter hash_iter;
4544 ExportedInterface *ei;
4547 /* first the header with the standard interfaces */
4548 s = g_string_sized_new (sizeof (introspect_header) +
4549 sizeof (introspect_properties_interface) +
4550 sizeof (introspect_introspectable_interface) +
4551 sizeof (introspect_tail));
4552 introspect_append_header (s);
4553 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4554 "org.freedesktop.DBus.Properties"))
4555 g_string_append (s, introspect_properties_interface);
4557 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4558 "org.freedesktop.DBus.Introspectable"))
4559 g_string_append (s, introspect_introspectable_interface);
4561 /* then include the registered interfaces */
4562 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4563 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4564 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4566 /* finally include nodes registered below us */
4567 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4568 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4569 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4570 g_strfreev (registered);
4571 g_string_append (s, introspect_tail);
4573 reply = g_dbus_message_new_method_reply (message);
4574 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4575 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4576 g_object_unref (reply);
4577 g_string_free (s, TRUE);
4582 /* called in thread where object was registered - no locks held */
4584 call_in_idle_cb (gpointer user_data)
4586 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4587 GDBusInterfaceVTable *vtable;
4588 guint registration_id;
4589 guint subtree_registration_id;
4591 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4592 g_assert (vtable != NULL && vtable->method_call != NULL);
4594 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4595 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4597 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4599 subtree_registration_id))
4601 GDBusMessage *reply;
4602 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4603 "org.freedesktop.DBus.Error.UnknownMethod",
4604 _("No such interface `%s' on object at path %s"),
4605 g_dbus_method_invocation_get_interface_name (invocation),
4606 g_dbus_method_invocation_get_object_path (invocation));
4607 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4608 g_object_unref (reply);
4612 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4613 g_dbus_method_invocation_get_sender (invocation),
4614 g_dbus_method_invocation_get_object_path (invocation),
4615 g_dbus_method_invocation_get_interface_name (invocation),
4616 g_dbus_method_invocation_get_method_name (invocation),
4617 g_dbus_method_invocation_get_parameters (invocation),
4618 g_object_ref (invocation),
4619 g_dbus_method_invocation_get_user_data (invocation));
4625 /* called in message handler thread with lock held */
4627 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4628 GDBusMessage *message,
4629 guint registration_id,
4630 guint subtree_registration_id,
4631 GDBusInterfaceInfo *interface_info,
4632 const GDBusInterfaceVTable *vtable,
4633 GMainContext *main_context,
4636 GDBusMethodInvocation *invocation;
4637 const GDBusMethodInfo *method_info;
4638 GDBusMessage *reply;
4639 GVariant *parameters;
4640 GSource *idle_source;
4642 GVariantType *in_type;
4646 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4647 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4649 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4650 * error to the caller
4652 if (method_info == NULL)
4654 reply = g_dbus_message_new_method_error (message,
4655 "org.freedesktop.DBus.Error.UnknownMethod",
4656 _("No such method `%s'"),
4657 g_dbus_message_get_member (message));
4658 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4659 g_object_unref (reply);
4664 parameters = g_dbus_message_get_body (message);
4665 if (parameters == NULL)
4667 parameters = g_variant_new ("()");
4668 g_variant_ref_sink (parameters);
4672 g_variant_ref (parameters);
4675 /* Check that the incoming args are of the right type - if they are not, return
4676 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4678 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4679 if (!g_variant_is_of_type (parameters, in_type))
4683 type_string = g_variant_type_dup_string (in_type);
4685 reply = g_dbus_message_new_method_error (message,
4686 "org.freedesktop.DBus.Error.InvalidArgs",
4687 _("Type of message, `%s', does not match expected type `%s'"),
4688 g_variant_get_type_string (parameters),
4690 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4691 g_variant_type_free (in_type);
4692 g_variant_unref (parameters);
4693 g_object_unref (reply);
4694 g_free (type_string);
4698 g_variant_type_free (in_type);
4700 /* schedule the call in idle */
4701 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4702 g_dbus_message_get_path (message),
4703 g_dbus_message_get_interface (message),
4704 g_dbus_message_get_member (message),
4710 g_variant_unref (parameters);
4712 /* TODO: would be nicer with a real MethodData like we already
4713 * have PropertyData and PropertyGetAllData... */
4714 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4715 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4716 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4718 idle_source = g_idle_source_new ();
4719 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4720 g_source_set_callback (idle_source,
4724 g_source_attach (idle_source, main_context);
4725 g_source_unref (idle_source);
4733 /* ---------------------------------------------------------------------------------------------------- */
4735 /* called in message handler thread with lock held */
4737 obj_message_func (GDBusConnection *connection,
4739 GDBusMessage *message)
4741 const gchar *interface_name;
4742 const gchar *member;
4743 const gchar *signature;
4748 interface_name = g_dbus_message_get_interface (message);
4749 member = g_dbus_message_get_member (message);
4750 signature = g_dbus_message_get_signature (message);
4752 /* see if we have an interface for handling this call */
4753 if (interface_name != NULL)
4755 ExportedInterface *ei;
4756 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4759 /* we do - invoke the handler in idle in the right thread */
4761 /* handle no vtable or handler being present */
4762 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
4765 handled = validate_and_maybe_schedule_method_call (connection,
4777 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4778 g_strcmp0 (member, "Introspect") == 0 &&
4779 g_strcmp0 (signature, "") == 0)
4781 handled = handle_introspect (connection, eo, message);
4784 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4785 g_strcmp0 (member, "Get") == 0 &&
4786 g_strcmp0 (signature, "ss") == 0)
4788 handled = handle_getset_property (connection, eo, message, TRUE);
4791 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4792 g_strcmp0 (member, "Set") == 0 &&
4793 g_strcmp0 (signature, "ssv") == 0)
4795 handled = handle_getset_property (connection, eo, message, FALSE);
4798 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4799 g_strcmp0 (member, "GetAll") == 0 &&
4800 g_strcmp0 (signature, "s") == 0)
4802 handled = handle_get_all_properties (connection, eo, message);
4811 * g_dbus_connection_register_object:
4812 * @connection: A #GDBusConnection.
4813 * @object_path: The object path to register at.
4814 * @interface_info: Introspection data for the interface.
4815 * @vtable: (allow-none): A #GDBusInterfaceVTable to call into or %NULL.
4816 * @user_data: (allow-none): Data to pass to functions in @vtable.
4817 * @user_data_free_func: Function to call when the object path is unregistered.
4818 * @error: Return location for error or %NULL.
4820 * Registers callbacks for exported objects at @object_path with the
4821 * D-Bus interface that is described in @interface_info.
4823 * Calls to functions in @vtable (and @user_data_free_func) will
4824 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
4825 * loop</link> of the thread you are calling this method from.
4827 * Note that all #GVariant values passed to functions in @vtable will match
4828 * the signature given in @interface_info - if a remote caller passes
4829 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
4830 * is returned to the remote caller.
4832 * Additionally, if the remote caller attempts to invoke methods or
4833 * access properties not mentioned in @interface_info the
4834 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
4835 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
4836 * are returned to the caller.
4838 * It is considered a programming error if the
4839 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
4840 * #GVariant of incorrect type.
4842 * If an existing callback is already registered at @object_path and
4843 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
4845 * GDBus automatically implements the standard D-Bus interfaces
4846 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
4847 * and org.freedesktop.Peer, so you don't have to implement those for
4848 * the objects you export. You <emphasis>can</emphasis> implement
4849 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
4850 * and setting of properties asynchronously.
4852 * Note that the reference count on @interface_info will be
4853 * incremented by 1 (unless allocated statically, e.g. if the
4854 * reference count is -1, see g_dbus_interface_info_ref()) for as long
4855 * as the object is exported. Also note that @vtable will be copied.
4857 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
4859 * Returns: 0 if @error is set, otherwise a registration id (never 0)
4860 * that can be used with g_dbus_connection_unregister_object() .
4865 g_dbus_connection_register_object (GDBusConnection *connection,
4866 const gchar *object_path,
4867 GDBusInterfaceInfo *interface_info,
4868 const GDBusInterfaceVTable *vtable,
4870 GDestroyNotify user_data_free_func,
4874 ExportedInterface *ei;
4877 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4878 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4879 g_return_val_if_fail (interface_info != NULL, 0);
4880 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
4881 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4885 CONNECTION_LOCK (connection);
4887 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
4890 eo = g_new0 (ExportedObject, 1);
4891 eo->object_path = g_strdup (object_path);
4892 eo->connection = connection;
4893 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
4896 (GDestroyNotify) exported_interface_free);
4897 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
4900 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
4906 _("An object is already exported for the interface %s at %s"),
4907 interface_info->name,
4912 ei = g_new0 (ExportedInterface, 1);
4913 ei->id = _global_registration_id++; /* TODO: overflow etc. */
4915 ei->user_data = user_data;
4916 ei->user_data_free_func = user_data_free_func;
4917 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
4918 ei->interface_info = g_dbus_interface_info_ref (interface_info);
4919 g_dbus_interface_info_cache_build (ei->interface_info);
4920 ei->interface_name = g_strdup (interface_info->name);
4921 ei->context = g_main_context_ref_thread_default ();
4923 g_hash_table_insert (eo->map_if_name_to_ei,
4924 (gpointer) ei->interface_name,
4926 g_hash_table_insert (connection->map_id_to_ei,
4927 GUINT_TO_POINTER (ei->id),
4933 CONNECTION_UNLOCK (connection);
4939 * g_dbus_connection_unregister_object:
4940 * @connection: A #GDBusConnection.
4941 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
4943 * Unregisters an object.
4945 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
4950 g_dbus_connection_unregister_object (GDBusConnection *connection,
4951 guint registration_id)
4953 ExportedInterface *ei;
4957 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4961 CONNECTION_LOCK (connection);
4963 ei = g_hash_table_lookup (connection->map_id_to_ei,
4964 GUINT_TO_POINTER (registration_id));
4970 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
4971 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
4972 /* unregister object path if we have no more exported interfaces */
4973 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
4974 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
4980 CONNECTION_UNLOCK (connection);
4985 /* ---------------------------------------------------------------------------------------------------- */
4988 * g_dbus_connection_emit_signal:
4989 * @connection: A #GDBusConnection.
4990 * @destination_bus_name: (allow-none): The unique bus name for the destination
4991 * for the signal or %NULL to emit to all listeners.
4992 * @object_path: Path of remote object.
4993 * @interface_name: D-Bus interface to emit a signal on.
4994 * @signal_name: The name of the signal to emit.
4995 * @parameters: (allow-none): A #GVariant tuple with parameters for the signal
4996 * or %NULL if not passing parameters.
4997 * @error: Return location for error or %NULL.
5001 * If the parameters GVariant is floating, it is consumed.
5003 * This can only fail if @parameters is not compatible with the D-Bus protocol.
5005 * Returns: %TRUE unless @error is set.
5010 g_dbus_connection_emit_signal (GDBusConnection *connection,
5011 const gchar *destination_bus_name,
5012 const gchar *object_path,
5013 const gchar *interface_name,
5014 const gchar *signal_name,
5015 GVariant *parameters,
5018 GDBusMessage *message;
5024 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5025 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5026 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5027 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5028 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5029 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5031 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5033 _g_dbus_debug_print_lock ();
5034 g_print ("========================================================================\n"
5035 "GDBus-debug:Emission:\n"
5036 " >>>> SIGNAL EMISSION %s.%s()\n"
5038 " destination %s\n",
5039 interface_name, signal_name,
5041 destination_bus_name != NULL ? destination_bus_name : "(none)");
5042 _g_dbus_debug_print_unlock ();
5045 message = g_dbus_message_new_signal (object_path,
5049 if (destination_bus_name != NULL)
5050 g_dbus_message_set_header (message,
5051 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5052 g_variant_new_string (destination_bus_name));
5054 if (parameters != NULL)
5055 g_dbus_message_set_body (message, parameters);
5057 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5058 g_object_unref (message);
5064 add_call_flags (GDBusMessage *message,
5065 GDBusCallFlags flags)
5067 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5068 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
5072 decode_method_reply (GDBusMessage *reply,
5073 const gchar *method_name,
5074 const GVariantType *reply_type,
5075 GUnixFDList **out_fd_list,
5081 switch (g_dbus_message_get_message_type (reply))
5083 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5084 result = g_dbus_message_get_body (reply);
5087 result = g_variant_new ("()");
5088 g_variant_ref_sink (result);
5092 g_variant_ref (result);
5095 if (!g_variant_is_of_type (result, reply_type))
5097 gchar *type_string = g_variant_type_dup_string (reply_type);
5101 G_IO_ERROR_INVALID_ARGUMENT,
5102 _("Method `%s' returned type `%s', but expected `%s'"),
5103 method_name, g_variant_get_type_string (result), type_string);
5105 g_variant_unref (result);
5106 g_free (type_string);
5113 if (out_fd_list != NULL)
5115 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5116 if (*out_fd_list != NULL)
5117 g_object_ref (*out_fd_list);
5123 case G_DBUS_MESSAGE_TYPE_ERROR:
5124 g_dbus_message_to_gerror (reply, error);
5128 g_assert_not_reached ();
5138 GSimpleAsyncResult *simple;
5139 GVariantType *reply_type;
5140 gchar *method_name; /* for error message */
5144 GUnixFDList *fd_list;
5148 call_state_free (CallState *state)
5150 g_variant_type_free (state->reply_type);
5151 g_free (state->method_name);
5153 if (state->value != NULL)
5154 g_variant_unref (state->value);
5155 if (state->fd_list != NULL)
5156 g_object_unref (state->fd_list);
5157 g_slice_free (CallState, state);
5161 g_dbus_connection_call_done (GObject *source,
5162 GAsyncResult *result,
5165 GSimpleAsyncResult *simple;
5166 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5167 CallState *state = user_data;
5169 GDBusMessage *reply;
5172 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5176 if (G_UNLIKELY (_g_dbus_debug_call ()))
5178 _g_dbus_debug_print_lock ();
5179 g_print ("========================================================================\n"
5180 "GDBus-debug:Call:\n"
5181 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5187 g_print ("SUCCESS\n");
5191 g_print ("FAILED: %s\n",
5194 _g_dbus_debug_print_unlock ();
5198 state->value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5200 simple = state->simple; /* why? because state is freed before we unref simple.. */
5203 g_simple_async_result_take_error (state->simple, error);
5204 g_simple_async_result_complete (state->simple);
5205 call_state_free (state);
5209 g_simple_async_result_set_op_res_gpointer (state->simple, state, (GDestroyNotify) call_state_free);
5210 g_simple_async_result_complete (state->simple);
5211 g_object_unref (reply);
5213 g_object_unref (simple);
5217 g_dbus_connection_call_internal (GDBusConnection *connection,
5218 const gchar *bus_name,
5219 const gchar *object_path,
5220 const gchar *interface_name,
5221 const gchar *method_name,
5222 GVariant *parameters,
5223 const GVariantType *reply_type,
5224 GDBusCallFlags flags,
5226 GUnixFDList *fd_list,
5227 GCancellable *cancellable,
5228 GAsyncReadyCallback callback,
5231 GDBusMessage *message;
5234 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5235 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5236 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5237 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5238 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5239 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5240 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5242 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5244 g_return_if_fail (fd_list == NULL);
5247 state = g_slice_new0 (CallState);
5248 state->simple = g_simple_async_result_new (G_OBJECT (connection),
5249 callback, user_data,
5250 g_dbus_connection_call_internal);
5251 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5253 if (reply_type == NULL)
5254 reply_type = G_VARIANT_TYPE_ANY;
5256 state->reply_type = g_variant_type_copy (reply_type);
5258 message = g_dbus_message_new_method_call (bus_name,
5262 add_call_flags (message, flags);
5263 if (parameters != NULL)
5264 g_dbus_message_set_body (message, parameters);
5267 if (fd_list != NULL)
5268 g_dbus_message_set_unix_fd_list (message, fd_list);
5271 g_dbus_connection_send_message_with_reply (connection,
5273 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5277 g_dbus_connection_call_done,
5280 if (G_UNLIKELY (_g_dbus_debug_call ()))
5282 _g_dbus_debug_print_lock ();
5283 g_print ("========================================================================\n"
5284 "GDBus-debug:Call:\n"
5285 " >>>> ASYNC %s.%s()\n"
5287 " owned by name %s (serial %d)\n",
5291 bus_name != NULL ? bus_name : "(none)",
5293 _g_dbus_debug_print_unlock ();
5296 if (message != NULL)
5297 g_object_unref (message);
5301 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
5302 GUnixFDList **out_fd_list,
5306 GSimpleAsyncResult *simple;
5309 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5310 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
5311 g_dbus_connection_call_internal), NULL);
5312 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5314 simple = G_SIMPLE_ASYNC_RESULT (res);
5316 if (g_simple_async_result_propagate_error (simple, error))
5319 state = g_simple_async_result_get_op_res_gpointer (simple);
5320 if (out_fd_list != NULL)
5321 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
5322 return g_variant_ref (state->value);
5326 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
5327 const gchar *bus_name,
5328 const gchar *object_path,
5329 const gchar *interface_name,
5330 const gchar *method_name,
5331 GVariant *parameters,
5332 const GVariantType *reply_type,
5333 GDBusCallFlags flags,
5335 GUnixFDList *fd_list,
5336 GUnixFDList **out_fd_list,
5337 GCancellable *cancellable,
5340 GDBusMessage *message;
5341 GDBusMessage *reply;
5343 GError *local_error;
5344 GDBusSendMessageFlags send_flags;
5350 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5351 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5352 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5353 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5354 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5355 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5356 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5358 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
5360 g_return_val_if_fail (fd_list == NULL, NULL);
5362 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5364 if (reply_type == NULL)
5365 reply_type = G_VARIANT_TYPE_ANY;
5367 message = g_dbus_message_new_method_call (bus_name,
5371 add_call_flags (message, flags);
5372 if (parameters != NULL)
5373 g_dbus_message_set_body (message, parameters);
5376 if (fd_list != NULL)
5377 g_dbus_message_set_unix_fd_list (message, fd_list);
5380 if (G_UNLIKELY (_g_dbus_debug_call ()))
5382 _g_dbus_debug_print_lock ();
5383 g_print ("========================================================================\n"
5384 "GDBus-debug:Call:\n"
5385 " >>>> SYNC %s.%s()\n"
5387 " owned by name %s\n",
5391 bus_name != NULL ? bus_name : "(none)");
5392 _g_dbus_debug_print_unlock ();
5397 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
5399 /* translate from one flavour of flags to another... */
5400 if (flags & CALL_FLAGS_INITIALIZING)
5401 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
5403 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5407 NULL, /* volatile guint32 *out_serial */
5411 if (G_UNLIKELY (_g_dbus_debug_call ()))
5413 _g_dbus_debug_print_lock ();
5414 g_print ("========================================================================\n"
5415 "GDBus-debug:Call:\n"
5416 " <<<< SYNC COMPLETE %s.%s()\n"
5422 g_print ("SUCCESS\n");
5426 g_print ("FAILED: %s\n",
5427 local_error->message);
5429 _g_dbus_debug_print_unlock ();
5435 *error = local_error;
5437 g_error_free (local_error);
5441 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
5444 if (message != NULL)
5445 g_object_unref (message);
5447 g_object_unref (reply);
5452 /* ---------------------------------------------------------------------------------------------------- */
5455 * g_dbus_connection_call:
5456 * @connection: A #GDBusConnection.
5457 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5458 * @connection is not a message bus connection.
5459 * @object_path: Path of remote object.
5460 * @interface_name: D-Bus interface to invoke method on.
5461 * @method_name: The name of the method to invoke.
5462 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5463 * or %NULL if not passing parameters.
5464 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5465 * @flags: Flags from the #GDBusCallFlags enumeration.
5466 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5467 * timeout or %G_MAXINT for no timeout.
5468 * @cancellable: A #GCancellable or %NULL.
5469 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5470 * satisfied or %NULL if you don't * care about the result of the
5471 * method invocation.
5472 * @user_data: The data to pass to @callback.
5474 * Asynchronously invokes the @method_name method on the
5475 * @interface_name D-Bus interface on the remote object at
5476 * @object_path owned by @bus_name.
5478 * If @connection is closed then the operation will fail with
5479 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
5480 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
5481 * not compatible with the D-Bus protocol, the operation fails with
5482 * %G_IO_ERROR_INVALID_ARGUMENT.
5484 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
5485 * error will be raised if it does not match. Said another way, if you give a @reply_type
5486 * then any non-%NULL return value will be of this type.
5488 * If the @parameters #GVariant is floating, it is consumed. This allows
5489 * convenient 'inline' use of g_variant_new(), e.g.:
5491 * g_dbus_connection_call (connection,
5492 * "org.freedesktop.StringThings",
5493 * "/org/freedesktop/StringThings",
5494 * "org.freedesktop.StringThings",
5496 * g_variant_new ("(ss)",
5500 * G_DBUS_CALL_FLAGS_NONE,
5503 * (GAsyncReadyCallback) two_strings_done,
5507 * This is an asynchronous method. When the operation is finished, @callback will be invoked
5508 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
5509 * of the thread you are calling this method from. You can then call
5510 * g_dbus_connection_call_finish() to get the result of the operation.
5511 * See g_dbus_connection_call_sync() for the synchronous version of this
5517 g_dbus_connection_call (GDBusConnection *connection,
5518 const gchar *bus_name,
5519 const gchar *object_path,
5520 const gchar *interface_name,
5521 const gchar *method_name,
5522 GVariant *parameters,
5523 const GVariantType *reply_type,
5524 GDBusCallFlags flags,
5526 GCancellable *cancellable,
5527 GAsyncReadyCallback callback,
5530 g_dbus_connection_call_internal (connection, bus_name, object_path, interface_name, method_name, parameters, reply_type, flags, timeout_msec, NULL, cancellable, callback, user_data);
5534 * g_dbus_connection_call_finish:
5535 * @connection: A #GDBusConnection.
5536 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
5537 * @error: Return location for error or %NULL.
5539 * Finishes an operation started with g_dbus_connection_call().
5541 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5542 * return values. Free with g_variant_unref().
5547 g_dbus_connection_call_finish (GDBusConnection *connection,
5551 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
5555 * g_dbus_connection_call_sync:
5556 * @connection: A #GDBusConnection.
5557 * @bus_name: A unique or well-known bus name.
5558 * @object_path: Path of remote object.
5559 * @interface_name: D-Bus interface to invoke method on.
5560 * @method_name: The name of the method to invoke.
5561 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5562 * or %NULL if not passing parameters.
5563 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5564 * @flags: Flags from the #GDBusCallFlags enumeration.
5565 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5566 * timeout or %G_MAXINT for no timeout.
5567 * @cancellable: A #GCancellable or %NULL.
5568 * @error: Return location for error or %NULL.
5570 * Synchronously invokes the @method_name method on the
5571 * @interface_name D-Bus interface on the remote object at
5572 * @object_path owned by @bus_name.
5574 * If @connection is closed then the operation will fail with
5575 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
5576 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
5577 * contains a value not compatible with the D-Bus protocol, the operation
5578 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
5580 * If @reply_type is non-%NULL then the reply will be checked for having
5581 * this type and an error will be raised if it does not match. Said
5582 * another way, if you give a @reply_type then any non-%NULL return
5583 * value will be of this type.
5585 * If the @parameters #GVariant is floating, it is consumed.
5586 * This allows convenient 'inline' use of g_variant_new(), e.g.:
5588 * g_dbus_connection_call_sync (connection,
5589 * "org.freedesktop.StringThings",
5590 * "/org/freedesktop/StringThings",
5591 * "org.freedesktop.StringThings",
5593 * g_variant_new ("(ss)",
5597 * G_DBUS_CALL_FLAGS_NONE,
5603 * The calling thread is blocked until a reply is received. See
5604 * g_dbus_connection_call() for the asynchronous version of
5607 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5608 * return values. Free with g_variant_unref().
5613 g_dbus_connection_call_sync (GDBusConnection *connection,
5614 const gchar *bus_name,
5615 const gchar *object_path,
5616 const gchar *interface_name,
5617 const gchar *method_name,
5618 GVariant *parameters,
5619 const GVariantType *reply_type,
5620 GDBusCallFlags flags,
5622 GCancellable *cancellable,
5625 return g_dbus_connection_call_sync_internal (connection, bus_name, object_path, interface_name, method_name, parameters, reply_type, flags, timeout_msec, NULL, NULL, cancellable, error);
5628 /* ---------------------------------------------------------------------------------------------------- */
5633 * g_dbus_connection_call_with_unix_fd_list:
5634 * @connection: A #GDBusConnection.
5635 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5636 * @connection is not a message bus connection.
5637 * @object_path: Path of remote object.
5638 * @interface_name: D-Bus interface to invoke method on.
5639 * @method_name: The name of the method to invoke.
5640 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5641 * or %NULL if not passing parameters.
5642 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5643 * @flags: Flags from the #GDBusCallFlags enumeration.
5644 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5645 * timeout or %G_MAXINT for no timeout.
5646 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
5647 * @cancellable: A #GCancellable or %NULL.
5648 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5649 * satisfied or %NULL if you don't * care about the result of the
5650 * method invocation.
5651 * @user_data: The data to pass to @callback.
5653 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
5655 * This method is only available on UNIX.
5660 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
5661 const gchar *bus_name,
5662 const gchar *object_path,
5663 const gchar *interface_name,
5664 const gchar *method_name,
5665 GVariant *parameters,
5666 const GVariantType *reply_type,
5667 GDBusCallFlags flags,
5669 GUnixFDList *fd_list,
5670 GCancellable *cancellable,
5671 GAsyncReadyCallback callback,
5674 g_dbus_connection_call_internal (connection, bus_name, object_path, interface_name, method_name, parameters, reply_type, flags, timeout_msec, fd_list, cancellable, callback, user_data);
5678 * g_dbus_connection_call_with_unix_fd_list_finish:
5679 * @connection: A #GDBusConnection.
5680 * @out_fd_list: (out): Return location for a #GUnixFDList or %NULL.
5681 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call_with_unix_fd_list().
5682 * @error: Return location for error or %NULL.
5684 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
5686 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5687 * return values. Free with g_variant_unref().
5692 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
5693 GUnixFDList **out_fd_list,
5697 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
5701 * g_dbus_connection_call_with_unix_fd_list_sync:
5702 * @connection: A #GDBusConnection.
5703 * @bus_name: A unique or well-known bus name.
5704 * @object_path: Path of remote object.
5705 * @interface_name: D-Bus interface to invoke method on.
5706 * @method_name: The name of the method to invoke.
5707 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5708 * or %NULL if not passing parameters.
5709 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5710 * @flags: Flags from the #GDBusCallFlags enumeration.
5711 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5712 * timeout or %G_MAXINT for no timeout.
5713 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
5714 * @out_fd_list: (out): Return location for a #GUnixFDList or %NULL.
5715 * @cancellable: A #GCancellable or %NULL.
5716 * @error: Return location for error or %NULL.
5718 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
5720 * This method is only available on UNIX.
5722 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5723 * return values. Free with g_variant_unref().
5728 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
5729 const gchar *bus_name,
5730 const gchar *object_path,
5731 const gchar *interface_name,
5732 const gchar *method_name,
5733 GVariant *parameters,
5734 const GVariantType *reply_type,
5735 GDBusCallFlags flags,
5737 GUnixFDList *fd_list,
5738 GUnixFDList **out_fd_list,
5739 GCancellable *cancellable,
5742 return g_dbus_connection_call_sync_internal (connection, bus_name, object_path, interface_name, method_name, parameters, reply_type, flags, timeout_msec, fd_list, out_fd_list, cancellable, error);
5745 #endif /* G_OS_UNIX */
5747 /* ---------------------------------------------------------------------------------------------------- */
5749 struct ExportedSubtree
5753 GDBusConnection *connection;
5754 GDBusSubtreeVTable *vtable;
5755 GDBusSubtreeFlags flags;
5757 GMainContext *context;
5759 GDestroyNotify user_data_free_func;
5763 exported_subtree_free (ExportedSubtree *es)
5765 call_destroy_notify (es->context,
5766 es->user_data_free_func,
5769 g_main_context_unref (es->context);
5771 _g_dbus_subtree_vtable_free (es->vtable);
5772 g_free (es->object_path);
5776 /* called without lock held */
5778 handle_subtree_introspect (GDBusConnection *connection,
5779 ExportedSubtree *es,
5780 GDBusMessage *message)
5784 GDBusMessage *reply;
5787 const gchar *sender;
5788 const gchar *requested_object_path;
5789 const gchar *requested_node;
5790 GDBusInterfaceInfo **interfaces;
5792 gchar **subnode_paths;
5793 gboolean has_properties_interface;
5794 gboolean has_introspectable_interface;
5798 requested_object_path = g_dbus_message_get_path (message);
5799 sender = g_dbus_message_get_sender (message);
5800 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5802 s = g_string_new (NULL);
5803 introspect_append_header (s);
5805 /* Strictly we don't need the children in dynamic mode, but we avoid the
5806 * conditionals to preserve code clarity
5808 children = es->vtable->enumerate (es->connection,
5815 requested_node = strrchr (requested_object_path, '/') + 1;
5817 /* Assert existence of object if we are not dynamic */
5818 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
5819 !_g_strv_has_string ((const gchar * const *) children, requested_node))
5824 requested_node = NULL;
5827 interfaces = es->vtable->introspect (es->connection,
5832 if (interfaces != NULL)
5834 has_properties_interface = FALSE;
5835 has_introspectable_interface = FALSE;
5837 for (n = 0; interfaces[n] != NULL; n++)
5839 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
5840 has_properties_interface = TRUE;
5841 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
5842 has_introspectable_interface = TRUE;
5844 if (!has_properties_interface)
5845 g_string_append (s, introspect_properties_interface);
5846 if (!has_introspectable_interface)
5847 g_string_append (s, introspect_introspectable_interface);
5849 for (n = 0; interfaces[n] != NULL; n++)
5851 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
5852 g_dbus_interface_info_unref (interfaces[n]);
5854 g_free (interfaces);
5857 /* then include <node> entries from the Subtree for the root */
5860 for (n = 0; children != NULL && children[n] != NULL; n++)
5861 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
5864 /* finally include nodes registered below us */
5865 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
5866 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
5867 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
5868 g_strfreev (subnode_paths);
5870 g_string_append (s, "</node>\n");
5872 reply = g_dbus_message_new_method_reply (message);
5873 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5874 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5875 g_object_unref (reply);
5880 g_string_free (s, TRUE);
5881 g_strfreev (children);
5885 /* called without lock held */
5887 handle_subtree_method_invocation (GDBusConnection *connection,
5888 ExportedSubtree *es,
5889 GDBusMessage *message)
5892 const gchar *sender;
5893 const gchar *interface_name;
5894 const gchar *member;
5895 const gchar *signature;
5896 const gchar *requested_object_path;
5897 const gchar *requested_node;
5899 GDBusInterfaceInfo *interface_info;
5900 const GDBusInterfaceVTable *interface_vtable;
5901 gpointer interface_user_data;
5903 GDBusInterfaceInfo **interfaces;
5904 gboolean is_property_get;
5905 gboolean is_property_set;
5906 gboolean is_property_get_all;
5911 requested_object_path = g_dbus_message_get_path (message);
5912 sender = g_dbus_message_get_sender (message);
5913 interface_name = g_dbus_message_get_interface (message);
5914 member = g_dbus_message_get_member (message);
5915 signature = g_dbus_message_get_signature (message);
5916 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5918 is_property_get = FALSE;
5919 is_property_set = FALSE;
5920 is_property_get_all = FALSE;
5921 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
5923 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
5924 is_property_get = TRUE;
5925 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
5926 is_property_set = TRUE;
5927 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
5928 is_property_get_all = TRUE;
5933 requested_node = strrchr (requested_object_path, '/') + 1;
5935 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
5937 /* We don't want to dispatch to unenumerated
5938 * nodes, so ensure that the child exists.
5943 children = es->vtable->enumerate (es->connection,
5948 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
5949 g_strfreev (children);
5957 requested_node = NULL;
5960 /* get introspection data for the node */
5961 interfaces = es->vtable->introspect (es->connection,
5963 requested_object_path,
5967 if (interfaces == NULL)
5970 interface_info = NULL;
5971 for (n = 0; interfaces[n] != NULL; n++)
5973 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
5974 interface_info = interfaces[n];
5977 /* dispatch the call if the user wants to handle it */
5978 if (interface_info != NULL)
5980 /* figure out where to dispatch the method call */
5981 interface_user_data = NULL;
5982 interface_vtable = es->vtable->dispatch (es->connection,
5987 &interface_user_data,
5989 if (interface_vtable == NULL)
5992 CONNECTION_LOCK (connection);
5993 handled = validate_and_maybe_schedule_method_call (es->connection,
6000 interface_user_data);
6001 CONNECTION_UNLOCK (connection);
6003 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6004 else if (is_property_get || is_property_set || is_property_get_all)
6006 if (is_property_get)
6007 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6008 else if (is_property_set)
6009 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6010 else if (is_property_get_all)
6011 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6013 g_assert_not_reached ();
6015 /* see if the object supports this interface at all */
6016 for (n = 0; interfaces[n] != NULL; n++)
6018 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6019 interface_info = interfaces[n];
6022 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6023 * claims it won't support the interface
6025 if (interface_info == NULL)
6027 GDBusMessage *reply;
6028 reply = g_dbus_message_new_method_error (message,
6029 "org.freedesktop.DBus.Error.InvalidArgs",
6030 _("No such interface `%s'"),
6032 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6033 g_object_unref (reply);
6038 /* figure out where to dispatch the property get/set/getall calls */
6039 interface_user_data = NULL;
6040 interface_vtable = es->vtable->dispatch (es->connection,
6045 &interface_user_data,
6047 if (interface_vtable == NULL)
6049 g_warning ("The subtree introspection function indicates that '%s' "
6050 "is a valid interface name, but calling the dispatch "
6051 "function on that interface gave us NULL", interface_name);
6055 if (is_property_get || is_property_set)
6057 CONNECTION_LOCK (connection);
6058 handled = validate_and_maybe_schedule_property_getset (es->connection,
6066 interface_user_data);
6067 CONNECTION_UNLOCK (connection);
6069 else if (is_property_get_all)
6071 CONNECTION_LOCK (connection);
6072 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6079 interface_user_data);
6080 CONNECTION_UNLOCK (connection);
6085 if (interfaces != NULL)
6087 for (n = 0; interfaces[n] != NULL; n++)
6088 g_dbus_interface_info_unref (interfaces[n]);
6089 g_free (interfaces);
6097 GDBusMessage *message;
6098 ExportedSubtree *es;
6099 } SubtreeDeferredData;
6102 subtree_deferred_data_free (SubtreeDeferredData *data)
6104 g_object_unref (data->message);
6108 /* called without lock held in the thread where the caller registered the subtree */
6110 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6112 SubtreeDeferredData *data = _data;
6117 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6118 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6119 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6120 handled = handle_subtree_introspect (data->es->connection,
6124 handled = handle_subtree_method_invocation (data->es->connection,
6130 CONNECTION_LOCK (data->es->connection);
6131 handled = handle_generic_unlocked (data->es->connection, data->message);
6132 CONNECTION_UNLOCK (data->es->connection);
6135 /* if we couldn't handle the request, just bail with the UnknownMethod error */
6138 GDBusMessage *reply;
6139 reply = g_dbus_message_new_method_error (data->message,
6140 "org.freedesktop.DBus.Error.UnknownMethod",
6141 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
6142 g_dbus_message_get_member (data->message),
6143 g_dbus_message_get_interface (data->message),
6144 g_dbus_message_get_signature (data->message));
6145 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6146 g_object_unref (reply);
6152 /* called in message handler thread with lock held */
6154 subtree_message_func (GDBusConnection *connection,
6155 ExportedSubtree *es,
6156 GDBusMessage *message)
6158 GSource *idle_source;
6159 SubtreeDeferredData *data;
6161 data = g_new0 (SubtreeDeferredData, 1);
6162 data->message = g_object_ref (message);
6165 /* defer this call to an idle handler in the right thread */
6166 idle_source = g_idle_source_new ();
6167 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
6168 g_source_set_callback (idle_source,
6169 process_subtree_vtable_message_in_idle_cb,
6171 (GDestroyNotify) subtree_deferred_data_free);
6172 g_source_attach (idle_source, es->context);
6173 g_source_unref (idle_source);
6175 /* since we own the entire subtree, handlers for objects not in the subtree have been
6176 * tried already by libdbus-1 - so we just need to ensure that we're always going
6177 * to reply to the message
6183 * g_dbus_connection_register_subtree:
6184 * @connection: A #GDBusConnection.
6185 * @object_path: The object path to register the subtree at.
6186 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
6187 * @flags: Flags used to fine tune the behavior of the subtree.
6188 * @user_data: Data to pass to functions in @vtable.
6189 * @user_data_free_func: Function to call when the subtree is unregistered.
6190 * @error: Return location for error or %NULL.
6192 * Registers a whole subtree of <quote>dynamic</quote> objects.
6194 * The @enumerate and @introspection functions in @vtable are used to
6195 * convey, to remote callers, what nodes exist in the subtree rooted
6198 * When handling remote calls into any node in the subtree, first the
6199 * @enumerate function is used to check if the node exists. If the node exists
6200 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6201 * the @introspection function is used to check if the node supports the
6202 * requested method. If so, the @dispatch function is used to determine
6203 * where to dispatch the call. The collected #GDBusInterfaceVTable and
6204 * #gpointer will be used to call into the interface vtable for processing
6207 * All calls into user-provided code will be invoked in the <link
6208 * linkend="g-main-context-push-thread-default">thread-default main
6209 * loop</link> of the thread you are calling this method from.
6211 * If an existing subtree is already registered at @object_path or
6212 * then @error is set to #G_IO_ERROR_EXISTS.
6214 * Note that it is valid to register regular objects (using
6215 * g_dbus_connection_register_object()) in a subtree registered with
6216 * g_dbus_connection_register_subtree() - if so, the subtree handler
6217 * is tried as the last resort. One way to think about a subtree
6218 * handler is to consider it a <quote>fallback handler</quote>
6219 * for object paths not registered via g_dbus_connection_register_object()
6220 * or other bindings.
6222 * Note that @vtable will be copied so you cannot change it after
6225 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
6227 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
6228 * that can be used with g_dbus_connection_unregister_subtree() .
6233 g_dbus_connection_register_subtree (GDBusConnection *connection,
6234 const gchar *object_path,
6235 const GDBusSubtreeVTable *vtable,
6236 GDBusSubtreeFlags flags,
6238 GDestroyNotify user_data_free_func,
6242 ExportedSubtree *es;
6244 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
6245 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
6246 g_return_val_if_fail (vtable != NULL, 0);
6247 g_return_val_if_fail (error == NULL || *error == NULL, 0);
6251 CONNECTION_LOCK (connection);
6253 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6259 _("A subtree is already exported for %s"),
6264 es = g_new0 (ExportedSubtree, 1);
6265 es->object_path = g_strdup (object_path);
6266 es->connection = connection;
6268 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
6270 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
6271 es->user_data = user_data;
6272 es->user_data_free_func = user_data_free_func;
6273 es->context = g_main_context_ref_thread_default ();
6275 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
6276 g_hash_table_insert (connection->map_id_to_es,
6277 GUINT_TO_POINTER (es->id),
6283 CONNECTION_UNLOCK (connection);
6288 /* ---------------------------------------------------------------------------------------------------- */
6291 * g_dbus_connection_unregister_subtree:
6292 * @connection: A #GDBusConnection.
6293 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
6295 * Unregisters a subtree.
6297 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
6302 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
6303 guint registration_id)
6305 ExportedSubtree *es;
6308 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
6312 CONNECTION_LOCK (connection);
6314 es = g_hash_table_lookup (connection->map_id_to_es,
6315 GUINT_TO_POINTER (registration_id));
6319 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
6320 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
6325 CONNECTION_UNLOCK (connection);
6330 /* ---------------------------------------------------------------------------------------------------- */
6332 /* must be called with lock held */
6334 handle_generic_ping_unlocked (GDBusConnection *connection,
6335 const gchar *object_path,
6336 GDBusMessage *message)
6338 GDBusMessage *reply;
6339 reply = g_dbus_message_new_method_reply (message);
6340 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6341 g_object_unref (reply);
6344 /* must be called with lock held */
6346 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
6347 const gchar *object_path,
6348 GDBusMessage *message)
6350 GDBusMessage *reply;
6353 if (connection->machine_id == NULL)
6358 connection->machine_id = _g_dbus_get_machine_id (&error);
6359 if (connection->machine_id == NULL)
6361 reply = g_dbus_message_new_method_error_literal (message,
6362 "org.freedesktop.DBus.Error.Failed",
6364 g_error_free (error);
6370 reply = g_dbus_message_new_method_reply (message);
6371 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
6373 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6374 g_object_unref (reply);
6377 /* must be called with lock held */
6379 handle_generic_introspect_unlocked (GDBusConnection *connection,
6380 const gchar *object_path,
6381 GDBusMessage *message)
6386 GDBusMessage *reply;
6388 /* first the header */
6389 s = g_string_new (NULL);
6390 introspect_append_header (s);
6392 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
6393 for (n = 0; registered != NULL && registered[n] != NULL; n++)
6394 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
6395 g_strfreev (registered);
6396 g_string_append (s, "</node>\n");
6398 reply = g_dbus_message_new_method_reply (message);
6399 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6400 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6401 g_object_unref (reply);
6402 g_string_free (s, TRUE);
6405 /* must be called with lock held */
6407 handle_generic_unlocked (GDBusConnection *connection,
6408 GDBusMessage *message)
6411 const gchar *interface_name;
6412 const gchar *member;
6413 const gchar *signature;
6416 CONNECTION_ENSURE_LOCK (connection);
6420 interface_name = g_dbus_message_get_interface (message);
6421 member = g_dbus_message_get_member (message);
6422 signature = g_dbus_message_get_signature (message);
6423 path = g_dbus_message_get_path (message);
6425 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
6426 g_strcmp0 (member, "Introspect") == 0 &&
6427 g_strcmp0 (signature, "") == 0)
6429 handle_generic_introspect_unlocked (connection, path, message);
6432 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6433 g_strcmp0 (member, "Ping") == 0 &&
6434 g_strcmp0 (signature, "") == 0)
6436 handle_generic_ping_unlocked (connection, path, message);
6439 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6440 g_strcmp0 (member, "GetMachineId") == 0 &&
6441 g_strcmp0 (signature, "") == 0)
6443 handle_generic_get_machine_id_unlocked (connection, path, message);
6450 /* ---------------------------------------------------------------------------------------------------- */
6452 /* called in message handler thread with lock held */
6454 distribute_method_call (GDBusConnection *connection,
6455 GDBusMessage *message)
6457 GDBusMessage *reply;
6459 ExportedSubtree *es;
6460 const gchar *object_path;
6461 const gchar *interface_name;
6462 const gchar *member;
6464 gchar *subtree_path;
6467 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
6469 interface_name = g_dbus_message_get_interface (message);
6470 member = g_dbus_message_get_member (message);
6471 path = g_dbus_message_get_path (message);
6472 subtree_path = g_strdup (path);
6473 needle = strrchr (subtree_path, '/');
6474 if (needle != NULL && needle != subtree_path)
6480 g_free (subtree_path);
6481 subtree_path = NULL;
6485 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
6487 _g_dbus_debug_print_lock ();
6488 g_print ("========================================================================\n"
6489 "GDBus-debug:Incoming:\n"
6490 " <<<< METHOD INVOCATION %s.%s()\n"
6492 " invoked by name %s\n"
6494 interface_name, member,
6496 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
6497 g_dbus_message_get_serial (message));
6498 _g_dbus_debug_print_unlock ();
6501 object_path = g_dbus_message_get_path (message);
6502 g_assert (object_path != NULL);
6504 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
6507 if (obj_message_func (connection, eo, message))
6511 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6514 if (subtree_message_func (connection, es, message))
6518 if (subtree_path != NULL)
6520 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
6523 if (subtree_message_func (connection, es, message))
6528 if (handle_generic_unlocked (connection, message))
6531 /* if we end up here, the message has not been not handled - so return an error saying this */
6532 reply = g_dbus_message_new_method_error (message,
6533 "org.freedesktop.DBus.Error.UnknownMethod",
6534 _("No such interface `%s' on object at path %s"),
6537 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6538 g_object_unref (reply);
6541 g_free (subtree_path);
6544 /* ---------------------------------------------------------------------------------------------------- */
6546 static GDBusConnection **
6547 message_bus_get_singleton (GBusType bus_type,
6550 GDBusConnection **ret;
6551 const gchar *starter_bus;
6557 case G_BUS_TYPE_SESSION:
6558 ret = &the_session_bus;
6561 case G_BUS_TYPE_SYSTEM:
6562 ret = &the_system_bus;
6565 case G_BUS_TYPE_STARTER:
6566 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
6567 if (g_strcmp0 (starter_bus, "session") == 0)
6569 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
6572 else if (g_strcmp0 (starter_bus, "system") == 0)
6574 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
6579 if (starter_bus != NULL)
6583 G_IO_ERROR_INVALID_ARGUMENT,
6584 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
6585 " - unknown value `%s'"),
6590 g_set_error_literal (error,
6592 G_IO_ERROR_INVALID_ARGUMENT,
6593 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
6594 "variable is not set"));
6600 g_assert_not_reached ();
6608 static GDBusConnection *
6609 get_uninitialized_connection (GBusType bus_type,
6610 GCancellable *cancellable,
6613 GDBusConnection **singleton;
6614 GDBusConnection *ret;
6618 G_LOCK (message_bus_lock);
6619 singleton = message_bus_get_singleton (bus_type, error);
6620 if (singleton == NULL)
6623 if (*singleton == NULL)
6626 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
6627 if (address == NULL)
6629 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
6631 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
6632 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
6633 "exit-on-close", TRUE,
6639 ret = g_object_ref (*singleton);
6642 g_assert (ret != NULL);
6645 G_UNLOCK (message_bus_lock);
6651 * @bus_type: A #GBusType.
6652 * @cancellable: A #GCancellable or %NULL.
6653 * @error: Return location for error or %NULL.
6655 * Synchronously connects to the message bus specified by @bus_type.
6656 * Note that the returned object may shared with other callers,
6657 * e.g. if two separate parts of a process calls this function with
6658 * the same @bus_type, they will share the same object.
6660 * This is a synchronous failable function. See g_bus_get() and
6661 * g_bus_get_finish() for the asynchronous version.
6663 * The returned object is a singleton, that is, shared with other
6664 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6665 * event that you need a private message bus connection, use
6666 * g_dbus_address_get_for_bus_sync() and
6667 * g_dbus_connection_new_for_address().
6669 * Note that the returned #GDBusConnection object will (usually) have
6670 * the #GDBusConnection:exit-on-close property set to %TRUE.
6672 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6677 g_bus_get_sync (GBusType bus_type,
6678 GCancellable *cancellable,
6681 GDBusConnection *connection;
6683 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6685 connection = get_uninitialized_connection (bus_type, cancellable, error);
6686 if (connection == NULL)
6689 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
6691 g_object_unref (connection);
6700 bus_get_async_initable_cb (GObject *source_object,
6704 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
6708 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
6712 g_assert (error != NULL);
6713 g_simple_async_result_take_error (simple, error);
6714 g_object_unref (source_object);
6718 g_simple_async_result_set_op_res_gpointer (simple,
6722 g_simple_async_result_complete_in_idle (simple);
6723 g_object_unref (simple);
6728 * @bus_type: A #GBusType.
6729 * @cancellable: A #GCancellable or %NULL.
6730 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
6731 * @user_data: The data to pass to @callback.
6733 * Asynchronously connects to the message bus specified by @bus_type.
6735 * When the operation is finished, @callback will be invoked. You can
6736 * then call g_bus_get_finish() to get the result of the operation.
6738 * This is a asynchronous failable function. See g_bus_get_sync() for
6739 * the synchronous version.
6744 g_bus_get (GBusType bus_type,
6745 GCancellable *cancellable,
6746 GAsyncReadyCallback callback,
6749 GDBusConnection *connection;
6750 GSimpleAsyncResult *simple;
6753 simple = g_simple_async_result_new (NULL,
6759 connection = get_uninitialized_connection (bus_type, cancellable, &error);
6760 if (connection == NULL)
6762 g_assert (error != NULL);
6763 g_simple_async_result_take_error (simple, error);
6764 g_simple_async_result_complete_in_idle (simple);
6765 g_object_unref (simple);
6769 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
6772 bus_get_async_initable_cb,
6779 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
6780 * @error: Return location for error or %NULL.
6782 * Finishes an operation started with g_bus_get().
6784 * The returned object is a singleton, that is, shared with other
6785 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6786 * event that you need a private message bus connection, use
6787 * g_dbus_address_get_for_bus_sync() and
6788 * g_dbus_connection_new_for_address().
6790 * Note that the returned #GDBusConnection object will (usually) have
6791 * the #GDBusConnection:exit-on-close property set to %TRUE.
6793 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6798 g_bus_get_finish (GAsyncResult *res,
6801 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
6803 GDBusConnection *ret;
6805 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6807 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
6811 if (g_simple_async_result_propagate_error (simple, error))
6814 object = g_simple_async_result_get_op_res_gpointer (simple);
6815 g_assert (object != NULL);
6816 ret = g_object_ref (G_DBUS_CONNECTION (object));
6822 /* ---------------------------------------------------------------------------------------------------- */