GLib 2.39.0
[glib.git] / gio / gdbusconnection.c
blob8a0748d2c4f17a71f66bf66ad3dd07581e370552
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>
24 * TODO for GDBus:
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
47 * distribution)
49 * - (ideally) this requires D-Bus spec work because none of
50 * this has never really been specced out properly (except
51 * the X11 bits)
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
65 * libX11 from libgio.
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
76 * like this:
78 * 3 -> /proc/18068/fd
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
101 * or similar.
104 #include "config.h"
106 #include <stdlib.h>
107 #include <string.h>
108 #include <sys/types.h>
109 #ifdef HAVE_UNISTD_H
110 #include <unistd.h>
111 #endif
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"
130 #ifdef G_OS_UNIX
131 #include "gunixconnection.h"
132 #include "gunixfdmessage.h"
133 #endif
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 * As an exception to the usual GLib rule that a particular object must not be
152 * used by two threads at the same time, #GDBusConnection's methods may be
153 * called from any thread<footnote>
154 * <para>
155 * This is so that g_bus_get() and g_bus_get_sync() can safely return the
156 * same #GDBusConnection when called from any thread.
157 * </para>
158 * </footnote>.
160 * Most of the ways to obtain a #GDBusConnection automatically initialize it
161 * (i.e. connect to D-Bus): for instance, g_dbus_connection_new() and
162 * g_bus_get(), and the synchronous versions of those methods, give you an
163 * initialized connection. Language bindings for GIO should use
164 * g_initable_new() or g_async_initable_new_async(), which also initialize the
165 * connection.
167 * If you construct an uninitialized #GDBusConnection, such as via
168 * g_object_new(), you must initialize it via g_initable_init() or
169 * g_async_initable_init_async() before using its methods or properties.
170 * Calling methods or accessing properties on a #GDBusConnection that has not
171 * completed initialization successfully is considered to be invalid, and leads
172 * to undefined behaviour. In particular, if initialization fails with a
173 * #GError, the only valid thing you can do with that #GDBusConnection is to
174 * free it with g_object_unref().
176 * <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>
178 * <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>
180 * <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>
182 * <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>
185 /* ---------------------------------------------------------------------------------------------------- */
187 typedef struct _GDBusConnectionClass GDBusConnectionClass;
190 * GDBusConnectionClass:
191 * @closed: Signal class handler for the #GDBusConnection::closed signal.
193 * Class structure for #GDBusConnection.
195 * Since: 2.26
197 struct _GDBusConnectionClass
199 /*< private >*/
200 GObjectClass parent_class;
202 /*< public >*/
203 /* Signals */
204 void (*closed) (GDBusConnection *connection,
205 gboolean remote_peer_vanished,
206 GError *error);
209 G_LOCK_DEFINE_STATIC (message_bus_lock);
211 static GWeakRef the_session_bus;
212 static GWeakRef the_system_bus;
214 /* Extra pseudo-member of GDBusSendMessageFlags.
215 * Set by initable_init() to indicate that despite not being initialized yet,
216 * enough of the only-valid-after-init members are set that we can send a
217 * message, and we're being called from its thread, so no memory barrier is
218 * required before accessing them.
220 #define SEND_MESSAGE_FLAGS_INITIALIZING (1<<31)
222 /* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
223 #define CALL_FLAGS_INITIALIZING (1<<31)
225 /* ---------------------------------------------------------------------------------------------------- */
227 typedef struct
229 GDestroyNotify callback;
230 gpointer user_data;
231 GMainContext *context;
232 } CallDestroyNotifyData;
234 static gboolean
235 call_destroy_notify_data_in_idle (gpointer user_data)
237 CallDestroyNotifyData *data = user_data;
238 data->callback (data->user_data);
239 return FALSE;
242 static void
243 call_destroy_notify_data_free (CallDestroyNotifyData *data)
245 if (data->context != NULL)
246 g_main_context_unref (data->context);
247 g_free (data);
251 * call_destroy_notify: <internal>
252 * @context: (allow-none): A #GMainContext or %NULL.
253 * @callback: (allow-none): A #GDestroyNotify or %NULL.
254 * @user_data: Data to pass to @callback.
256 * Schedules @callback to run in @context.
258 static void
259 call_destroy_notify (GMainContext *context,
260 GDestroyNotify callback,
261 gpointer user_data)
263 GSource *idle_source;
264 CallDestroyNotifyData *data;
266 if (callback == NULL)
267 goto out;
269 data = g_new0 (CallDestroyNotifyData, 1);
270 data->callback = callback;
271 data->user_data = user_data;
272 data->context = context;
273 if (data->context != NULL)
274 g_main_context_ref (data->context);
276 idle_source = g_idle_source_new ();
277 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
278 g_source_set_callback (idle_source,
279 call_destroy_notify_data_in_idle,
280 data,
281 (GDestroyNotify) call_destroy_notify_data_free);
282 g_source_attach (idle_source, data->context);
283 g_source_unref (idle_source);
285 out:
289 /* ---------------------------------------------------------------------------------------------------- */
291 static gboolean
292 _g_strv_has_string (const gchar* const *haystack,
293 const gchar *needle)
295 guint n;
297 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
299 if (g_strcmp0 (haystack[n], needle) == 0)
300 return TRUE;
302 return FALSE;
305 /* ---------------------------------------------------------------------------------------------------- */
307 #ifdef G_OS_WIN32
308 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
309 #else
310 // TODO: for some reason this doesn't work on Windows
311 #define CONNECTION_ENSURE_LOCK(obj) do { \
312 if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock))) \
314 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
315 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
317 } while (FALSE)
318 #endif
320 #define CONNECTION_LOCK(obj) do { \
321 g_mutex_lock (&(obj)->lock); \
322 } while (FALSE)
324 #define CONNECTION_UNLOCK(obj) do { \
325 g_mutex_unlock (&(obj)->lock); \
326 } while (FALSE)
328 /* Flags in connection->atomic_flags */
329 enum {
330 FLAG_INITIALIZED = 1 << 0,
331 FLAG_EXIT_ON_CLOSE = 1 << 1,
332 FLAG_CLOSED = 1 << 2
336 * GDBusConnection:
338 * The #GDBusConnection structure contains only private data and
339 * should only be accessed using the provided API.
341 * Since: 2.26
343 struct _GDBusConnection
345 /*< private >*/
346 GObject parent_instance;
348 /* ------------------------------------------------------------------------ */
349 /* -- General object state ------------------------------------------------ */
350 /* ------------------------------------------------------------------------ */
352 /* General-purpose lock for most fields */
353 GMutex lock;
355 /* A lock used in the init() method of the GInitable interface - see comments
356 * in initable_init() for why a separate lock is needed.
358 * If you need both @lock and @init_lock, you must take @init_lock first.
360 GMutex init_lock;
362 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
363 * someone calls org.freedesktop.DBus.GetMachineId(). Protected by @lock.
365 gchar *machine_id;
367 /* The underlying stream used for communication
368 * Read-only after initable_init(), so it may be read if you either
369 * hold @init_lock or check for initialization first.
371 GIOStream *stream;
373 /* The object used for authentication (if any).
374 * Read-only after initable_init(), so it may be read if you either
375 * hold @init_lock or check for initialization first.
377 GDBusAuth *auth;
379 /* Last serial used. Protected by @lock. */
380 guint32 last_serial;
382 /* The object used to send/receive messages.
383 * Read-only after initable_init(), so it may be read if you either
384 * hold @init_lock or check for initialization first.
386 GDBusWorker *worker;
388 /* If connected to a message bus, this contains the unique name assigned to
389 * us by the bus (e.g. ":1.42").
390 * Read-only after initable_init(), so it may be read if you either
391 * hold @init_lock or check for initialization first.
393 gchar *bus_unique_name;
395 /* The GUID returned by the other side if we authenticed as a client or
396 * the GUID to use if authenticating as a server.
397 * Read-only after initable_init(), so it may be read if you either
398 * hold @init_lock or check for initialization first.
400 gchar *guid;
402 /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
403 * Inspect @initialization_error to see whether it succeeded or failed.
405 * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
407 * FLAG_CLOSED is the closed property. It may be read at any time, but
408 * may only be written while holding @lock.
410 volatile gint atomic_flags;
412 /* If the connection could not be established during initable_init(),
413 * this GError will be set.
414 * Read-only after initable_init(), so it may be read if you either
415 * hold @init_lock or check for initialization first.
417 GError *initialization_error;
419 /* The result of g_main_context_ref_thread_default() when the object
420 * was created (the GObject _init() function) - this is used for delivery
421 * of the :closed GObject signal.
423 * Only set in the GObject init function, so no locks are needed.
425 GMainContext *main_context_at_construction;
427 /* Read-only construct properties, no locks needed */
428 gchar *address;
429 GDBusConnectionFlags flags;
431 /* Map used for managing method replies, protected by @lock */
432 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
434 /* Maps used for managing signal subscription, protected by @lock */
435 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
436 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
437 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
439 /* Maps used for managing exported objects and subtrees,
440 * protected by @lock
442 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
443 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
444 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
445 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
447 /* Map used for storing last used serials for each thread, protected by @lock */
448 GHashTable *map_thread_to_last_serial;
450 /* Structure used for message filters, protected by @lock */
451 GPtrArray *filters;
453 /* Capabilities negotiated during authentication
454 * Read-only after initable_init(), so it may be read without holding a
455 * lock, if you check for initialization first.
457 GDBusCapabilityFlags capabilities;
459 /* Protected by @init_lock */
460 GDBusAuthObserver *authentication_observer;
462 /* Read-only after initable_init(), so it may be read if you either
463 * hold @init_lock or check for initialization first.
465 GCredentials *credentials;
467 /* set to TRUE when finalizing */
468 gboolean finalizing;
471 typedef struct ExportedObject ExportedObject;
472 static void exported_object_free (ExportedObject *eo);
474 typedef struct ExportedSubtree ExportedSubtree;
475 static void exported_subtree_free (ExportedSubtree *es);
477 enum
479 CLOSED_SIGNAL,
480 LAST_SIGNAL,
483 enum
485 PROP_0,
486 PROP_STREAM,
487 PROP_ADDRESS,
488 PROP_FLAGS,
489 PROP_GUID,
490 PROP_UNIQUE_NAME,
491 PROP_CLOSED,
492 PROP_EXIT_ON_CLOSE,
493 PROP_CAPABILITY_FLAGS,
494 PROP_AUTHENTICATION_OBSERVER,
497 static void distribute_signals (GDBusConnection *connection,
498 GDBusMessage *message);
500 static void distribute_method_call (GDBusConnection *connection,
501 GDBusMessage *message);
503 static gboolean handle_generic_unlocked (GDBusConnection *connection,
504 GDBusMessage *message);
507 static void purge_all_signal_subscriptions (GDBusConnection *connection);
508 static void purge_all_filters (GDBusConnection *connection);
510 static void schedule_method_call (GDBusConnection *connection,
511 GDBusMessage *message,
512 guint registration_id,
513 guint subtree_registration_id,
514 const GDBusInterfaceInfo *interface_info,
515 const GDBusMethodInfo *method_info,
516 const GDBusPropertyInfo *property_info,
517 GVariant *parameters,
518 const GDBusInterfaceVTable *vtable,
519 GMainContext *main_context,
520 gpointer user_data);
522 #define _G_ENSURE_LOCK(name) do { \
523 if (G_UNLIKELY (G_TRYLOCK(name))) \
525 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
526 "_G_ENSURE_LOCK: Lock '" #name "' is not locked"); \
528 } while (FALSE) \
530 static guint signals[LAST_SIGNAL] = { 0 };
532 static void initable_iface_init (GInitableIface *initable_iface);
533 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
535 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
536 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
537 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
541 * Check that all members of @connection that can only be accessed after
542 * the connection is initialized can safely be accessed. If not,
543 * log a critical warning. This function is a memory barrier.
545 * Returns: %TRUE if initialized
547 static gboolean
548 check_initialized (GDBusConnection *connection)
550 /* The access to @atomic_flags isn't conditional, so that this function
551 * provides a memory barrier for thread-safety even if checks are disabled.
552 * (If you don't want this stricter guarantee, you can call
553 * g_return_if_fail (check_initialized (c)).)
555 * This isn't strictly necessary now that we've decided use of an
556 * uninitialized GDBusConnection is undefined behaviour, but it seems
557 * better to be as deterministic as is feasible.
559 * (Anything that could suffer a crash from seeing undefined values
560 * must have a race condition - thread A initializes the connection while
561 * thread B calls a method without initialization, hoping that thread A will
562 * win the race - so its behaviour is undefined anyway.)
564 gint flags = g_atomic_int_get (&connection->atomic_flags);
566 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
568 /* We can safely access this, due to the memory barrier above */
569 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
571 return TRUE;
574 typedef enum {
575 MAY_BE_UNINITIALIZED = (1<<1)
576 } CheckUnclosedFlags;
579 * Check the same thing as check_initialized(), and also that the
580 * connection is not closed. If the connection is uninitialized,
581 * raise a critical warning (it's programmer error); if it's closed,
582 * raise a recoverable GError (it's a runtime error).
584 * This function is a memory barrier.
586 * Returns: %TRUE if initialized and not closed
588 static gboolean
589 check_unclosed (GDBusConnection *connection,
590 CheckUnclosedFlags check,
591 GError **error)
593 /* check_initialized() is effectively inlined, so we don't waste time
594 * doing two memory barriers
596 gint flags = g_atomic_int_get (&connection->atomic_flags);
598 if (!(check & MAY_BE_UNINITIALIZED))
600 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
601 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
604 if (flags & FLAG_CLOSED)
606 g_set_error_literal (error,
607 G_IO_ERROR,
608 G_IO_ERROR_CLOSED,
609 _("The connection is closed"));
610 return FALSE;
613 return TRUE;
616 static GHashTable *alive_connections = NULL;
618 static void
619 g_dbus_connection_dispose (GObject *object)
621 GDBusConnection *connection = G_DBUS_CONNECTION (object);
623 G_LOCK (message_bus_lock);
624 CONNECTION_LOCK (connection);
625 if (connection->worker != NULL)
627 _g_dbus_worker_stop (connection->worker);
628 connection->worker = NULL;
629 if (alive_connections != NULL)
630 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
632 else
634 if (alive_connections != NULL)
635 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
637 CONNECTION_UNLOCK (connection);
638 G_UNLOCK (message_bus_lock);
640 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
641 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
644 static void
645 g_dbus_connection_finalize (GObject *object)
647 GDBusConnection *connection = G_DBUS_CONNECTION (object);
649 connection->finalizing = TRUE;
651 purge_all_signal_subscriptions (connection);
653 purge_all_filters (connection);
654 g_ptr_array_unref (connection->filters);
656 if (connection->authentication_observer != NULL)
657 g_object_unref (connection->authentication_observer);
659 if (connection->auth != NULL)
660 g_object_unref (connection->auth);
662 if (connection->credentials)
663 g_object_unref (connection->credentials);
665 if (connection->stream != NULL)
667 g_object_unref (connection->stream);
668 connection->stream = NULL;
671 g_free (connection->address);
673 g_free (connection->guid);
674 g_free (connection->bus_unique_name);
676 if (connection->initialization_error != NULL)
677 g_error_free (connection->initialization_error);
679 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
681 g_hash_table_unref (connection->map_rule_to_signal_data);
682 g_hash_table_unref (connection->map_id_to_signal_data);
683 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
685 g_hash_table_unref (connection->map_id_to_ei);
686 g_hash_table_unref (connection->map_object_path_to_eo);
687 g_hash_table_unref (connection->map_id_to_es);
688 g_hash_table_unref (connection->map_object_path_to_es);
690 g_hash_table_unref (connection->map_thread_to_last_serial);
692 g_main_context_unref (connection->main_context_at_construction);
694 g_free (connection->machine_id);
696 g_mutex_clear (&connection->init_lock);
697 g_mutex_clear (&connection->lock);
699 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
702 /* called in any user thread, with the connection's lock not held */
703 static void
704 g_dbus_connection_get_property (GObject *object,
705 guint prop_id,
706 GValue *value,
707 GParamSpec *pspec)
709 GDBusConnection *connection = G_DBUS_CONNECTION (object);
711 switch (prop_id)
713 case PROP_STREAM:
714 g_value_set_object (value, g_dbus_connection_get_stream (connection));
715 break;
717 case PROP_GUID:
718 g_value_set_string (value, g_dbus_connection_get_guid (connection));
719 break;
721 case PROP_UNIQUE_NAME:
722 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
723 break;
725 case PROP_CLOSED:
726 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
727 break;
729 case PROP_EXIT_ON_CLOSE:
730 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
731 break;
733 case PROP_CAPABILITY_FLAGS:
734 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
735 break;
737 default:
738 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
739 break;
743 /* called in any user thread, with the connection's lock not held */
744 static void
745 g_dbus_connection_set_property (GObject *object,
746 guint prop_id,
747 const GValue *value,
748 GParamSpec *pspec)
750 GDBusConnection *connection = G_DBUS_CONNECTION (object);
752 switch (prop_id)
754 case PROP_STREAM:
755 connection->stream = g_value_dup_object (value);
756 break;
758 case PROP_GUID:
759 connection->guid = g_value_dup_string (value);
760 break;
762 case PROP_ADDRESS:
763 connection->address = g_value_dup_string (value);
764 break;
766 case PROP_FLAGS:
767 connection->flags = g_value_get_flags (value);
768 break;
770 case PROP_EXIT_ON_CLOSE:
771 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
772 break;
774 case PROP_AUTHENTICATION_OBSERVER:
775 connection->authentication_observer = g_value_dup_object (value);
776 break;
778 default:
779 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
780 break;
784 /* Base-class implementation of GDBusConnection::closed.
786 * Called in a user thread, by the main context that was thread-default when
787 * the object was constructed.
789 static void
790 g_dbus_connection_real_closed (GDBusConnection *connection,
791 gboolean remote_peer_vanished,
792 GError *error)
794 gint flags = g_atomic_int_get (&connection->atomic_flags);
796 /* Because atomic int access is a memory barrier, we can safely read
797 * initialization_error without a lock, as long as we do it afterwards.
799 if (remote_peer_vanished &&
800 (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
801 (flags & FLAG_INITIALIZED) != 0 &&
802 connection->initialization_error == NULL)
804 if (error != NULL)
806 g_print ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
807 G_STRFUNC,
808 error->message,
809 g_quark_to_string (error->domain), error->code);
811 else
813 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
815 raise (SIGTERM);
819 static void
820 g_dbus_connection_class_init (GDBusConnectionClass *klass)
822 GObjectClass *gobject_class;
824 gobject_class = G_OBJECT_CLASS (klass);
826 gobject_class->finalize = g_dbus_connection_finalize;
827 gobject_class->dispose = g_dbus_connection_dispose;
828 gobject_class->set_property = g_dbus_connection_set_property;
829 gobject_class->get_property = g_dbus_connection_get_property;
831 klass->closed = g_dbus_connection_real_closed;
834 * GDBusConnection:stream:
836 * The underlying #GIOStream used for I/O.
838 * If this is passed on construction and is a #GSocketConnection,
839 * then the corresponding #GSocket will be put into non-blocking mode.
841 * While the #GDBusConnection is active, it will interact with this
842 * stream from a worker thread, so it is not safe to interact with
843 * the stream directly.
845 * Since: 2.26
847 g_object_class_install_property (gobject_class,
848 PROP_STREAM,
849 g_param_spec_object ("stream",
850 P_("IO Stream"),
851 P_("The underlying streams used for I/O"),
852 G_TYPE_IO_STREAM,
853 G_PARAM_READABLE |
854 G_PARAM_WRITABLE |
855 G_PARAM_CONSTRUCT_ONLY |
856 G_PARAM_STATIC_NAME |
857 G_PARAM_STATIC_BLURB |
858 G_PARAM_STATIC_NICK));
861 * GDBusConnection:address:
863 * A D-Bus address specifying potential endpoints that can be used
864 * when establishing the connection.
866 * Since: 2.26
868 g_object_class_install_property (gobject_class,
869 PROP_ADDRESS,
870 g_param_spec_string ("address",
871 P_("Address"),
872 P_("D-Bus address specifying potential socket endpoints"),
873 NULL,
874 G_PARAM_WRITABLE |
875 G_PARAM_CONSTRUCT_ONLY |
876 G_PARAM_STATIC_NAME |
877 G_PARAM_STATIC_BLURB |
878 G_PARAM_STATIC_NICK));
881 * GDBusConnection:flags:
883 * Flags from the #GDBusConnectionFlags enumeration.
885 * Since: 2.26
887 g_object_class_install_property (gobject_class,
888 PROP_FLAGS,
889 g_param_spec_flags ("flags",
890 P_("Flags"),
891 P_("Flags"),
892 G_TYPE_DBUS_CONNECTION_FLAGS,
893 G_DBUS_CONNECTION_FLAGS_NONE,
894 G_PARAM_WRITABLE |
895 G_PARAM_CONSTRUCT_ONLY |
896 G_PARAM_STATIC_NAME |
897 G_PARAM_STATIC_BLURB |
898 G_PARAM_STATIC_NICK));
901 * GDBusConnection:guid:
903 * The GUID of the peer performing the role of server when
904 * authenticating.
906 * If you are constructing a #GDBusConnection and pass
907 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
908 * #GDBusConnection:flags property then you MUST also set this
909 * property to a valid guid.
911 * If you are constructing a #GDBusConnection and pass
912 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
913 * #GDBusConnection:flags property you will be able to read the GUID
914 * of the other peer here after the connection has been successfully
915 * initialized.
917 * Since: 2.26
919 g_object_class_install_property (gobject_class,
920 PROP_GUID,
921 g_param_spec_string ("guid",
922 P_("GUID"),
923 P_("GUID of the server peer"),
924 NULL,
925 G_PARAM_READABLE |
926 G_PARAM_WRITABLE |
927 G_PARAM_CONSTRUCT_ONLY |
928 G_PARAM_STATIC_NAME |
929 G_PARAM_STATIC_BLURB |
930 G_PARAM_STATIC_NICK));
933 * GDBusConnection:unique-name:
935 * The unique name as assigned by the message bus or %NULL if the
936 * connection is not open or not a message bus connection.
938 * Since: 2.26
940 g_object_class_install_property (gobject_class,
941 PROP_UNIQUE_NAME,
942 g_param_spec_string ("unique-name",
943 P_("unique-name"),
944 P_("Unique name of bus connection"),
945 NULL,
946 G_PARAM_READABLE |
947 G_PARAM_STATIC_NAME |
948 G_PARAM_STATIC_BLURB |
949 G_PARAM_STATIC_NICK));
952 * GDBusConnection:closed:
954 * A boolean specifying whether the connection has been closed.
956 * Since: 2.26
958 g_object_class_install_property (gobject_class,
959 PROP_CLOSED,
960 g_param_spec_boolean ("closed",
961 P_("Closed"),
962 P_("Whether the connection is closed"),
963 FALSE,
964 G_PARAM_READABLE |
965 G_PARAM_STATIC_NAME |
966 G_PARAM_STATIC_BLURB |
967 G_PARAM_STATIC_NICK));
970 * GDBusConnection:exit-on-close:
972 * A boolean specifying whether the process will be terminated (by
973 * calling <literal>raise(SIGTERM)</literal>) if the connection
974 * is closed by the remote peer.
976 * Note that #GDBusConnection objects returned by g_bus_get_finish() and
977 * g_bus_get_sync() will (usually) have this property set to %TRUE.
979 * Since: 2.26
981 g_object_class_install_property (gobject_class,
982 PROP_EXIT_ON_CLOSE,
983 g_param_spec_boolean ("exit-on-close",
984 P_("Exit on close"),
985 P_("Whether the process is terminated when the connection is closed"),
986 FALSE,
987 G_PARAM_READABLE |
988 G_PARAM_WRITABLE |
989 G_PARAM_STATIC_NAME |
990 G_PARAM_STATIC_BLURB |
991 G_PARAM_STATIC_NICK));
994 * GDBusConnection:capabilities:
996 * Flags from the #GDBusCapabilityFlags enumeration
997 * representing connection features negotiated with the other peer.
999 * Since: 2.26
1001 g_object_class_install_property (gobject_class,
1002 PROP_CAPABILITY_FLAGS,
1003 g_param_spec_flags ("capabilities",
1004 P_("Capabilities"),
1005 P_("Capabilities"),
1006 G_TYPE_DBUS_CAPABILITY_FLAGS,
1007 G_DBUS_CAPABILITY_FLAGS_NONE,
1008 G_PARAM_READABLE |
1009 G_PARAM_STATIC_NAME |
1010 G_PARAM_STATIC_BLURB |
1011 G_PARAM_STATIC_NICK));
1014 * GDBusConnection:authentication-observer:
1016 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
1018 * Since: 2.26
1020 g_object_class_install_property (gobject_class,
1021 PROP_AUTHENTICATION_OBSERVER,
1022 g_param_spec_object ("authentication-observer",
1023 P_("Authentication Observer"),
1024 P_("Object used to assist in the authentication process"),
1025 G_TYPE_DBUS_AUTH_OBSERVER,
1026 G_PARAM_WRITABLE |
1027 G_PARAM_CONSTRUCT_ONLY |
1028 G_PARAM_STATIC_NAME |
1029 G_PARAM_STATIC_BLURB |
1030 G_PARAM_STATIC_NICK));
1033 * GDBusConnection::closed:
1034 * @connection: The #GDBusConnection emitting the signal.
1035 * @remote_peer_vanished: %TRUE if @connection is closed because the
1036 * remote peer closed its end of the connection.
1037 * @error: (allow-none): A #GError with more details about the event or %NULL.
1039 * Emitted when the connection is closed.
1041 * The cause of this event can be
1042 * <itemizedlist>
1043 * <listitem><para>
1044 * If g_dbus_connection_close() is called. In this case
1045 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
1046 * </para></listitem>
1047 * <listitem><para>
1048 * If the remote peer closes the connection. In this case
1049 * @remote_peer_vanished is set to %TRUE and @error is set.
1050 * </para></listitem>
1051 * <listitem><para>
1052 * If the remote peer sends invalid or malformed data. In this
1053 * case @remote_peer_vanished is set to %FALSE and @error
1054 * is set.
1055 * </para></listitem>
1056 * </itemizedlist>
1058 * Upon receiving this signal, you should give up your reference to
1059 * @connection. You are guaranteed that this signal is emitted only
1060 * once.
1062 * Since: 2.26
1064 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
1065 G_TYPE_DBUS_CONNECTION,
1066 G_SIGNAL_RUN_LAST,
1067 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1068 NULL,
1069 NULL,
1070 NULL,
1071 G_TYPE_NONE,
1073 G_TYPE_BOOLEAN,
1074 G_TYPE_ERROR);
1077 static void
1078 g_dbus_connection_init (GDBusConnection *connection)
1080 g_mutex_init (&connection->lock);
1081 g_mutex_init (&connection->init_lock);
1083 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
1085 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1086 g_str_equal);
1087 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1088 g_direct_equal);
1089 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1090 g_str_equal,
1091 g_free,
1092 (GDestroyNotify) g_ptr_array_unref);
1094 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1095 g_str_equal,
1096 NULL,
1097 (GDestroyNotify) exported_object_free);
1099 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1100 g_direct_equal);
1102 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1103 g_str_equal,
1104 NULL,
1105 (GDestroyNotify) exported_subtree_free);
1107 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1108 g_direct_equal);
1110 connection->map_thread_to_last_serial = g_hash_table_new (g_direct_hash,
1111 g_direct_equal);
1113 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1115 connection->filters = g_ptr_array_new ();
1119 * g_dbus_connection_get_stream:
1120 * @connection: a #GDBusConnection
1122 * Gets the underlying stream used for IO.
1124 * While the #GDBusConnection is active, it will interact with this
1125 * stream from a worker thread, so it is not safe to interact with
1126 * the stream directly.
1128 * Returns: (transfer none): the stream used for IO
1130 * Since: 2.26
1132 GIOStream *
1133 g_dbus_connection_get_stream (GDBusConnection *connection)
1135 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1137 /* do not use g_return_val_if_fail(), we want the memory barrier */
1138 if (!check_initialized (connection))
1139 return NULL;
1141 return connection->stream;
1145 * g_dbus_connection_start_message_processing:
1146 * @connection: A #GDBusConnection.
1148 * If @connection was created with
1149 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1150 * starts processing messages. Does nothing on if @connection wasn't
1151 * created with this flag or if the method has already been called.
1153 * Since: 2.26
1155 void
1156 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1158 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1160 /* do not use g_return_val_if_fail(), we want the memory barrier */
1161 if (!check_initialized (connection))
1162 return;
1164 g_assert (connection->worker != NULL);
1165 _g_dbus_worker_unfreeze (connection->worker);
1169 * g_dbus_connection_is_closed:
1170 * @connection: A #GDBusConnection.
1172 * Gets whether @connection is closed.
1174 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
1176 * Since: 2.26
1178 gboolean
1179 g_dbus_connection_is_closed (GDBusConnection *connection)
1181 gint flags;
1183 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1185 flags = g_atomic_int_get (&connection->atomic_flags);
1187 return (flags & FLAG_CLOSED) ? TRUE : FALSE;
1191 * g_dbus_connection_get_capabilities:
1192 * @connection: A #GDBusConnection.
1194 * Gets the capabilities negotiated with the remote peer
1196 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
1198 * Since: 2.26
1200 GDBusCapabilityFlags
1201 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1203 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1205 /* do not use g_return_val_if_fail(), we want the memory barrier */
1206 if (!check_initialized (connection))
1207 return G_DBUS_CAPABILITY_FLAGS_NONE;
1209 return connection->capabilities;
1212 /* ---------------------------------------------------------------------------------------------------- */
1214 /* Called in a temporary thread without holding locks. */
1215 static void
1216 flush_in_thread_func (GSimpleAsyncResult *res,
1217 GObject *object,
1218 GCancellable *cancellable)
1220 GError *error;
1222 error = NULL;
1223 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1224 cancellable,
1225 &error))
1226 g_simple_async_result_take_error (res, error);
1230 * g_dbus_connection_flush:
1231 * @connection: A #GDBusConnection.
1232 * @cancellable: (allow-none): A #GCancellable or %NULL.
1233 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1234 * satisfied or %NULL if you don't care about the result.
1235 * @user_data: The data to pass to @callback.
1237 * Asynchronously flushes @connection, that is, writes all queued
1238 * outgoing message to the transport and then flushes the transport
1239 * (using g_output_stream_flush_async()). This is useful in programs
1240 * that wants to emit a D-Bus signal and then exit
1241 * immediately. Without flushing the connection, there is no guarantee
1242 * that the message has been sent to the networking buffers in the OS
1243 * kernel.
1245 * This is an asynchronous method. When the operation is finished,
1246 * @callback will be invoked in the <link
1247 * linkend="g-main-context-push-thread-default">thread-default main
1248 * loop</link> of the thread you are calling this method from. You can
1249 * then call g_dbus_connection_flush_finish() to get the result of the
1250 * operation. See g_dbus_connection_flush_sync() for the synchronous
1251 * version.
1253 * Since: 2.26
1255 void
1256 g_dbus_connection_flush (GDBusConnection *connection,
1257 GCancellable *cancellable,
1258 GAsyncReadyCallback callback,
1259 gpointer user_data)
1261 GSimpleAsyncResult *simple;
1263 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1265 simple = g_simple_async_result_new (G_OBJECT (connection),
1266 callback,
1267 user_data,
1268 g_dbus_connection_flush);
1269 g_simple_async_result_set_check_cancellable (simple, cancellable);
1270 g_simple_async_result_run_in_thread (simple,
1271 flush_in_thread_func,
1272 G_PRIORITY_DEFAULT,
1273 cancellable);
1274 g_object_unref (simple);
1278 * g_dbus_connection_flush_finish:
1279 * @connection: A #GDBusConnection.
1280 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_flush().
1281 * @error: Return location for error or %NULL.
1283 * Finishes an operation started with g_dbus_connection_flush().
1285 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1287 * Since: 2.26
1289 gboolean
1290 g_dbus_connection_flush_finish (GDBusConnection *connection,
1291 GAsyncResult *res,
1292 GError **error)
1294 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1295 gboolean ret;
1297 ret = FALSE;
1299 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1300 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1301 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1303 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1305 if (g_simple_async_result_propagate_error (simple, error))
1306 goto out;
1308 ret = TRUE;
1310 out:
1311 return ret;
1315 * g_dbus_connection_flush_sync:
1316 * @connection: A #GDBusConnection.
1317 * @cancellable: (allow-none): A #GCancellable or %NULL.
1318 * @error: Return location for error or %NULL.
1320 * Synchronously flushes @connection. The calling thread is blocked
1321 * until this is done. See g_dbus_connection_flush() for the
1322 * asynchronous version of this method and more details about what it
1323 * does.
1325 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1327 * Since: 2.26
1329 gboolean
1330 g_dbus_connection_flush_sync (GDBusConnection *connection,
1331 GCancellable *cancellable,
1332 GError **error)
1334 gboolean ret;
1336 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1337 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1339 ret = FALSE;
1341 /* This is only a best-effort attempt to see whether the connection is
1342 * closed, so it doesn't need the lock. If the connection closes just
1343 * after this check, but before scheduling the flush operation, the
1344 * result will be more or less the same as if the connection closed while
1345 * the flush operation was pending - it'll fail with either CLOSED or
1346 * CANCELLED.
1348 if (!check_unclosed (connection, 0, error))
1349 goto out;
1351 g_assert (connection->worker != NULL);
1353 ret = _g_dbus_worker_flush_sync (connection->worker,
1354 cancellable,
1355 error);
1357 out:
1358 return ret;
1361 /* ---------------------------------------------------------------------------------------------------- */
1363 typedef struct
1365 GDBusConnection *connection;
1366 GError *error;
1367 gboolean remote_peer_vanished;
1368 } EmitClosedData;
1370 static void
1371 emit_closed_data_free (EmitClosedData *data)
1373 g_object_unref (data->connection);
1374 if (data->error != NULL)
1375 g_error_free (data->error);
1376 g_free (data);
1379 /* Called in a user thread that has acquired the main context that was
1380 * thread-default when the object was constructed
1382 static gboolean
1383 emit_closed_in_idle (gpointer user_data)
1385 EmitClosedData *data = user_data;
1386 gboolean result;
1388 g_object_notify (G_OBJECT (data->connection), "closed");
1389 g_signal_emit (data->connection,
1390 signals[CLOSED_SIGNAL],
1392 data->remote_peer_vanished,
1393 data->error,
1394 &result);
1395 return FALSE;
1398 /* Can be called from any thread, must hold lock.
1399 * FLAG_CLOSED must already have been set.
1401 static void
1402 schedule_closed_unlocked (GDBusConnection *connection,
1403 gboolean remote_peer_vanished,
1404 GError *error)
1406 GSource *idle_source;
1407 EmitClosedData *data;
1409 CONNECTION_ENSURE_LOCK (connection);
1411 data = g_new0 (EmitClosedData, 1);
1412 data->connection = g_object_ref (connection);
1413 data->remote_peer_vanished = remote_peer_vanished;
1414 data->error = error != NULL ? g_error_copy (error) : NULL;
1416 idle_source = g_idle_source_new ();
1417 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1418 g_source_set_callback (idle_source,
1419 emit_closed_in_idle,
1420 data,
1421 (GDestroyNotify) emit_closed_data_free);
1422 g_source_attach (idle_source, connection->main_context_at_construction);
1423 g_source_unref (idle_source);
1426 /* ---------------------------------------------------------------------------------------------------- */
1429 * g_dbus_connection_close:
1430 * @connection: A #GDBusConnection.
1431 * @cancellable: (allow-none): A #GCancellable or %NULL.
1432 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1433 * satisfied or %NULL if you don't care about the result.
1434 * @user_data: The data to pass to @callback.
1436 * Closes @connection. Note that this never causes the process to
1437 * exit (this might only happen if the other end of a shared message
1438 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1440 * Once the connection is closed, operations such as sending a message
1441 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1442 * will not automatically flush the connection so queued messages may
1443 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1445 * If @connection is already closed, this method fails with
1446 * %G_IO_ERROR_CLOSED.
1448 * When @connection has been closed, the #GDBusConnection::closed
1449 * signal is emitted in the <link
1450 * linkend="g-main-context-push-thread-default">thread-default main
1451 * loop</link> of the thread that @connection was constructed in.
1453 * This is an asynchronous method. When the operation is finished,
1454 * @callback will be invoked in the <link
1455 * linkend="g-main-context-push-thread-default">thread-default main
1456 * loop</link> of the thread you are calling this method from. You can
1457 * then call g_dbus_connection_close_finish() to get the result of the
1458 * operation. See g_dbus_connection_close_sync() for the synchronous
1459 * version.
1461 * Since: 2.26
1463 void
1464 g_dbus_connection_close (GDBusConnection *connection,
1465 GCancellable *cancellable,
1466 GAsyncReadyCallback callback,
1467 gpointer user_data)
1469 GSimpleAsyncResult *simple;
1471 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1473 /* do not use g_return_val_if_fail(), we want the memory barrier */
1474 if (!check_initialized (connection))
1475 return;
1477 g_assert (connection->worker != NULL);
1479 simple = g_simple_async_result_new (G_OBJECT (connection),
1480 callback,
1481 user_data,
1482 g_dbus_connection_close);
1483 g_simple_async_result_set_check_cancellable (simple, cancellable);
1484 _g_dbus_worker_close (connection->worker, cancellable, simple);
1485 g_object_unref (simple);
1489 * g_dbus_connection_close_finish:
1490 * @connection: A #GDBusConnection.
1491 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_close().
1492 * @error: Return location for error or %NULL.
1494 * Finishes an operation started with g_dbus_connection_close().
1496 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1498 * Since: 2.26
1500 gboolean
1501 g_dbus_connection_close_finish (GDBusConnection *connection,
1502 GAsyncResult *res,
1503 GError **error)
1505 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1506 gboolean ret;
1508 ret = FALSE;
1510 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1511 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1512 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1514 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1516 if (g_simple_async_result_propagate_error (simple, error))
1517 goto out;
1519 ret = TRUE;
1521 out:
1522 return ret;
1525 typedef struct {
1526 GMainLoop *loop;
1527 GAsyncResult *result;
1528 } SyncCloseData;
1530 /* Can be called by any thread, without the connection lock */
1531 static void
1532 sync_close_cb (GObject *source_object,
1533 GAsyncResult *res,
1534 gpointer user_data)
1536 SyncCloseData *data = user_data;
1538 data->result = g_object_ref (res);
1539 g_main_loop_quit (data->loop);
1543 * g_dbus_connection_close_sync:
1544 * @connection: A #GDBusConnection.
1545 * @cancellable: (allow-none): A #GCancellable or %NULL.
1546 * @error: Return location for error or %NULL.
1548 * Synchronously closees @connection. The calling thread is blocked
1549 * until this is done. See g_dbus_connection_close() for the
1550 * asynchronous version of this method and more details about what it
1551 * does.
1553 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1555 * Since: 2.26
1557 gboolean
1558 g_dbus_connection_close_sync (GDBusConnection *connection,
1559 GCancellable *cancellable,
1560 GError **error)
1562 gboolean ret;
1564 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1565 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1567 ret = FALSE;
1569 if (check_unclosed (connection, 0, error))
1571 GMainContext *context;
1572 SyncCloseData data;
1574 context = g_main_context_new ();
1575 g_main_context_push_thread_default (context);
1576 data.loop = g_main_loop_new (context, TRUE);
1577 data.result = NULL;
1579 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1580 g_main_loop_run (data.loop);
1581 ret = g_dbus_connection_close_finish (connection, data.result, error);
1583 g_object_unref (data.result);
1584 g_main_loop_unref (data.loop);
1585 g_main_context_pop_thread_default (context);
1586 g_main_context_unref (context);
1589 return ret;
1592 /* ---------------------------------------------------------------------------------------------------- */
1595 * g_dbus_connection_get_last_serial:
1596 * @connection: A #GDBusConnection.
1598 * Retrieves the last serial number assigned to a #GDBusMessage on
1599 * the current thread. This includes messages sent via both low-level
1600 * API such as g_dbus_connection_send_message() as well as
1601 * high-level API such as g_dbus_connection_emit_signal(),
1602 * g_dbus_connection_call() or g_dbus_proxy_call().
1604 * Returns: the last used serial or zero when no message has been sent
1605 * within the current thread.
1607 * Since: 2.34
1609 guint32
1610 g_dbus_connection_get_last_serial (GDBusConnection *connection)
1612 guint32 ret;
1614 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
1616 CONNECTION_LOCK (connection);
1617 ret = GPOINTER_TO_UINT (g_hash_table_lookup (connection->map_thread_to_last_serial,
1618 g_thread_self ()));
1619 CONNECTION_UNLOCK (connection);
1621 return ret;
1624 /* ---------------------------------------------------------------------------------------------------- */
1626 /* Can be called by any thread, with the connection lock held */
1627 static gboolean
1628 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1629 GDBusMessage *message,
1630 GDBusSendMessageFlags flags,
1631 volatile guint32 *out_serial,
1632 GError **error)
1634 guchar *blob;
1635 gsize blob_size;
1636 guint32 serial_to_use;
1637 gboolean ret;
1639 CONNECTION_ENSURE_LOCK (connection);
1641 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1642 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1644 /* TODO: check all necessary headers are present */
1646 ret = FALSE;
1647 blob = NULL;
1649 if (out_serial != NULL)
1650 *out_serial = 0;
1652 /* If we're in initable_init(), don't check for being initialized, to avoid
1653 * chicken-and-egg problems. initable_init() is responsible for setting up
1654 * our prerequisites (mainly connection->worker), and only calling us
1655 * from its own thread (so no memory barrier is needed).
1657 if (!check_unclosed (connection,
1658 (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
1659 error))
1660 goto out;
1662 blob = g_dbus_message_to_blob (message,
1663 &blob_size,
1664 connection->capabilities,
1665 error);
1666 if (blob == NULL)
1667 goto out;
1669 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1670 serial_to_use = g_dbus_message_get_serial (message);
1671 else
1672 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1674 switch (blob[0])
1676 case 'l':
1677 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1678 break;
1679 case 'B':
1680 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1681 break;
1682 default:
1683 g_assert_not_reached ();
1684 break;
1687 #if 0
1688 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1689 blob_size, serial_to_use, connection);
1690 g_printerr ("----\n");
1691 hexdump (blob, blob_size);
1692 g_printerr ("----\n");
1693 #endif
1695 /* TODO: use connection->auth to encode the blob */
1697 if (out_serial != NULL)
1698 *out_serial = serial_to_use;
1700 /* store used serial for the current thread */
1701 /* TODO: watch the thread disposal and remove associated record
1702 * from hashtable
1703 * - see https://bugzilla.gnome.org/show_bug.cgi?id=676825#c7
1705 g_hash_table_replace (connection->map_thread_to_last_serial,
1706 g_thread_self (),
1707 GUINT_TO_POINTER (serial_to_use));
1709 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
1710 g_dbus_message_set_serial (message, serial_to_use);
1712 g_dbus_message_lock (message);
1713 _g_dbus_worker_send_message (connection->worker,
1714 message,
1715 (gchar*) blob,
1716 blob_size);
1717 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1719 ret = TRUE;
1721 out:
1722 g_free (blob);
1724 return ret;
1728 * g_dbus_connection_send_message:
1729 * @connection: A #GDBusConnection.
1730 * @message: A #GDBusMessage
1731 * @flags: Flags affecting how the message is sent.
1732 * @out_serial: (out) (allow-none): Return location for serial number assigned
1733 * to @message when sending it or %NULL.
1734 * @error: Return location for error or %NULL.
1736 * Asynchronously sends @message to the peer represented by @connection.
1738 * Unless @flags contain the
1739 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1740 * will be assigned by @connection and set on @message via
1741 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1742 * serial number used will be written to this location prior to
1743 * submitting the message to the underlying transport.
1745 * If @connection is closed then the operation will fail with
1746 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1747 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1749 * See <xref linkend="gdbus-server"/> and <xref
1750 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1751 * low-level API to send and receive UNIX file descriptors.
1753 * Note that @message must be unlocked, unless @flags contain the
1754 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1756 * Returns: %TRUE if the message was well-formed and queued for
1757 * transmission, %FALSE if @error is set.
1759 * Since: 2.26
1761 gboolean
1762 g_dbus_connection_send_message (GDBusConnection *connection,
1763 GDBusMessage *message,
1764 GDBusSendMessageFlags flags,
1765 volatile guint32 *out_serial,
1766 GError **error)
1768 gboolean ret;
1770 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1771 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1772 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1773 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1775 CONNECTION_LOCK (connection);
1776 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1777 CONNECTION_UNLOCK (connection);
1778 return ret;
1781 /* ---------------------------------------------------------------------------------------------------- */
1783 typedef struct
1785 volatile gint ref_count;
1786 GDBusConnection *connection;
1787 guint32 serial;
1788 GSimpleAsyncResult *simple;
1790 GMainContext *main_context;
1792 GCancellable *cancellable;
1794 gulong cancellable_handler_id;
1796 GSource *timeout_source;
1798 gboolean delivered;
1799 } SendMessageData;
1801 /* Can be called from any thread with or without lock held */
1802 static SendMessageData *
1803 send_message_data_ref (SendMessageData *data)
1805 g_atomic_int_inc (&data->ref_count);
1806 return data;
1809 /* Can be called from any thread with or without lock held */
1810 static void
1811 send_message_data_unref (SendMessageData *data)
1813 if (g_atomic_int_dec_and_test (&data->ref_count))
1815 g_assert (data->timeout_source == NULL);
1816 g_assert (data->simple == NULL);
1817 g_assert (data->cancellable_handler_id == 0);
1818 g_object_unref (data->connection);
1819 if (data->cancellable != NULL)
1820 g_object_unref (data->cancellable);
1821 g_main_context_unref (data->main_context);
1822 g_free (data);
1826 /* ---------------------------------------------------------------------------------------------------- */
1828 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1829 static void
1830 send_message_with_reply_deliver (SendMessageData *data, gboolean remove)
1832 CONNECTION_ENSURE_LOCK (data->connection);
1834 g_assert (!data->delivered);
1836 data->delivered = TRUE;
1838 g_simple_async_result_complete_in_idle (data->simple);
1839 g_object_unref (data->simple);
1840 data->simple = NULL;
1842 if (data->timeout_source != NULL)
1844 g_source_destroy (data->timeout_source);
1845 data->timeout_source = NULL;
1847 if (data->cancellable_handler_id > 0)
1849 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1850 data->cancellable_handler_id = 0;
1853 if (remove)
1855 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
1856 GUINT_TO_POINTER (data->serial)));
1859 send_message_data_unref (data);
1862 /* ---------------------------------------------------------------------------------------------------- */
1864 /* Can be called from any thread with lock held */
1865 static void
1866 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1867 GDBusMessage *reply)
1869 if (data->delivered)
1870 goto out;
1872 g_simple_async_result_set_op_res_gpointer (data->simple,
1873 g_object_ref (reply),
1874 g_object_unref);
1876 send_message_with_reply_deliver (data, TRUE);
1878 out:
1882 /* ---------------------------------------------------------------------------------------------------- */
1884 /* Called from a user thread, lock is not held */
1885 static gboolean
1886 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1888 SendMessageData *data = user_data;
1890 CONNECTION_LOCK (data->connection);
1891 if (data->delivered)
1892 goto out;
1894 g_simple_async_result_set_error (data->simple,
1895 G_IO_ERROR,
1896 G_IO_ERROR_CANCELLED,
1897 _("Operation was cancelled"));
1899 send_message_with_reply_deliver (data, TRUE);
1901 out:
1902 CONNECTION_UNLOCK (data->connection);
1903 return FALSE;
1906 /* Can be called from any thread with or without lock held */
1907 static void
1908 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1909 gpointer user_data)
1911 SendMessageData *data = user_data;
1912 GSource *idle_source;
1914 /* postpone cancellation to idle handler since we may be called directly
1915 * via g_cancellable_connect() (e.g. holding lock)
1917 idle_source = g_idle_source_new ();
1918 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1919 g_source_set_callback (idle_source,
1920 send_message_with_reply_cancelled_idle_cb,
1921 send_message_data_ref (data),
1922 (GDestroyNotify) send_message_data_unref);
1923 g_source_attach (idle_source, data->main_context);
1924 g_source_unref (idle_source);
1927 /* ---------------------------------------------------------------------------------------------------- */
1929 /* Called from a user thread, lock is not held */
1930 static gboolean
1931 send_message_with_reply_timeout_cb (gpointer user_data)
1933 SendMessageData *data = user_data;
1935 CONNECTION_LOCK (data->connection);
1936 if (data->delivered)
1937 goto out;
1939 g_simple_async_result_set_error (data->simple,
1940 G_IO_ERROR,
1941 G_IO_ERROR_TIMED_OUT,
1942 _("Timeout was reached"));
1944 send_message_with_reply_deliver (data, TRUE);
1946 out:
1947 CONNECTION_UNLOCK (data->connection);
1949 return FALSE;
1952 /* ---------------------------------------------------------------------------------------------------- */
1954 /* Called from a user thread, connection's lock is held */
1955 static void
1956 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1957 GDBusMessage *message,
1958 GDBusSendMessageFlags flags,
1959 gint timeout_msec,
1960 volatile guint32 *out_serial,
1961 GCancellable *cancellable,
1962 GAsyncReadyCallback callback,
1963 gpointer user_data)
1965 GSimpleAsyncResult *simple;
1966 SendMessageData *data;
1967 GError *error;
1968 volatile guint32 serial;
1970 data = NULL;
1972 if (out_serial == NULL)
1973 out_serial = &serial;
1975 if (timeout_msec == -1)
1976 timeout_msec = 25 * 1000;
1978 simple = g_simple_async_result_new (G_OBJECT (connection),
1979 callback,
1980 user_data,
1981 g_dbus_connection_send_message_with_reply);
1982 g_simple_async_result_set_check_cancellable (simple, cancellable);
1984 if (g_cancellable_is_cancelled (cancellable))
1986 g_simple_async_result_set_error (simple,
1987 G_IO_ERROR,
1988 G_IO_ERROR_CANCELLED,
1989 _("Operation was cancelled"));
1990 g_simple_async_result_complete_in_idle (simple);
1991 g_object_unref (simple);
1992 goto out;
1995 error = NULL;
1996 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1998 g_simple_async_result_take_error (simple, error);
1999 g_simple_async_result_complete_in_idle (simple);
2000 g_object_unref (simple);
2001 goto out;
2004 data = g_new0 (SendMessageData, 1);
2005 data->ref_count = 1;
2006 data->connection = g_object_ref (connection);
2007 data->simple = simple;
2008 data->serial = *out_serial;
2009 data->main_context = g_main_context_ref_thread_default ();
2011 if (cancellable != NULL)
2013 data->cancellable = g_object_ref (cancellable);
2014 data->cancellable_handler_id = g_cancellable_connect (cancellable,
2015 G_CALLBACK (send_message_with_reply_cancelled_cb),
2016 send_message_data_ref (data),
2017 (GDestroyNotify) send_message_data_unref);
2020 if (timeout_msec != G_MAXINT)
2022 data->timeout_source = g_timeout_source_new (timeout_msec);
2023 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
2024 g_source_set_callback (data->timeout_source,
2025 send_message_with_reply_timeout_cb,
2026 send_message_data_ref (data),
2027 (GDestroyNotify) send_message_data_unref);
2028 g_source_attach (data->timeout_source, data->main_context);
2029 g_source_unref (data->timeout_source);
2032 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
2033 GUINT_TO_POINTER (*out_serial),
2034 data);
2036 out:
2041 * g_dbus_connection_send_message_with_reply:
2042 * @connection: A #GDBusConnection.
2043 * @message: A #GDBusMessage.
2044 * @flags: Flags affecting how the message is sent.
2045 * @timeout_msec: The timeout in milliseconds, -1 to use the default
2046 * timeout or %G_MAXINT for no timeout.
2047 * @out_serial: (out) (allow-none): Return location for serial number assigned
2048 * to @message when sending it or %NULL.
2049 * @cancellable: (allow-none): A #GCancellable or %NULL.
2050 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
2051 * satisfied or %NULL if you don't care about the result.
2052 * @user_data: The data to pass to @callback.
2054 * Asynchronously sends @message to the peer represented by @connection.
2056 * Unless @flags contain the
2057 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2058 * will be assigned by @connection and set on @message via
2059 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2060 * serial number used will be written to this location prior to
2061 * submitting the message to the underlying transport.
2063 * If @connection is closed then the operation will fail with
2064 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2065 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2066 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2068 * This is an asynchronous method. When the operation is finished, @callback will be invoked
2069 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
2070 * of the thread you are calling this method from. You can then call
2071 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
2072 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
2074 * Note that @message must be unlocked, unless @flags contain the
2075 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2077 * See <xref linkend="gdbus-server"/> and <xref
2078 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2079 * low-level API to send and receive UNIX file descriptors.
2081 * Since: 2.26
2083 void
2084 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
2085 GDBusMessage *message,
2086 GDBusSendMessageFlags flags,
2087 gint timeout_msec,
2088 volatile guint32 *out_serial,
2089 GCancellable *cancellable,
2090 GAsyncReadyCallback callback,
2091 gpointer user_data)
2093 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2094 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2095 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2096 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2098 CONNECTION_LOCK (connection);
2099 g_dbus_connection_send_message_with_reply_unlocked (connection,
2100 message,
2101 flags,
2102 timeout_msec,
2103 out_serial,
2104 cancellable,
2105 callback,
2106 user_data);
2107 CONNECTION_UNLOCK (connection);
2111 * g_dbus_connection_send_message_with_reply_finish:
2112 * @connection: a #GDBusConnection
2113 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
2114 * @error: Return location for error or %NULL.
2116 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2118 * Note that @error is only set if a local in-process error
2119 * occurred. That is to say that the returned #GDBusMessage object may
2120 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2121 * g_dbus_message_to_gerror() to transcode this to a #GError.
2123 * See <xref linkend="gdbus-server"/> and <xref
2124 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2125 * low-level API to send and receive UNIX file descriptors.
2127 * Returns: (transfer full): A locked #GDBusMessage or %NULL if @error is set.
2129 * Since: 2.26
2131 GDBusMessage *
2132 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2133 GAsyncResult *res,
2134 GError **error)
2136 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2137 GDBusMessage *reply;
2139 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2140 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2142 reply = NULL;
2144 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
2146 if (g_simple_async_result_propagate_error (simple, error))
2147 goto out;
2149 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
2151 out:
2152 return reply;
2155 /* ---------------------------------------------------------------------------------------------------- */
2157 typedef struct
2159 GAsyncResult *res;
2160 GMainContext *context;
2161 GMainLoop *loop;
2162 } SendMessageSyncData;
2164 /* Called from a user thread, lock is not held */
2165 static void
2166 send_message_with_reply_sync_cb (GDBusConnection *connection,
2167 GAsyncResult *res,
2168 gpointer user_data)
2170 SendMessageSyncData *data = user_data;
2171 data->res = g_object_ref (res);
2172 g_main_loop_quit (data->loop);
2176 * g_dbus_connection_send_message_with_reply_sync:
2177 * @connection: A #GDBusConnection.
2178 * @message: A #GDBusMessage.
2179 * @flags: Flags affecting how the message is sent.
2180 * @timeout_msec: The timeout in milliseconds, -1 to use the default
2181 * timeout or %G_MAXINT for no timeout.
2182 * @out_serial: (out) (allow-none): Return location for serial number assigned
2183 * to @message when sending it or %NULL.
2184 * @cancellable: (allow-none): A #GCancellable or %NULL.
2185 * @error: Return location for error or %NULL.
2187 * Synchronously sends @message to the peer represented by @connection
2188 * and blocks the calling thread until a reply is received or the
2189 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2190 * for the asynchronous version of this method.
2192 * Unless @flags contain the
2193 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2194 * will be assigned by @connection and set on @message via
2195 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2196 * serial number used will be written to this location prior to
2197 * submitting the message to the underlying transport.
2199 * If @connection is closed then the operation will fail with
2200 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2201 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2202 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2204 * Note that @error is only set if a local in-process error
2205 * occurred. That is to say that the returned #GDBusMessage object may
2206 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2207 * g_dbus_message_to_gerror() to transcode this to a #GError.
2209 * See <xref linkend="gdbus-server"/> and <xref
2210 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2211 * low-level API to send and receive UNIX file descriptors.
2213 * Note that @message must be unlocked, unless @flags contain the
2214 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2216 * Returns: (transfer full): A locked #GDBusMessage that is the reply to @message or %NULL if @error is set.
2218 * Since: 2.26
2220 GDBusMessage *
2221 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2222 GDBusMessage *message,
2223 GDBusSendMessageFlags flags,
2224 gint timeout_msec,
2225 volatile guint32 *out_serial,
2226 GCancellable *cancellable,
2227 GError **error)
2229 SendMessageSyncData *data;
2230 GDBusMessage *reply;
2232 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2233 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2234 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2235 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2236 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2238 data = g_new0 (SendMessageSyncData, 1);
2239 data->context = g_main_context_new ();
2240 data->loop = g_main_loop_new (data->context, FALSE);
2242 g_main_context_push_thread_default (data->context);
2244 g_dbus_connection_send_message_with_reply (connection,
2245 message,
2246 flags,
2247 timeout_msec,
2248 out_serial,
2249 cancellable,
2250 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2251 data);
2252 g_main_loop_run (data->loop);
2253 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2254 data->res,
2255 error);
2257 g_main_context_pop_thread_default (data->context);
2259 g_main_context_unref (data->context);
2260 g_main_loop_unref (data->loop);
2261 g_object_unref (data->res);
2262 g_free (data);
2264 return reply;
2267 /* ---------------------------------------------------------------------------------------------------- */
2269 typedef struct
2271 GDBusMessageFilterFunction func;
2272 gpointer user_data;
2273 } FilterCallback;
2275 typedef struct
2277 guint id;
2278 GDBusMessageFilterFunction filter_function;
2279 gpointer user_data;
2280 GDestroyNotify user_data_free_func;
2281 } FilterData;
2283 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2284 static void
2285 on_worker_message_received (GDBusWorker *worker,
2286 GDBusMessage *message,
2287 gpointer user_data)
2289 GDBusConnection *connection;
2290 FilterCallback *filters;
2291 guint num_filters;
2292 guint n;
2293 gboolean alive;
2295 G_LOCK (message_bus_lock);
2296 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2297 if (!alive)
2299 G_UNLOCK (message_bus_lock);
2300 return;
2302 connection = G_DBUS_CONNECTION (user_data);
2303 g_object_ref (connection);
2304 G_UNLOCK (message_bus_lock);
2306 //g_debug ("in on_worker_message_received");
2308 g_object_ref (message);
2309 g_dbus_message_lock (message);
2311 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2313 /* First collect the set of callback functions */
2314 CONNECTION_LOCK (connection);
2315 num_filters = connection->filters->len;
2316 filters = g_new0 (FilterCallback, num_filters);
2317 for (n = 0; n < num_filters; n++)
2319 FilterData *data = connection->filters->pdata[n];
2320 filters[n].func = data->filter_function;
2321 filters[n].user_data = data->user_data;
2323 CONNECTION_UNLOCK (connection);
2325 /* then call the filters in order (without holding the lock) */
2326 for (n = 0; n < num_filters; n++)
2328 message = filters[n].func (connection,
2329 message,
2330 TRUE,
2331 filters[n].user_data);
2332 if (message == NULL)
2333 break;
2334 g_dbus_message_lock (message);
2337 /* Standard dispatch unless the filter ate the message - no need to
2338 * do anything if the message was altered
2340 if (message != NULL)
2342 GDBusMessageType message_type;
2344 message_type = g_dbus_message_get_message_type (message);
2345 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2347 guint32 reply_serial;
2348 SendMessageData *send_message_data;
2350 reply_serial = g_dbus_message_get_reply_serial (message);
2351 CONNECTION_LOCK (connection);
2352 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2353 GUINT_TO_POINTER (reply_serial));
2354 if (send_message_data != NULL)
2356 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2357 send_message_data_deliver_reply_unlocked (send_message_data, message);
2359 else
2361 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2363 CONNECTION_UNLOCK (connection);
2365 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2367 CONNECTION_LOCK (connection);
2368 distribute_signals (connection, message);
2369 CONNECTION_UNLOCK (connection);
2371 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2373 CONNECTION_LOCK (connection);
2374 distribute_method_call (connection, message);
2375 CONNECTION_UNLOCK (connection);
2379 if (message != NULL)
2380 g_object_unref (message);
2381 g_object_unref (connection);
2382 g_free (filters);
2385 /* Called in GDBusWorker's thread, lock is not held */
2386 static GDBusMessage *
2387 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2388 GDBusMessage *message,
2389 gpointer user_data)
2391 GDBusConnection *connection;
2392 FilterCallback *filters;
2393 guint num_filters;
2394 guint n;
2395 gboolean alive;
2397 G_LOCK (message_bus_lock);
2398 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2399 if (!alive)
2401 G_UNLOCK (message_bus_lock);
2402 return message;
2404 connection = G_DBUS_CONNECTION (user_data);
2405 g_object_ref (connection);
2406 G_UNLOCK (message_bus_lock);
2408 //g_debug ("in on_worker_message_about_to_be_sent");
2410 /* First collect the set of callback functions */
2411 CONNECTION_LOCK (connection);
2412 num_filters = connection->filters->len;
2413 filters = g_new0 (FilterCallback, num_filters);
2414 for (n = 0; n < num_filters; n++)
2416 FilterData *data = connection->filters->pdata[n];
2417 filters[n].func = data->filter_function;
2418 filters[n].user_data = data->user_data;
2420 CONNECTION_UNLOCK (connection);
2422 /* then call the filters in order (without holding the lock) */
2423 for (n = 0; n < num_filters; n++)
2425 g_dbus_message_lock (message);
2426 message = filters[n].func (connection,
2427 message,
2428 FALSE,
2429 filters[n].user_data);
2430 if (message == NULL)
2431 break;
2434 g_object_unref (connection);
2435 g_free (filters);
2437 return message;
2440 /* called with connection lock held, in GDBusWorker thread */
2441 static gboolean
2442 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2444 SendMessageData *data = value;
2446 if (data->delivered)
2447 return FALSE;
2449 g_simple_async_result_set_error (data->simple,
2450 G_IO_ERROR,
2451 G_IO_ERROR_CLOSED,
2452 _("The connection is closed"));
2454 /* Ask send_message_with_reply_deliver not to remove the element from the
2455 * hash table - we're in the middle of a foreach; that would be unsafe.
2456 * Instead, return TRUE from this function so that it gets removed safely.
2458 send_message_with_reply_deliver (data, FALSE);
2459 return TRUE;
2462 /* Called in GDBusWorker's thread - we must not block - without lock held */
2463 static void
2464 on_worker_closed (GDBusWorker *worker,
2465 gboolean remote_peer_vanished,
2466 GError *error,
2467 gpointer user_data)
2469 GDBusConnection *connection;
2470 gboolean alive;
2471 guint old_atomic_flags;
2473 G_LOCK (message_bus_lock);
2474 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2475 if (!alive)
2477 G_UNLOCK (message_bus_lock);
2478 return;
2480 connection = G_DBUS_CONNECTION (user_data);
2481 g_object_ref (connection);
2482 G_UNLOCK (message_bus_lock);
2484 //g_debug ("in on_worker_closed: %s", error->message);
2486 CONNECTION_LOCK (connection);
2487 /* Even though this is atomic, we do it inside the lock to avoid breaking
2488 * assumptions in remove_match_rule(). We'd need the lock in a moment
2489 * anyway, so, no loss.
2491 old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
2493 if (!(old_atomic_flags & FLAG_CLOSED))
2495 g_hash_table_foreach_remove (connection->map_method_serial_to_send_message_data, cancel_method_on_close, NULL);
2496 schedule_closed_unlocked (connection, remote_peer_vanished, error);
2498 CONNECTION_UNLOCK (connection);
2500 g_object_unref (connection);
2503 /* ---------------------------------------------------------------------------------------------------- */
2505 /* Determines the biggest set of capabilities we can support on this
2506 * connection.
2508 * Called with the init_lock held.
2510 static GDBusCapabilityFlags
2511 get_offered_capabilities_max (GDBusConnection *connection)
2513 GDBusCapabilityFlags ret;
2514 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2515 #ifdef G_OS_UNIX
2516 if (G_IS_UNIX_CONNECTION (connection->stream))
2517 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2518 #endif
2519 return ret;
2522 /* Called in a user thread, lock is not held */
2523 static gboolean
2524 initable_init (GInitable *initable,
2525 GCancellable *cancellable,
2526 GError **error)
2528 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2529 gboolean ret;
2531 /* This method needs to be idempotent to work with the singleton
2532 * pattern. See the docs for g_initable_init(). We implement this by
2533 * locking.
2535 * Unfortunately we can't use the main lock since the on_worker_*()
2536 * callbacks above needs the lock during initialization (for message
2537 * bus connections we do a synchronous Hello() call on the bus).
2539 g_mutex_lock (&connection->init_lock);
2541 ret = FALSE;
2543 /* Make this a no-op if we're already initialized (successfully or
2544 * unsuccessfully)
2546 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
2548 ret = (connection->initialization_error == NULL);
2549 goto out;
2552 /* Because of init_lock, we can't get here twice in different threads */
2553 g_assert (connection->initialization_error == NULL);
2555 /* The user can pass multiple (but mutally exclusive) construct
2556 * properties:
2558 * - stream (of type GIOStream)
2559 * - address (of type gchar*)
2561 * At the end of the day we end up with a non-NULL GIOStream
2562 * object in connection->stream.
2564 if (connection->address != NULL)
2566 g_assert (connection->stream == NULL);
2568 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2569 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2571 g_set_error_literal (&connection->initialization_error,
2572 G_IO_ERROR,
2573 G_IO_ERROR_INVALID_ARGUMENT,
2574 _("Unsupported flags encountered when constructing a client-side connection"));
2575 goto out;
2578 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2579 NULL, /* TODO: out_guid */
2580 cancellable,
2581 &connection->initialization_error);
2582 if (connection->stream == NULL)
2583 goto out;
2585 else if (connection->stream != NULL)
2587 /* nothing to do */
2589 else
2591 g_assert_not_reached ();
2594 /* Authenticate the connection */
2595 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2597 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2598 g_assert (connection->guid != NULL);
2599 connection->auth = _g_dbus_auth_new (connection->stream);
2600 if (!_g_dbus_auth_run_server (connection->auth,
2601 connection->authentication_observer,
2602 connection->guid,
2603 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2604 get_offered_capabilities_max (connection),
2605 &connection->capabilities,
2606 &connection->credentials,
2607 cancellable,
2608 &connection->initialization_error))
2609 goto out;
2611 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2613 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2614 g_assert (connection->guid == NULL);
2615 connection->auth = _g_dbus_auth_new (connection->stream);
2616 connection->guid = _g_dbus_auth_run_client (connection->auth,
2617 connection->authentication_observer,
2618 get_offered_capabilities_max (connection),
2619 &connection->capabilities,
2620 cancellable,
2621 &connection->initialization_error);
2622 if (connection->guid == NULL)
2623 goto out;
2626 if (connection->authentication_observer != NULL)
2628 g_object_unref (connection->authentication_observer);
2629 connection->authentication_observer = NULL;
2632 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2634 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2636 #ifdef G_OS_UNIX
2637 /* We want all IO operations to be non-blocking since they happen in
2638 * the worker thread which is shared by _all_ connections.
2640 if (G_IS_SOCKET_CONNECTION (connection->stream))
2642 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2644 #endif
2646 G_LOCK (message_bus_lock);
2647 if (alive_connections == NULL)
2648 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2649 g_hash_table_insert (alive_connections, connection, connection);
2650 G_UNLOCK (message_bus_lock);
2652 connection->worker = _g_dbus_worker_new (connection->stream,
2653 connection->capabilities,
2654 ((connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) != 0),
2655 on_worker_message_received,
2656 on_worker_message_about_to_be_sent,
2657 on_worker_closed,
2658 connection);
2660 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2661 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2663 GVariant *hello_result;
2665 /* we could lift this restriction by adding code in gdbusprivate.c */
2666 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2668 g_set_error_literal (&connection->initialization_error,
2669 G_IO_ERROR,
2670 G_IO_ERROR_FAILED,
2671 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2672 goto out;
2675 hello_result = g_dbus_connection_call_sync (connection,
2676 "org.freedesktop.DBus", /* name */
2677 "/org/freedesktop/DBus", /* path */
2678 "org.freedesktop.DBus", /* interface */
2679 "Hello",
2680 NULL, /* parameters */
2681 G_VARIANT_TYPE ("(s)"),
2682 CALL_FLAGS_INITIALIZING,
2684 NULL, /* TODO: cancellable */
2685 &connection->initialization_error);
2686 if (hello_result == NULL)
2687 goto out;
2689 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2690 g_variant_unref (hello_result);
2691 //g_debug ("unique name is '%s'", connection->bus_unique_name);
2694 ret = TRUE;
2695 out:
2696 if (!ret)
2698 g_assert (connection->initialization_error != NULL);
2699 g_propagate_error (error, g_error_copy (connection->initialization_error));
2702 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
2703 g_mutex_unlock (&connection->init_lock);
2705 return ret;
2708 static void
2709 initable_iface_init (GInitableIface *initable_iface)
2711 initable_iface->init = initable_init;
2714 /* ---------------------------------------------------------------------------------------------------- */
2716 static void
2717 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2719 /* Use default */
2722 /* ---------------------------------------------------------------------------------------------------- */
2725 * g_dbus_connection_new:
2726 * @stream: A #GIOStream.
2727 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2728 * @flags: Flags describing how to make the connection.
2729 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2730 * @cancellable: (allow-none): A #GCancellable or %NULL.
2731 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2732 * @user_data: The data to pass to @callback.
2734 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2735 * with the end represented by @stream.
2737 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2738 * will be put into non-blocking mode.
2740 * The D-Bus connection will interact with @stream from a worker thread.
2741 * As a result, the caller should not interact with @stream after this
2742 * method has been called, except by calling g_object_unref() on it.
2744 * If @observer is not %NULL it may be used to control the
2745 * authentication process.
2747 * When the operation is finished, @callback will be invoked. You can
2748 * then call g_dbus_connection_new_finish() to get the result of the
2749 * operation.
2751 * This is a asynchronous failable constructor. See
2752 * g_dbus_connection_new_sync() for the synchronous
2753 * version.
2755 * Since: 2.26
2757 void
2758 g_dbus_connection_new (GIOStream *stream,
2759 const gchar *guid,
2760 GDBusConnectionFlags flags,
2761 GDBusAuthObserver *observer,
2762 GCancellable *cancellable,
2763 GAsyncReadyCallback callback,
2764 gpointer user_data)
2766 g_return_if_fail (G_IS_IO_STREAM (stream));
2767 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2768 G_PRIORITY_DEFAULT,
2769 cancellable,
2770 callback,
2771 user_data,
2772 "stream", stream,
2773 "guid", guid,
2774 "flags", flags,
2775 "authentication-observer", observer,
2776 NULL);
2780 * g_dbus_connection_new_finish:
2781 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2782 * @error: Return location for error or %NULL.
2784 * Finishes an operation started with g_dbus_connection_new().
2786 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2788 * Since: 2.26
2790 GDBusConnection *
2791 g_dbus_connection_new_finish (GAsyncResult *res,
2792 GError **error)
2794 GObject *object;
2795 GObject *source_object;
2797 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2798 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2800 source_object = g_async_result_get_source_object (res);
2801 g_assert (source_object != NULL);
2802 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2803 res,
2804 error);
2805 g_object_unref (source_object);
2806 if (object != NULL)
2807 return G_DBUS_CONNECTION (object);
2808 else
2809 return NULL;
2813 * g_dbus_connection_new_sync:
2814 * @stream: A #GIOStream.
2815 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2816 * @flags: Flags describing how to make the connection.
2817 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2818 * @cancellable: (allow-none): A #GCancellable or %NULL.
2819 * @error: Return location for error or %NULL.
2821 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2822 * with the end represented by @stream.
2824 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2825 * will be put into non-blocking mode.
2827 * The D-Bus connection will interact with @stream from a worker thread.
2828 * As a result, the caller should not interact with @stream after this
2829 * method has been called, except by calling g_object_unref() on it.
2831 * If @observer is not %NULL it may be used to control the
2832 * authentication process.
2834 * This is a synchronous failable constructor. See
2835 * g_dbus_connection_new() for the asynchronous version.
2837 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2839 * Since: 2.26
2841 GDBusConnection *
2842 g_dbus_connection_new_sync (GIOStream *stream,
2843 const gchar *guid,
2844 GDBusConnectionFlags flags,
2845 GDBusAuthObserver *observer,
2846 GCancellable *cancellable,
2847 GError **error)
2849 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2850 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2851 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2852 cancellable,
2853 error,
2854 "stream", stream,
2855 "guid", guid,
2856 "flags", flags,
2857 "authentication-observer", observer,
2858 NULL);
2861 /* ---------------------------------------------------------------------------------------------------- */
2864 * g_dbus_connection_new_for_address:
2865 * @address: A D-Bus address.
2866 * @flags: Flags describing how to make the connection.
2867 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2868 * @cancellable: (allow-none): A #GCancellable or %NULL.
2869 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2870 * @user_data: The data to pass to @callback.
2872 * Asynchronously connects and sets up a D-Bus client connection for
2873 * exchanging D-Bus messages with an endpoint specified by @address
2874 * which must be in the D-Bus address format.
2876 * This constructor can only be used to initiate client-side
2877 * connections - use g_dbus_connection_new() if you need to act as the
2878 * server. In particular, @flags cannot contain the
2879 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2880 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2882 * When the operation is finished, @callback will be invoked. You can
2883 * then call g_dbus_connection_new_finish() to get the result of the
2884 * operation.
2886 * If @observer is not %NULL it may be used to control the
2887 * authentication process.
2889 * This is a asynchronous failable constructor. See
2890 * g_dbus_connection_new_for_address_sync() for the synchronous
2891 * version.
2893 * Since: 2.26
2895 void
2896 g_dbus_connection_new_for_address (const gchar *address,
2897 GDBusConnectionFlags flags,
2898 GDBusAuthObserver *observer,
2899 GCancellable *cancellable,
2900 GAsyncReadyCallback callback,
2901 gpointer user_data)
2903 g_return_if_fail (address != NULL);
2904 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2905 G_PRIORITY_DEFAULT,
2906 cancellable,
2907 callback,
2908 user_data,
2909 "address", address,
2910 "flags", flags,
2911 "authentication-observer", observer,
2912 NULL);
2916 * g_dbus_connection_new_for_address_finish:
2917 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2918 * @error: Return location for error or %NULL.
2920 * Finishes an operation started with g_dbus_connection_new_for_address().
2922 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2924 * Since: 2.26
2926 GDBusConnection *
2927 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2928 GError **error)
2930 GObject *object;
2931 GObject *source_object;
2933 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2934 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2936 source_object = g_async_result_get_source_object (res);
2937 g_assert (source_object != NULL);
2938 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2939 res,
2940 error);
2941 g_object_unref (source_object);
2942 if (object != NULL)
2943 return G_DBUS_CONNECTION (object);
2944 else
2945 return NULL;
2949 * g_dbus_connection_new_for_address_sync:
2950 * @address: A D-Bus address.
2951 * @flags: Flags describing how to make the connection.
2952 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2953 * @cancellable: (allow-none): A #GCancellable or %NULL.
2954 * @error: Return location for error or %NULL.
2956 * Synchronously connects and sets up a D-Bus client connection for
2957 * exchanging D-Bus messages with an endpoint specified by @address
2958 * which must be in the D-Bus address format.
2960 * This constructor can only be used to initiate client-side
2961 * connections - use g_dbus_connection_new_sync() if you need to act
2962 * as the server. In particular, @flags cannot contain the
2963 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2964 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2966 * This is a synchronous failable constructor. See
2967 * g_dbus_connection_new_for_address() for the asynchronous version.
2969 * If @observer is not %NULL it may be used to control the
2970 * authentication process.
2972 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2974 * Since: 2.26
2976 GDBusConnection *
2977 g_dbus_connection_new_for_address_sync (const gchar *address,
2978 GDBusConnectionFlags flags,
2979 GDBusAuthObserver *observer,
2980 GCancellable *cancellable,
2981 GError **error)
2983 g_return_val_if_fail (address != NULL, NULL);
2984 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2985 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2986 cancellable,
2987 error,
2988 "address", address,
2989 "flags", flags,
2990 "authentication-observer", observer,
2991 NULL);
2994 /* ---------------------------------------------------------------------------------------------------- */
2997 * g_dbus_connection_set_exit_on_close:
2998 * @connection: A #GDBusConnection.
2999 * @exit_on_close: Whether the process should be terminated
3000 * when @connection is closed by the remote peer.
3002 * Sets whether the process should be terminated when @connection is
3003 * closed by the remote peer. See #GDBusConnection:exit-on-close for
3004 * more details.
3006 * Note that this function should be used with care. Most modern UNIX
3007 * desktops tie the notion of a user session the session bus, and expect
3008 * all of a users applications to quit when their bus connection goes away.
3009 * If you are setting @exit_on_close to %FALSE for the shared session
3010 * bus connection, you should make sure that your application exits
3011 * when the user session ends.
3013 * Since: 2.26
3015 void
3016 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
3017 gboolean exit_on_close)
3019 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3021 if (exit_on_close)
3022 g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
3023 else
3024 g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
3029 * g_dbus_connection_get_exit_on_close:
3030 * @connection: A #GDBusConnection.
3032 * Gets whether the process is terminated when @connection is
3033 * closed by the remote peer. See
3034 * #GDBusConnection:exit-on-close for more details.
3036 * Returns: Whether the process is terminated when @connection is
3037 * closed by the remote peer.
3039 * Since: 2.26
3041 gboolean
3042 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
3044 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3046 if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
3047 return TRUE;
3048 else
3049 return FALSE;
3053 * g_dbus_connection_get_guid:
3054 * @connection: A #GDBusConnection.
3056 * The GUID of the peer performing the role of server when
3057 * authenticating. See #GDBusConnection:guid for more details.
3059 * Returns: The GUID. Do not free this string, it is owned by
3060 * @connection.
3062 * Since: 2.26
3064 const gchar *
3065 g_dbus_connection_get_guid (GDBusConnection *connection)
3067 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3068 return connection->guid;
3072 * g_dbus_connection_get_unique_name:
3073 * @connection: A #GDBusConnection.
3075 * Gets the unique name of @connection as assigned by the message
3076 * bus. This can also be used to figure out if @connection is a
3077 * message bus connection.
3079 * Returns: The unique name or %NULL if @connection is not a message
3080 * bus connection. Do not free this string, it is owned by
3081 * @connection.
3083 * Since: 2.26
3085 const gchar *
3086 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3088 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3090 /* do not use g_return_val_if_fail(), we want the memory barrier */
3091 if (!check_initialized (connection))
3092 return NULL;
3094 return connection->bus_unique_name;
3098 * g_dbus_connection_get_peer_credentials:
3099 * @connection: A #GDBusConnection.
3101 * Gets the credentials of the authenticated peer. This will always
3102 * return %NULL unless @connection acted as a server
3103 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3104 * when set up and the client passed credentials as part of the
3105 * authentication process.
3107 * In a message bus setup, the message bus is always the server and
3108 * each application is a client. So this method will always return
3109 * %NULL for message bus clients.
3111 * Returns: (transfer none): A #GCredentials or %NULL if not available. Do not free
3112 * this object, it is owned by @connection.
3114 * Since: 2.26
3116 GCredentials *
3117 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3119 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3121 /* do not use g_return_val_if_fail(), we want the memory barrier */
3122 if (!check_initialized (connection))
3123 return NULL;
3125 return connection->credentials;
3128 /* ---------------------------------------------------------------------------------------------------- */
3130 static guint _global_filter_id = 1;
3133 * g_dbus_connection_add_filter:
3134 * @connection: A #GDBusConnection.
3135 * @filter_function: A filter function.
3136 * @user_data: User data to pass to @filter_function.
3137 * @user_data_free_func: Function to free @user_data with when filter
3138 * is removed or %NULL.
3140 * Adds a message filter. Filters are handlers that are run on all
3141 * incoming and outgoing messages, prior to standard dispatch. Filters
3142 * are run in the order that they were added. The same handler can be
3143 * added as a filter more than once, in which case it will be run more
3144 * than once. Filters added during a filter callback won't be run on
3145 * the message being processed. Filter functions are allowed to modify
3146 * and even drop messages.
3148 * Note that filters are run in a dedicated message handling thread so
3149 * they can't block and, generally, can't do anything but signal a
3150 * worker thread. Also note that filters are rarely needed - use API
3151 * such as g_dbus_connection_send_message_with_reply(),
3152 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3154 * If a filter consumes an incoming message the message is not
3155 * dispatched anywhere else - not even the standard dispatch machinery
3156 * (that API such as g_dbus_connection_signal_subscribe() and
3157 * g_dbus_connection_send_message_with_reply() relies on) will see the
3158 * message. Similary, if a filter consumes an outgoing message, the
3159 * message will not be sent to the other peer.
3161 * Returns: A filter identifier that can be used with
3162 * g_dbus_connection_remove_filter().
3164 * Since: 2.26
3166 guint
3167 g_dbus_connection_add_filter (GDBusConnection *connection,
3168 GDBusMessageFilterFunction filter_function,
3169 gpointer user_data,
3170 GDestroyNotify user_data_free_func)
3172 FilterData *data;
3174 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3175 g_return_val_if_fail (filter_function != NULL, 0);
3176 g_return_val_if_fail (check_initialized (connection), 0);
3178 CONNECTION_LOCK (connection);
3179 data = g_new0 (FilterData, 1);
3180 data->id = _global_filter_id++; /* TODO: overflow etc. */
3181 data->filter_function = filter_function;
3182 data->user_data = user_data;
3183 data->user_data_free_func = user_data_free_func;
3184 g_ptr_array_add (connection->filters, data);
3185 CONNECTION_UNLOCK (connection);
3187 return data->id;
3190 /* only called from finalize(), removes all filters */
3191 static void
3192 purge_all_filters (GDBusConnection *connection)
3194 guint n;
3195 for (n = 0; n < connection->filters->len; n++)
3197 FilterData *data = connection->filters->pdata[n];
3198 if (data->user_data_free_func != NULL)
3199 data->user_data_free_func (data->user_data);
3200 g_free (data);
3205 * g_dbus_connection_remove_filter:
3206 * @connection: a #GDBusConnection
3207 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3209 * Removes a filter.
3211 * Since: 2.26
3213 void
3214 g_dbus_connection_remove_filter (GDBusConnection *connection,
3215 guint filter_id)
3217 guint n;
3218 FilterData *to_destroy;
3220 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3221 g_return_if_fail (check_initialized (connection));
3223 CONNECTION_LOCK (connection);
3224 to_destroy = NULL;
3225 for (n = 0; n < connection->filters->len; n++)
3227 FilterData *data = connection->filters->pdata[n];
3228 if (data->id == filter_id)
3230 g_ptr_array_remove_index (connection->filters, n);
3231 to_destroy = data;
3232 break;
3235 CONNECTION_UNLOCK (connection);
3237 /* do free without holding lock */
3238 if (to_destroy != NULL)
3240 if (to_destroy->user_data_free_func != NULL)
3241 to_destroy->user_data_free_func (to_destroy->user_data);
3242 g_free (to_destroy);
3244 else
3246 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3250 /* ---------------------------------------------------------------------------------------------------- */
3252 typedef struct
3254 gchar *rule;
3255 gchar *sender;
3256 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3257 gchar *interface_name;
3258 gchar *member;
3259 gchar *object_path;
3260 gchar *arg0;
3261 GDBusSignalFlags flags;
3262 GArray *subscribers;
3263 } SignalData;
3265 typedef struct
3267 GDBusSignalCallback callback;
3268 gpointer user_data;
3269 GDestroyNotify user_data_free_func;
3270 guint id;
3271 GMainContext *context;
3272 } SignalSubscriber;
3274 static void
3275 signal_data_free (SignalData *signal_data)
3277 g_free (signal_data->rule);
3278 g_free (signal_data->sender);
3279 g_free (signal_data->sender_unique_name);
3280 g_free (signal_data->interface_name);
3281 g_free (signal_data->member);
3282 g_free (signal_data->object_path);
3283 g_free (signal_data->arg0);
3284 g_array_free (signal_data->subscribers, TRUE);
3285 g_free (signal_data);
3288 static gchar *
3289 args_to_rule (const gchar *sender,
3290 const gchar *interface_name,
3291 const gchar *member,
3292 const gchar *object_path,
3293 const gchar *arg0,
3294 GDBusSignalFlags flags)
3296 GString *rule;
3298 rule = g_string_new ("type='signal'");
3299 if (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE)
3300 g_string_prepend_c (rule, '-');
3301 if (sender != NULL)
3302 g_string_append_printf (rule, ",sender='%s'", sender);
3303 if (interface_name != NULL)
3304 g_string_append_printf (rule, ",interface='%s'", interface_name);
3305 if (member != NULL)
3306 g_string_append_printf (rule, ",member='%s'", member);
3307 if (object_path != NULL)
3308 g_string_append_printf (rule, ",path='%s'", object_path);
3310 if (arg0 != NULL)
3312 if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3313 g_string_append_printf (rule, ",arg0path='%s'", arg0);
3314 else if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3315 g_string_append_printf (rule, ",arg0namespace='%s'", arg0);
3316 else
3317 g_string_append_printf (rule, ",arg0='%s'", arg0);
3320 return g_string_free (rule, FALSE);
3323 static guint _global_subscriber_id = 1;
3324 static guint _global_registration_id = 1;
3325 static guint _global_subtree_registration_id = 1;
3327 /* ---------------------------------------------------------------------------------------------------- */
3329 /* Called in a user thread, lock is held */
3330 static void
3331 add_match_rule (GDBusConnection *connection,
3332 const gchar *match_rule)
3334 GError *error;
3335 GDBusMessage *message;
3337 if (match_rule[0] == '-')
3338 return;
3340 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3341 "/org/freedesktop/DBus", /* path */
3342 "org.freedesktop.DBus", /* interface */
3343 "AddMatch");
3344 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3345 error = NULL;
3346 if (!g_dbus_connection_send_message_unlocked (connection,
3347 message,
3348 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3349 NULL,
3350 &error))
3352 g_critical ("Error while sending AddMatch() message: %s", error->message);
3353 g_error_free (error);
3355 g_object_unref (message);
3358 /* ---------------------------------------------------------------------------------------------------- */
3360 /* Called in a user thread, lock is held */
3361 static void
3362 remove_match_rule (GDBusConnection *connection,
3363 const gchar *match_rule)
3365 GError *error;
3366 GDBusMessage *message;
3368 if (match_rule[0] == '-')
3369 return;
3371 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3372 "/org/freedesktop/DBus", /* path */
3373 "org.freedesktop.DBus", /* interface */
3374 "RemoveMatch");
3375 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3377 error = NULL;
3378 if (!g_dbus_connection_send_message_unlocked (connection,
3379 message,
3380 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3381 NULL,
3382 &error))
3384 /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
3385 * critical; but we're holding the lock, and our caller checked whether
3386 * we were already closed, so we can't get that error.
3388 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3389 g_error_free (error);
3391 g_object_unref (message);
3394 /* ---------------------------------------------------------------------------------------------------- */
3396 static gboolean
3397 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3399 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3400 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3401 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3402 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3403 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3406 /* ---------------------------------------------------------------------------------------------------- */
3409 * g_dbus_connection_signal_subscribe:
3410 * @connection: A #GDBusConnection.
3411 * @sender: (allow-none): Sender name to match on (unique or well-known name)
3412 * or %NULL to listen from all senders.
3413 * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3414 * match on all interfaces.
3415 * @member: (allow-none): D-Bus signal name to match on or %NULL to match on all signals.
3416 * @object_path: (allow-none): Object path to match on or %NULL to match on all object paths.
3417 * @arg0: (allow-none): Contents of first string argument to match on or %NULL
3418 * to match on all kinds of arguments.
3419 * @flags: Flags describing how to subscribe to the signal (currently unused).
3420 * @callback: Callback to invoke when there is a signal matching the requested data.
3421 * @user_data: User data to pass to @callback.
3422 * @user_data_free_func: (allow-none): Function to free @user_data with when
3423 * subscription is removed or %NULL.
3425 * Subscribes to signals on @connection and invokes @callback with a
3426 * whenever the signal is received. Note that @callback
3427 * will be invoked in the <link
3428 * linkend="g-main-context-push-thread-default">thread-default main
3429 * loop</link> of the thread you are calling this method from.
3431 * If @connection is not a message bus connection, @sender must be
3432 * %NULL.
3434 * If @sender is a well-known name note that @callback is invoked with
3435 * the unique name for the owner of @sender, not the well-known name
3436 * as one would expect. This is because the message bus rewrites the
3437 * name. As such, to avoid certain race conditions, users should be
3438 * tracking the name owner of the well-known name and use that when
3439 * processing the received signal.
3441 * If one of %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE or
3442 * %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH are given, @arg0 is
3443 * interpreted as part of a namespace or path. The first argument
3444 * of a signal is matched against that part as specified by D-Bus.
3446 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
3448 * Since: 2.26
3450 guint
3451 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3452 const gchar *sender,
3453 const gchar *interface_name,
3454 const gchar *member,
3455 const gchar *object_path,
3456 const gchar *arg0,
3457 GDBusSignalFlags flags,
3458 GDBusSignalCallback callback,
3459 gpointer user_data,
3460 GDestroyNotify user_data_free_func)
3462 gchar *rule;
3463 SignalData *signal_data;
3464 SignalSubscriber subscriber;
3465 GPtrArray *signal_data_array;
3466 const gchar *sender_unique_name;
3468 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3469 * an OOM condition. We might want to change that but that would involve making
3470 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3471 * handle that. And there's really no sensible way of handling this short of retrying
3472 * to add the match rule... and then there's the little thing that, hey, maybe there's
3473 * a reason the bus in an OOM condition.
3475 * Doable, but not really sure it's worth it...
3478 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3479 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3480 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3481 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3482 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3483 g_return_val_if_fail (callback != NULL, 0);
3484 g_return_val_if_fail (check_initialized (connection), 0);
3485 g_return_val_if_fail (!((flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH) && (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)), 0);
3486 g_return_val_if_fail (!(arg0 == NULL && (flags & (G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH | G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE))), 0);
3488 CONNECTION_LOCK (connection);
3490 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3491 * with a '-' character to prefix the rule (which will otherwise be
3492 * normal).
3494 * This allows us to hash the rule and do our lifecycle tracking in
3495 * the usual way, but the '-' prevents the match rule from ever
3496 * actually being send to the bus (either for add or remove).
3498 rule = args_to_rule (sender, interface_name, member, object_path, arg0, flags);
3500 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3501 sender_unique_name = sender;
3502 else
3503 sender_unique_name = "";
3505 subscriber.callback = callback;
3506 subscriber.user_data = user_data;
3507 subscriber.user_data_free_func = user_data_free_func;
3508 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3509 subscriber.context = g_main_context_ref_thread_default ();
3511 /* see if we've already have this rule */
3512 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3513 if (signal_data != NULL)
3515 g_array_append_val (signal_data->subscribers, subscriber);
3516 g_free (rule);
3517 goto out;
3520 signal_data = g_new0 (SignalData, 1);
3521 signal_data->rule = rule;
3522 signal_data->sender = g_strdup (sender);
3523 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3524 signal_data->interface_name = g_strdup (interface_name);
3525 signal_data->member = g_strdup (member);
3526 signal_data->object_path = g_strdup (object_path);
3527 signal_data->arg0 = g_strdup (arg0);
3528 signal_data->flags = flags;
3529 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3530 g_array_append_val (signal_data->subscribers, subscriber);
3532 g_hash_table_insert (connection->map_rule_to_signal_data,
3533 signal_data->rule,
3534 signal_data);
3536 /* Add the match rule to the bus...
3538 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3539 * always send such messages to us.
3541 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3543 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3544 add_match_rule (connection, signal_data->rule);
3547 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3548 signal_data->sender_unique_name);
3549 if (signal_data_array == NULL)
3551 signal_data_array = g_ptr_array_new ();
3552 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3553 g_strdup (signal_data->sender_unique_name),
3554 signal_data_array);
3556 g_ptr_array_add (signal_data_array, signal_data);
3558 out:
3559 g_hash_table_insert (connection->map_id_to_signal_data,
3560 GUINT_TO_POINTER (subscriber.id),
3561 signal_data);
3563 CONNECTION_UNLOCK (connection);
3565 return subscriber.id;
3568 /* ---------------------------------------------------------------------------------------------------- */
3570 /* called in any thread */
3571 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3572 static void
3573 unsubscribe_id_internal (GDBusConnection *connection,
3574 guint subscription_id,
3575 GArray *out_removed_subscribers)
3577 SignalData *signal_data;
3578 GPtrArray *signal_data_array;
3579 guint n;
3581 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3582 GUINT_TO_POINTER (subscription_id));
3583 if (signal_data == NULL)
3585 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3586 goto out;
3589 for (n = 0; n < signal_data->subscribers->len; n++)
3591 SignalSubscriber *subscriber;
3593 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3594 if (subscriber->id != subscription_id)
3595 continue;
3597 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3598 GUINT_TO_POINTER (subscription_id)));
3599 g_array_append_val (out_removed_subscribers, *subscriber);
3600 g_array_remove_index (signal_data->subscribers, n);
3602 if (signal_data->subscribers->len == 0)
3604 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3606 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3607 signal_data->sender_unique_name);
3608 g_warn_if_fail (signal_data_array != NULL);
3609 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3611 if (signal_data_array->len == 0)
3613 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3614 signal_data->sender_unique_name));
3617 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3618 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
3619 !is_signal_data_for_name_lost_or_acquired (signal_data) &&
3620 !g_dbus_connection_is_closed (connection) &&
3621 !connection->finalizing)
3623 /* The check for g_dbus_connection_is_closed() means that
3624 * sending the RemoveMatch message can't fail with
3625 * G_IO_ERROR_CLOSED, because we're holding the lock,
3626 * so on_worker_closed() can't happen between the check we just
3627 * did, and releasing the lock later.
3629 remove_match_rule (connection, signal_data->rule);
3632 signal_data_free (signal_data);
3635 goto out;
3638 g_assert_not_reached ();
3640 out:
3645 * g_dbus_connection_signal_unsubscribe:
3646 * @connection: A #GDBusConnection.
3647 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
3649 * Unsubscribes from signals.
3651 * Since: 2.26
3653 void
3654 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3655 guint subscription_id)
3657 GArray *subscribers;
3658 guint n;
3660 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3661 g_return_if_fail (check_initialized (connection));
3663 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3665 CONNECTION_LOCK (connection);
3666 unsubscribe_id_internal (connection,
3667 subscription_id,
3668 subscribers);
3669 CONNECTION_UNLOCK (connection);
3671 /* invariant */
3672 g_assert (subscribers->len == 0 || subscribers->len == 1);
3674 /* call GDestroyNotify without lock held */
3675 for (n = 0; n < subscribers->len; n++)
3677 SignalSubscriber *subscriber;
3678 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3679 call_destroy_notify (subscriber->context,
3680 subscriber->user_data_free_func,
3681 subscriber->user_data);
3682 g_main_context_unref (subscriber->context);
3685 g_array_free (subscribers, TRUE);
3688 /* ---------------------------------------------------------------------------------------------------- */
3690 typedef struct
3692 guint subscription_id;
3693 GDBusSignalCallback callback;
3694 gpointer user_data;
3695 GDBusMessage *message;
3696 GDBusConnection *connection;
3697 const gchar *sender;
3698 const gchar *path;
3699 const gchar *interface;
3700 const gchar *member;
3701 } SignalInstance;
3703 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3704 * no locks held
3706 static gboolean
3707 emit_signal_instance_in_idle_cb (gpointer data)
3709 SignalInstance *signal_instance = data;
3710 GVariant *parameters;
3711 gboolean has_subscription;
3713 parameters = g_dbus_message_get_body (signal_instance->message);
3714 if (parameters == NULL)
3716 parameters = g_variant_new ("()");
3717 g_variant_ref_sink (parameters);
3719 else
3721 g_variant_ref_sink (parameters);
3724 #if 0
3725 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3726 signal_instance->subscription_id,
3727 signal_instance->sender,
3728 signal_instance->path,
3729 signal_instance->interface,
3730 signal_instance->member,
3731 g_variant_print (parameters, TRUE));
3732 #endif
3734 /* Careful here, don't do the callback if we no longer has the subscription */
3735 CONNECTION_LOCK (signal_instance->connection);
3736 has_subscription = FALSE;
3737 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3738 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3739 has_subscription = TRUE;
3740 CONNECTION_UNLOCK (signal_instance->connection);
3742 if (has_subscription)
3743 signal_instance->callback (signal_instance->connection,
3744 signal_instance->sender,
3745 signal_instance->path,
3746 signal_instance->interface,
3747 signal_instance->member,
3748 parameters,
3749 signal_instance->user_data);
3751 g_variant_unref (parameters);
3753 return FALSE;
3756 static void
3757 signal_instance_free (SignalInstance *signal_instance)
3759 g_object_unref (signal_instance->message);
3760 g_object_unref (signal_instance->connection);
3761 g_free (signal_instance);
3764 static gboolean
3765 namespace_rule_matches (const gchar *namespace,
3766 const gchar *name)
3768 gint len_namespace;
3769 gint len_name;
3771 len_namespace = strlen (namespace);
3772 len_name = strlen (name);
3774 if (len_name < len_namespace)
3775 return FALSE;
3777 if (memcmp (namespace, name, len_namespace) != 0)
3778 return FALSE;
3780 return len_namespace == len_name || name[len_namespace] == '.';
3783 static gboolean
3784 path_rule_matches (const gchar *path_a,
3785 const gchar *path_b)
3787 gint len_a, len_b;
3789 len_a = strlen (path_a);
3790 len_b = strlen (path_b);
3792 if (len_a < len_b && path_a[len_a - 1] != '/')
3793 return FALSE;
3795 if (len_b < len_a && path_b[len_b - 1] != '/')
3796 return FALSE;
3798 return memcmp (path_a, path_b, MIN (len_a, len_b)) == 0;
3801 /* called in GDBusWorker thread WITH lock held */
3802 static void
3803 schedule_callbacks (GDBusConnection *connection,
3804 GPtrArray *signal_data_array,
3805 GDBusMessage *message,
3806 const gchar *sender)
3808 guint n, m;
3809 const gchar *interface;
3810 const gchar *member;
3811 const gchar *path;
3812 const gchar *arg0;
3814 interface = NULL;
3815 member = NULL;
3816 path = NULL;
3817 arg0 = NULL;
3819 interface = g_dbus_message_get_interface (message);
3820 member = g_dbus_message_get_member (message);
3821 path = g_dbus_message_get_path (message);
3822 arg0 = g_dbus_message_get_arg0 (message);
3824 #if 0
3825 g_print ("In schedule_callbacks:\n"
3826 " sender = '%s'\n"
3827 " interface = '%s'\n"
3828 " member = '%s'\n"
3829 " path = '%s'\n"
3830 " arg0 = '%s'\n",
3831 sender,
3832 interface,
3833 member,
3834 path,
3835 arg0);
3836 #endif
3838 /* TODO: if this is slow, then we can change signal_data_array into
3839 * map_object_path_to_signal_data_array or something.
3841 for (n = 0; n < signal_data_array->len; n++)
3843 SignalData *signal_data = signal_data_array->pdata[n];
3845 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3846 continue;
3848 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3849 continue;
3851 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3852 continue;
3854 if (signal_data->arg0 != NULL)
3856 if (arg0 == NULL)
3857 continue;
3859 if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3861 if (!namespace_rule_matches (signal_data->arg0, arg0))
3862 continue;
3864 else if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3866 if (!path_rule_matches (signal_data->arg0, arg0))
3867 continue;
3869 else if (!g_str_equal (signal_data->arg0, arg0))
3870 continue;
3873 for (m = 0; m < signal_data->subscribers->len; m++)
3875 SignalSubscriber *subscriber;
3876 GSource *idle_source;
3877 SignalInstance *signal_instance;
3879 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3881 signal_instance = g_new0 (SignalInstance, 1);
3882 signal_instance->subscription_id = subscriber->id;
3883 signal_instance->callback = subscriber->callback;
3884 signal_instance->user_data = subscriber->user_data;
3885 signal_instance->message = g_object_ref (message);
3886 signal_instance->connection = g_object_ref (connection);
3887 signal_instance->sender = sender;
3888 signal_instance->path = path;
3889 signal_instance->interface = interface;
3890 signal_instance->member = member;
3892 idle_source = g_idle_source_new ();
3893 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3894 g_source_set_callback (idle_source,
3895 emit_signal_instance_in_idle_cb,
3896 signal_instance,
3897 (GDestroyNotify) signal_instance_free);
3898 g_source_attach (idle_source, subscriber->context);
3899 g_source_unref (idle_source);
3904 /* called in GDBusWorker thread with lock held */
3905 static void
3906 distribute_signals (GDBusConnection *connection,
3907 GDBusMessage *message)
3909 GPtrArray *signal_data_array;
3910 const gchar *sender;
3912 sender = g_dbus_message_get_sender (message);
3914 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3916 _g_dbus_debug_print_lock ();
3917 g_print ("========================================================================\n"
3918 "GDBus-debug:Signal:\n"
3919 " <<<< RECEIVED SIGNAL %s.%s\n"
3920 " on object %s\n"
3921 " sent by name %s\n",
3922 g_dbus_message_get_interface (message),
3923 g_dbus_message_get_member (message),
3924 g_dbus_message_get_path (message),
3925 sender != NULL ? sender : "(none)");
3926 _g_dbus_debug_print_unlock ();
3929 /* collect subscribers that match on sender */
3930 if (sender != NULL)
3932 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3933 if (signal_data_array != NULL)
3934 schedule_callbacks (connection, signal_data_array, message, sender);
3937 /* collect subscribers not matching on sender */
3938 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3939 if (signal_data_array != NULL)
3940 schedule_callbacks (connection, signal_data_array, message, sender);
3943 /* ---------------------------------------------------------------------------------------------------- */
3945 /* only called from finalize(), removes all subscriptions */
3946 static void
3947 purge_all_signal_subscriptions (GDBusConnection *connection)
3949 GHashTableIter iter;
3950 gpointer key;
3951 GArray *ids;
3952 GArray *subscribers;
3953 guint n;
3955 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3956 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3957 while (g_hash_table_iter_next (&iter, &key, NULL))
3959 guint subscription_id = GPOINTER_TO_UINT (key);
3960 g_array_append_val (ids, subscription_id);
3963 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3964 for (n = 0; n < ids->len; n++)
3966 guint subscription_id = g_array_index (ids, guint, n);
3967 unsubscribe_id_internal (connection,
3968 subscription_id,
3969 subscribers);
3971 g_array_free (ids, TRUE);
3973 /* call GDestroyNotify without lock held */
3974 for (n = 0; n < subscribers->len; n++)
3976 SignalSubscriber *subscriber;
3977 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3978 call_destroy_notify (subscriber->context,
3979 subscriber->user_data_free_func,
3980 subscriber->user_data);
3981 g_main_context_unref (subscriber->context);
3984 g_array_free (subscribers, TRUE);
3987 /* ---------------------------------------------------------------------------------------------------- */
3989 static GDBusInterfaceVTable *
3990 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3992 /* Don't waste memory by copying padding - remember to update this
3993 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3995 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3998 static void
3999 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
4001 g_free (vtable);
4004 /* ---------------------------------------------------------------------------------------------------- */
4006 static GDBusSubtreeVTable *
4007 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
4009 /* Don't waste memory by copying padding - remember to update this
4010 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
4012 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4015 static void
4016 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
4018 g_free (vtable);
4021 /* ---------------------------------------------------------------------------------------------------- */
4023 struct ExportedObject
4025 gchar *object_path;
4026 GDBusConnection *connection;
4028 /* maps gchar* -> ExportedInterface* */
4029 GHashTable *map_if_name_to_ei;
4032 /* only called with lock held */
4033 static void
4034 exported_object_free (ExportedObject *eo)
4036 g_free (eo->object_path);
4037 g_hash_table_unref (eo->map_if_name_to_ei);
4038 g_free (eo);
4041 typedef struct
4043 ExportedObject *eo;
4045 guint id;
4046 gchar *interface_name;
4047 GDBusInterfaceVTable *vtable;
4048 GDBusInterfaceInfo *interface_info;
4050 GMainContext *context;
4051 gpointer user_data;
4052 GDestroyNotify user_data_free_func;
4053 } ExportedInterface;
4055 /* called with lock held */
4056 static void
4057 exported_interface_free (ExportedInterface *ei)
4059 g_dbus_interface_info_cache_release (ei->interface_info);
4060 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
4062 call_destroy_notify (ei->context,
4063 ei->user_data_free_func,
4064 ei->user_data);
4066 g_main_context_unref (ei->context);
4068 g_free (ei->interface_name);
4069 _g_dbus_interface_vtable_free (ei->vtable);
4070 g_free (ei);
4073 /* ---------------------------------------------------------------------------------------------------- */
4075 /* Convenience function to check if @registration_id (if not zero) or
4076 * @subtree_registration_id (if not zero) has been unregistered. If
4077 * so, returns %TRUE.
4079 * May be called by any thread. Caller must *not* hold lock.
4081 static gboolean
4082 has_object_been_unregistered (GDBusConnection *connection,
4083 guint registration_id,
4084 guint subtree_registration_id)
4086 gboolean ret;
4088 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4090 ret = FALSE;
4092 CONNECTION_LOCK (connection);
4093 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
4094 GUINT_TO_POINTER (registration_id)) == NULL)
4096 ret = TRUE;
4098 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
4099 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
4101 ret = TRUE;
4103 CONNECTION_UNLOCK (connection);
4105 return ret;
4108 /* ---------------------------------------------------------------------------------------------------- */
4110 typedef struct
4112 GDBusConnection *connection;
4113 GDBusMessage *message;
4114 gpointer user_data;
4115 const gchar *property_name;
4116 const GDBusInterfaceVTable *vtable;
4117 GDBusInterfaceInfo *interface_info;
4118 const GDBusPropertyInfo *property_info;
4119 guint registration_id;
4120 guint subtree_registration_id;
4121 } PropertyData;
4123 static void
4124 property_data_free (PropertyData *data)
4126 g_object_unref (data->connection);
4127 g_object_unref (data->message);
4128 g_free (data);
4131 /* called in thread where object was registered - no locks held */
4132 static gboolean
4133 invoke_get_property_in_idle_cb (gpointer _data)
4135 PropertyData *data = _data;
4136 GVariant *value;
4137 GError *error;
4138 GDBusMessage *reply;
4140 if (has_object_been_unregistered (data->connection,
4141 data->registration_id,
4142 data->subtree_registration_id))
4144 reply = g_dbus_message_new_method_error (data->message,
4145 "org.freedesktop.DBus.Error.UnknownMethod",
4146 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4147 g_dbus_message_get_path (data->message));
4148 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4149 g_object_unref (reply);
4150 goto out;
4153 error = NULL;
4154 value = data->vtable->get_property (data->connection,
4155 g_dbus_message_get_sender (data->message),
4156 g_dbus_message_get_path (data->message),
4157 data->interface_info->name,
4158 data->property_name,
4159 &error,
4160 data->user_data);
4163 if (value != NULL)
4165 g_assert_no_error (error);
4167 g_variant_take_ref (value);
4168 reply = g_dbus_message_new_method_reply (data->message);
4169 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4170 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4171 g_variant_unref (value);
4172 g_object_unref (reply);
4174 else
4176 gchar *dbus_error_name;
4177 g_assert (error != NULL);
4178 dbus_error_name = g_dbus_error_encode_gerror (error);
4179 reply = g_dbus_message_new_method_error_literal (data->message,
4180 dbus_error_name,
4181 error->message);
4182 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4183 g_free (dbus_error_name);
4184 g_error_free (error);
4185 g_object_unref (reply);
4188 out:
4189 return FALSE;
4192 /* called in thread where object was registered - no locks held */
4193 static gboolean
4194 invoke_set_property_in_idle_cb (gpointer _data)
4196 PropertyData *data = _data;
4197 GError *error;
4198 GDBusMessage *reply;
4199 GVariant *value;
4201 error = NULL;
4202 value = NULL;
4204 g_variant_get (g_dbus_message_get_body (data->message),
4205 "(ssv)",
4206 NULL,
4207 NULL,
4208 &value);
4210 if (!data->vtable->set_property (data->connection,
4211 g_dbus_message_get_sender (data->message),
4212 g_dbus_message_get_path (data->message),
4213 data->interface_info->name,
4214 data->property_name,
4215 value,
4216 &error,
4217 data->user_data))
4219 gchar *dbus_error_name;
4220 g_assert (error != NULL);
4221 dbus_error_name = g_dbus_error_encode_gerror (error);
4222 reply = g_dbus_message_new_method_error_literal (data->message,
4223 dbus_error_name,
4224 error->message);
4225 g_free (dbus_error_name);
4226 g_error_free (error);
4228 else
4230 reply = g_dbus_message_new_method_reply (data->message);
4233 g_assert (reply != NULL);
4234 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4235 g_object_unref (reply);
4236 g_variant_unref (value);
4238 return FALSE;
4241 /* called in any thread with connection's lock held */
4242 static gboolean
4243 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4244 GDBusMessage *message,
4245 guint registration_id,
4246 guint subtree_registration_id,
4247 gboolean is_get,
4248 GDBusInterfaceInfo *interface_info,
4249 const GDBusInterfaceVTable *vtable,
4250 GMainContext *main_context,
4251 gpointer user_data)
4253 gboolean handled;
4254 const char *interface_name;
4255 const char *property_name;
4256 const GDBusPropertyInfo *property_info;
4257 GSource *idle_source;
4258 PropertyData *property_data;
4259 GDBusMessage *reply;
4261 handled = FALSE;
4263 if (is_get)
4264 g_variant_get (g_dbus_message_get_body (message),
4265 "(&s&s)",
4266 &interface_name,
4267 &property_name);
4268 else
4269 g_variant_get (g_dbus_message_get_body (message),
4270 "(&s&sv)",
4271 &interface_name,
4272 &property_name,
4273 NULL);
4275 if (vtable == NULL)
4276 goto out;
4278 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4280 property_info = NULL;
4282 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4283 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4284 if (property_info == NULL)
4286 reply = g_dbus_message_new_method_error (message,
4287 "org.freedesktop.DBus.Error.InvalidArgs",
4288 _("No such property '%s'"),
4289 property_name);
4290 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4291 g_object_unref (reply);
4292 handled = TRUE;
4293 goto out;
4296 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4298 reply = g_dbus_message_new_method_error (message,
4299 "org.freedesktop.DBus.Error.InvalidArgs",
4300 _("Property '%s' is not readable"),
4301 property_name);
4302 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4303 g_object_unref (reply);
4304 handled = TRUE;
4305 goto out;
4307 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4309 reply = g_dbus_message_new_method_error (message,
4310 "org.freedesktop.DBus.Error.InvalidArgs",
4311 _("Property '%s' is not writable"),
4312 property_name);
4313 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4314 g_object_unref (reply);
4315 handled = TRUE;
4316 goto out;
4319 if (!is_get)
4321 GVariant *value;
4323 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4324 * of the given value is wrong
4326 g_variant_get_child (g_dbus_message_get_body (message), 2, "v", &value);
4327 if (g_strcmp0 (g_variant_get_type_string (value), property_info->signature) != 0)
4329 reply = g_dbus_message_new_method_error (message,
4330 "org.freedesktop.DBus.Error.InvalidArgs",
4331 _("Error setting property '%s': Expected type '%s' but got '%s'"),
4332 property_name, property_info->signature,
4333 g_variant_get_type_string (value));
4334 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4335 g_variant_unref (value);
4336 g_object_unref (reply);
4337 handled = TRUE;
4338 goto out;
4341 g_variant_unref (value);
4344 /* If the vtable pointer for get_property() resp. set_property() is
4345 * NULL then dispatch the call via the method_call() handler.
4347 if (is_get)
4349 if (vtable->get_property == NULL)
4351 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4352 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4353 vtable, main_context, user_data);
4354 handled = TRUE;
4355 goto out;
4358 else
4360 if (vtable->set_property == NULL)
4362 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4363 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4364 vtable, main_context, user_data);
4365 handled = TRUE;
4366 goto out;
4370 /* ok, got the property info - call user code in an idle handler */
4371 property_data = g_new0 (PropertyData, 1);
4372 property_data->connection = g_object_ref (connection);
4373 property_data->message = g_object_ref (message);
4374 property_data->user_data = user_data;
4375 property_data->property_name = property_name;
4376 property_data->vtable = vtable;
4377 property_data->interface_info = interface_info;
4378 property_data->property_info = property_info;
4379 property_data->registration_id = registration_id;
4380 property_data->subtree_registration_id = subtree_registration_id;
4382 idle_source = g_idle_source_new ();
4383 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4384 g_source_set_callback (idle_source,
4385 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4386 property_data,
4387 (GDestroyNotify) property_data_free);
4388 g_source_attach (idle_source, main_context);
4389 g_source_unref (idle_source);
4391 handled = TRUE;
4393 out:
4394 return handled;
4397 /* called in GDBusWorker thread with connection's lock held */
4398 static gboolean
4399 handle_getset_property (GDBusConnection *connection,
4400 ExportedObject *eo,
4401 GDBusMessage *message,
4402 gboolean is_get)
4404 ExportedInterface *ei;
4405 gboolean handled;
4406 const char *interface_name;
4407 const char *property_name;
4409 handled = FALSE;
4411 if (is_get)
4412 g_variant_get (g_dbus_message_get_body (message),
4413 "(&s&s)",
4414 &interface_name,
4415 &property_name);
4416 else
4417 g_variant_get (g_dbus_message_get_body (message),
4418 "(&s&sv)",
4419 &interface_name,
4420 &property_name,
4421 NULL);
4423 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4424 * no such interface registered
4426 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4427 if (ei == NULL)
4429 GDBusMessage *reply;
4430 reply = g_dbus_message_new_method_error (message,
4431 "org.freedesktop.DBus.Error.InvalidArgs",
4432 _("No such interface '%s'"),
4433 interface_name);
4434 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4435 g_object_unref (reply);
4436 handled = TRUE;
4437 goto out;
4440 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4441 message,
4442 ei->id,
4444 is_get,
4445 ei->interface_info,
4446 ei->vtable,
4447 ei->context,
4448 ei->user_data);
4449 out:
4450 return handled;
4453 /* ---------------------------------------------------------------------------------------------------- */
4455 typedef struct
4457 GDBusConnection *connection;
4458 GDBusMessage *message;
4459 gpointer user_data;
4460 const GDBusInterfaceVTable *vtable;
4461 GDBusInterfaceInfo *interface_info;
4462 guint registration_id;
4463 guint subtree_registration_id;
4464 } PropertyGetAllData;
4466 static void
4467 property_get_all_data_free (PropertyData *data)
4469 g_object_unref (data->connection);
4470 g_object_unref (data->message);
4471 g_free (data);
4474 /* called in thread where object was registered - no locks held */
4475 static gboolean
4476 invoke_get_all_properties_in_idle_cb (gpointer _data)
4478 PropertyGetAllData *data = _data;
4479 GVariantBuilder builder;
4480 GDBusMessage *reply;
4481 guint n;
4483 if (has_object_been_unregistered (data->connection,
4484 data->registration_id,
4485 data->subtree_registration_id))
4487 reply = g_dbus_message_new_method_error (data->message,
4488 "org.freedesktop.DBus.Error.UnknownMethod",
4489 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4490 g_dbus_message_get_path (data->message));
4491 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4492 g_object_unref (reply);
4493 goto out;
4496 /* TODO: Right now we never fail this call - we just omit values if
4497 * a get_property() call is failing.
4499 * We could fail the whole call if just a single get_property() call
4500 * returns an error. We need clarification in the D-Bus spec about this.
4502 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4503 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4504 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4506 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4507 GVariant *value;
4509 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4510 continue;
4512 value = data->vtable->get_property (data->connection,
4513 g_dbus_message_get_sender (data->message),
4514 g_dbus_message_get_path (data->message),
4515 data->interface_info->name,
4516 property_info->name,
4517 NULL,
4518 data->user_data);
4520 if (value == NULL)
4521 continue;
4523 g_variant_take_ref (value);
4524 g_variant_builder_add (&builder,
4525 "{sv}",
4526 property_info->name,
4527 value);
4528 g_variant_unref (value);
4530 g_variant_builder_close (&builder);
4532 reply = g_dbus_message_new_method_reply (data->message);
4533 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4534 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4535 g_object_unref (reply);
4537 out:
4538 return FALSE;
4541 static gboolean
4542 interface_has_readable_properties (GDBusInterfaceInfo *interface_info)
4544 gint i;
4546 if (!interface_info->properties)
4547 return FALSE;
4549 for (i = 0; interface_info->properties[i]; i++)
4550 if (interface_info->properties[i]->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE)
4551 return TRUE;
4553 return FALSE;
4556 /* called in any thread with connection's lock held */
4557 static gboolean
4558 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4559 GDBusMessage *message,
4560 guint registration_id,
4561 guint subtree_registration_id,
4562 GDBusInterfaceInfo *interface_info,
4563 const GDBusInterfaceVTable *vtable,
4564 GMainContext *main_context,
4565 gpointer user_data)
4567 gboolean handled;
4568 GSource *idle_source;
4569 PropertyGetAllData *property_get_all_data;
4571 handled = FALSE;
4573 if (vtable == NULL)
4574 goto out;
4576 /* If the vtable pointer for get_property() is NULL but we have a
4577 * non-zero number of readable properties, then dispatch the call via
4578 * the method_call() handler.
4580 if (vtable->get_property == NULL && interface_has_readable_properties (interface_info))
4582 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4583 interface_info, NULL, NULL, g_dbus_message_get_body (message),
4584 vtable, main_context, user_data);
4585 handled = TRUE;
4586 goto out;
4589 /* ok, got the property info - call user in an idle handler */
4590 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4591 property_get_all_data->connection = g_object_ref (connection);
4592 property_get_all_data->message = g_object_ref (message);
4593 property_get_all_data->user_data = user_data;
4594 property_get_all_data->vtable = vtable;
4595 property_get_all_data->interface_info = interface_info;
4596 property_get_all_data->registration_id = registration_id;
4597 property_get_all_data->subtree_registration_id = subtree_registration_id;
4599 idle_source = g_idle_source_new ();
4600 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4601 g_source_set_callback (idle_source,
4602 invoke_get_all_properties_in_idle_cb,
4603 property_get_all_data,
4604 (GDestroyNotify) property_get_all_data_free);
4605 g_source_attach (idle_source, main_context);
4606 g_source_unref (idle_source);
4608 handled = TRUE;
4610 out:
4611 return handled;
4614 /* called in GDBusWorker thread with connection's lock held */
4615 static gboolean
4616 handle_get_all_properties (GDBusConnection *connection,
4617 ExportedObject *eo,
4618 GDBusMessage *message)
4620 ExportedInterface *ei;
4621 gboolean handled;
4622 const char *interface_name;
4624 handled = FALSE;
4626 g_variant_get (g_dbus_message_get_body (message),
4627 "(&s)",
4628 &interface_name);
4630 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4631 * no such interface registered
4633 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4634 if (ei == NULL)
4636 GDBusMessage *reply;
4637 reply = g_dbus_message_new_method_error (message,
4638 "org.freedesktop.DBus.Error.InvalidArgs",
4639 _("No such interface"),
4640 interface_name);
4641 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4642 g_object_unref (reply);
4643 handled = TRUE;
4644 goto out;
4647 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4648 message,
4649 ei->id,
4651 ei->interface_info,
4652 ei->vtable,
4653 ei->context,
4654 ei->user_data);
4655 out:
4656 return handled;
4659 /* ---------------------------------------------------------------------------------------------------- */
4661 static const gchar introspect_header[] =
4662 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4663 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4664 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4665 "<node>\n";
4667 static const gchar introspect_tail[] =
4668 "</node>\n";
4670 static const gchar introspect_properties_interface[] =
4671 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4672 " <method name=\"Get\">\n"
4673 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4674 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4675 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4676 " </method>\n"
4677 " <method name=\"GetAll\">\n"
4678 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4679 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4680 " </method>\n"
4681 " <method name=\"Set\">\n"
4682 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4683 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4684 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4685 " </method>\n"
4686 " <signal name=\"PropertiesChanged\">\n"
4687 " <arg type=\"s\" name=\"interface_name\"/>\n"
4688 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4689 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4690 " </signal>\n"
4691 " </interface>\n";
4693 static const gchar introspect_introspectable_interface[] =
4694 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4695 " <method name=\"Introspect\">\n"
4696 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4697 " </method>\n"
4698 " </interface>\n"
4699 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4700 " <method name=\"Ping\"/>\n"
4701 " <method name=\"GetMachineId\">\n"
4702 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4703 " </method>\n"
4704 " </interface>\n";
4706 static void
4707 introspect_append_header (GString *s)
4709 g_string_append (s, introspect_header);
4712 static void
4713 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4715 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4717 const gchar *begin;
4718 const gchar *end;
4719 gchar *s;
4721 begin = object_path + path_len;
4722 end = strchr (begin, '/');
4723 if (end != NULL)
4724 s = g_strndup (begin, end - begin);
4725 else
4726 s = g_strdup (begin);
4728 if (g_hash_table_lookup (set, s) == NULL)
4729 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
4730 else
4731 g_free (s);
4735 /* TODO: we want a nicer public interface for this */
4736 /* called in any thread with connection's lock held */
4737 static gchar **
4738 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4739 const gchar *path)
4741 GPtrArray *p;
4742 gchar **ret;
4743 GHashTableIter hash_iter;
4744 const gchar *object_path;
4745 gsize path_len;
4746 GHashTable *set;
4747 GList *keys;
4748 GList *l;
4750 CONNECTION_ENSURE_LOCK (connection);
4752 path_len = strlen (path);
4753 if (path_len > 1)
4754 path_len++;
4756 set = g_hash_table_new (g_str_hash, g_str_equal);
4758 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4759 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4760 maybe_add_path (path, path_len, object_path, set);
4762 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4763 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4764 maybe_add_path (path, path_len, object_path, set);
4766 p = g_ptr_array_new ();
4767 keys = g_hash_table_get_keys (set);
4768 for (l = keys; l != NULL; l = l->next)
4769 g_ptr_array_add (p, l->data);
4770 g_hash_table_unref (set);
4771 g_list_free (keys);
4773 g_ptr_array_add (p, NULL);
4774 ret = (gchar **) g_ptr_array_free (p, FALSE);
4775 return ret;
4778 /* called in any thread with connection's lock not held */
4779 static gchar **
4780 g_dbus_connection_list_registered (GDBusConnection *connection,
4781 const gchar *path)
4783 gchar **ret;
4784 CONNECTION_LOCK (connection);
4785 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4786 CONNECTION_UNLOCK (connection);
4787 return ret;
4790 /* called in GDBusWorker thread with connection's lock held */
4791 static gboolean
4792 handle_introspect (GDBusConnection *connection,
4793 ExportedObject *eo,
4794 GDBusMessage *message)
4796 guint n;
4797 GString *s;
4798 GDBusMessage *reply;
4799 GHashTableIter hash_iter;
4800 ExportedInterface *ei;
4801 gchar **registered;
4803 /* first the header with the standard interfaces */
4804 s = g_string_sized_new (sizeof (introspect_header) +
4805 sizeof (introspect_properties_interface) +
4806 sizeof (introspect_introspectable_interface) +
4807 sizeof (introspect_tail));
4808 introspect_append_header (s);
4809 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4810 "org.freedesktop.DBus.Properties"))
4811 g_string_append (s, introspect_properties_interface);
4813 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4814 "org.freedesktop.DBus.Introspectable"))
4815 g_string_append (s, introspect_introspectable_interface);
4817 /* then include the registered interfaces */
4818 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4819 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4820 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4822 /* finally include nodes registered below us */
4823 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4824 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4825 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4826 g_strfreev (registered);
4827 g_string_append (s, introspect_tail);
4829 reply = g_dbus_message_new_method_reply (message);
4830 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4831 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4832 g_object_unref (reply);
4833 g_string_free (s, TRUE);
4835 return TRUE;
4838 /* called in thread where object was registered - no locks held */
4839 static gboolean
4840 call_in_idle_cb (gpointer user_data)
4842 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4843 GDBusInterfaceVTable *vtable;
4844 guint registration_id;
4845 guint subtree_registration_id;
4847 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4848 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4850 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4851 registration_id,
4852 subtree_registration_id))
4854 GDBusMessage *reply;
4855 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4856 "org.freedesktop.DBus.Error.UnknownMethod",
4857 _("No such interface '%s' on object at path %s"),
4858 g_dbus_method_invocation_get_interface_name (invocation),
4859 g_dbus_method_invocation_get_object_path (invocation));
4860 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4861 g_object_unref (reply);
4862 goto out;
4865 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4866 g_assert (vtable != NULL && vtable->method_call != NULL);
4868 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4869 g_dbus_method_invocation_get_sender (invocation),
4870 g_dbus_method_invocation_get_object_path (invocation),
4871 g_dbus_method_invocation_get_interface_name (invocation),
4872 g_dbus_method_invocation_get_method_name (invocation),
4873 g_dbus_method_invocation_get_parameters (invocation),
4874 g_object_ref (invocation),
4875 g_dbus_method_invocation_get_user_data (invocation));
4877 out:
4878 return FALSE;
4881 /* called in GDBusWorker thread with connection's lock held */
4882 static void
4883 schedule_method_call (GDBusConnection *connection,
4884 GDBusMessage *message,
4885 guint registration_id,
4886 guint subtree_registration_id,
4887 const GDBusInterfaceInfo *interface_info,
4888 const GDBusMethodInfo *method_info,
4889 const GDBusPropertyInfo *property_info,
4890 GVariant *parameters,
4891 const GDBusInterfaceVTable *vtable,
4892 GMainContext *main_context,
4893 gpointer user_data)
4895 GDBusMethodInvocation *invocation;
4896 GSource *idle_source;
4898 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4899 g_dbus_message_get_path (message),
4900 g_dbus_message_get_interface (message),
4901 g_dbus_message_get_member (message),
4902 method_info,
4903 property_info,
4904 connection,
4905 message,
4906 parameters,
4907 user_data);
4909 /* TODO: would be nicer with a real MethodData like we already
4910 * have PropertyData and PropertyGetAllData... */
4911 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4912 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4913 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4915 idle_source = g_idle_source_new ();
4916 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4917 g_source_set_callback (idle_source,
4918 call_in_idle_cb,
4919 invocation,
4920 g_object_unref);
4921 g_source_attach (idle_source, main_context);
4922 g_source_unref (idle_source);
4925 /* called in GDBusWorker thread with connection's lock held */
4926 static gboolean
4927 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4928 GDBusMessage *message,
4929 guint registration_id,
4930 guint subtree_registration_id,
4931 GDBusInterfaceInfo *interface_info,
4932 const GDBusInterfaceVTable *vtable,
4933 GMainContext *main_context,
4934 gpointer user_data)
4936 GDBusMethodInfo *method_info;
4937 GDBusMessage *reply;
4938 GVariant *parameters;
4939 gboolean handled;
4940 GVariantType *in_type;
4942 handled = FALSE;
4944 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4945 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4947 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4948 * error to the caller
4950 if (method_info == NULL)
4952 reply = g_dbus_message_new_method_error (message,
4953 "org.freedesktop.DBus.Error.UnknownMethod",
4954 _("No such method '%s'"),
4955 g_dbus_message_get_member (message));
4956 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4957 g_object_unref (reply);
4958 handled = TRUE;
4959 goto out;
4962 parameters = g_dbus_message_get_body (message);
4963 if (parameters == NULL)
4965 parameters = g_variant_new ("()");
4966 g_variant_ref_sink (parameters);
4968 else
4970 g_variant_ref (parameters);
4973 /* Check that the incoming args are of the right type - if they are not, return
4974 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4976 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4977 if (!g_variant_is_of_type (parameters, in_type))
4979 gchar *type_string;
4981 type_string = g_variant_type_dup_string (in_type);
4983 reply = g_dbus_message_new_method_error (message,
4984 "org.freedesktop.DBus.Error.InvalidArgs",
4985 _("Type of message, '%s', does not match expected type '%s'"),
4986 g_variant_get_type_string (parameters),
4987 type_string);
4988 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4989 g_variant_type_free (in_type);
4990 g_variant_unref (parameters);
4991 g_object_unref (reply);
4992 g_free (type_string);
4993 handled = TRUE;
4994 goto out;
4996 g_variant_type_free (in_type);
4998 /* schedule the call in idle */
4999 schedule_method_call (connection, message, registration_id, subtree_registration_id,
5000 interface_info, method_info, NULL, parameters,
5001 vtable, main_context, user_data);
5002 g_variant_unref (parameters);
5003 handled = TRUE;
5005 out:
5006 return handled;
5009 /* ---------------------------------------------------------------------------------------------------- */
5011 /* called in GDBusWorker thread with connection's lock held */
5012 static gboolean
5013 obj_message_func (GDBusConnection *connection,
5014 ExportedObject *eo,
5015 GDBusMessage *message)
5017 const gchar *interface_name;
5018 const gchar *member;
5019 const gchar *signature;
5020 gboolean handled;
5022 handled = FALSE;
5024 interface_name = g_dbus_message_get_interface (message);
5025 member = g_dbus_message_get_member (message);
5026 signature = g_dbus_message_get_signature (message);
5028 /* see if we have an interface for handling this call */
5029 if (interface_name != NULL)
5031 ExportedInterface *ei;
5032 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5033 if (ei != NULL)
5035 /* we do - invoke the handler in idle in the right thread */
5037 /* handle no vtable or handler being present */
5038 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
5039 goto out;
5041 handled = validate_and_maybe_schedule_method_call (connection,
5042 message,
5043 ei->id,
5045 ei->interface_info,
5046 ei->vtable,
5047 ei->context,
5048 ei->user_data);
5049 goto out;
5053 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5054 g_strcmp0 (member, "Introspect") == 0 &&
5055 g_strcmp0 (signature, "") == 0)
5057 handled = handle_introspect (connection, eo, message);
5058 goto out;
5060 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5061 g_strcmp0 (member, "Get") == 0 &&
5062 g_strcmp0 (signature, "ss") == 0)
5064 handled = handle_getset_property (connection, eo, message, TRUE);
5065 goto out;
5067 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5068 g_strcmp0 (member, "Set") == 0 &&
5069 g_strcmp0 (signature, "ssv") == 0)
5071 handled = handle_getset_property (connection, eo, message, FALSE);
5072 goto out;
5074 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5075 g_strcmp0 (member, "GetAll") == 0 &&
5076 g_strcmp0 (signature, "s") == 0)
5078 handled = handle_get_all_properties (connection, eo, message);
5079 goto out;
5082 out:
5083 return handled;
5087 * g_dbus_connection_register_object:
5088 * @connection: A #GDBusConnection.
5089 * @object_path: The object path to register at.
5090 * @interface_info: Introspection data for the interface.
5091 * @vtable: (allow-none): A #GDBusInterfaceVTable to call into or %NULL.
5092 * @user_data: (allow-none): Data to pass to functions in @vtable.
5093 * @user_data_free_func: Function to call when the object path is unregistered.
5094 * @error: Return location for error or %NULL.
5096 * Registers callbacks for exported objects at @object_path with the
5097 * D-Bus interface that is described in @interface_info.
5099 * Calls to functions in @vtable (and @user_data_free_func) will
5100 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
5101 * loop</link> of the thread you are calling this method from.
5103 * Note that all #GVariant values passed to functions in @vtable will match
5104 * the signature given in @interface_info - if a remote caller passes
5105 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
5106 * is returned to the remote caller.
5108 * Additionally, if the remote caller attempts to invoke methods or
5109 * access properties not mentioned in @interface_info the
5110 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
5111 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
5112 * are returned to the caller.
5114 * It is considered a programming error if the
5115 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
5116 * #GVariant of incorrect type.
5118 * If an existing callback is already registered at @object_path and
5119 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
5121 * GDBus automatically implements the standard D-Bus interfaces
5122 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
5123 * and org.freedesktop.Peer, so you don't have to implement those for
5124 * the objects you export. You <emphasis>can</emphasis> implement
5125 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
5126 * and setting of properties asynchronously.
5128 * Note that the reference count on @interface_info will be
5129 * incremented by 1 (unless allocated statically, e.g. if the
5130 * reference count is -1, see g_dbus_interface_info_ref()) for as long
5131 * as the object is exported. Also note that @vtable will be copied.
5133 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
5135 * Returns: 0 if @error is set, otherwise a registration id (never 0)
5136 * that can be used with g_dbus_connection_unregister_object() .
5138 * Since: 2.26
5140 guint
5141 g_dbus_connection_register_object (GDBusConnection *connection,
5142 const gchar *object_path,
5143 GDBusInterfaceInfo *interface_info,
5144 const GDBusInterfaceVTable *vtable,
5145 gpointer user_data,
5146 GDestroyNotify user_data_free_func,
5147 GError **error)
5149 ExportedObject *eo;
5150 ExportedInterface *ei;
5151 guint ret;
5153 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5154 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5155 g_return_val_if_fail (interface_info != NULL, 0);
5156 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
5157 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5158 g_return_val_if_fail (check_initialized (connection), 0);
5160 ret = 0;
5162 CONNECTION_LOCK (connection);
5164 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5165 if (eo == NULL)
5167 eo = g_new0 (ExportedObject, 1);
5168 eo->object_path = g_strdup (object_path);
5169 eo->connection = connection;
5170 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
5171 g_str_equal,
5172 NULL,
5173 (GDestroyNotify) exported_interface_free);
5174 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
5177 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
5178 if (ei != NULL)
5180 g_set_error (error,
5181 G_IO_ERROR,
5182 G_IO_ERROR_EXISTS,
5183 _("An object is already exported for the interface %s at %s"),
5184 interface_info->name,
5185 object_path);
5186 goto out;
5189 ei = g_new0 (ExportedInterface, 1);
5190 ei->id = _global_registration_id++; /* TODO: overflow etc. */
5191 ei->eo = eo;
5192 ei->user_data = user_data;
5193 ei->user_data_free_func = user_data_free_func;
5194 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
5195 ei->interface_info = g_dbus_interface_info_ref (interface_info);
5196 g_dbus_interface_info_cache_build (ei->interface_info);
5197 ei->interface_name = g_strdup (interface_info->name);
5198 ei->context = g_main_context_ref_thread_default ();
5200 g_hash_table_insert (eo->map_if_name_to_ei,
5201 (gpointer) ei->interface_name,
5202 ei);
5203 g_hash_table_insert (connection->map_id_to_ei,
5204 GUINT_TO_POINTER (ei->id),
5205 ei);
5207 ret = ei->id;
5209 out:
5210 CONNECTION_UNLOCK (connection);
5212 return ret;
5216 * g_dbus_connection_unregister_object:
5217 * @connection: A #GDBusConnection.
5218 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
5220 * Unregisters an object.
5222 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
5224 * Since: 2.26
5226 gboolean
5227 g_dbus_connection_unregister_object (GDBusConnection *connection,
5228 guint registration_id)
5230 ExportedInterface *ei;
5231 ExportedObject *eo;
5232 gboolean ret;
5234 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5235 g_return_val_if_fail (check_initialized (connection), FALSE);
5237 ret = FALSE;
5239 CONNECTION_LOCK (connection);
5241 ei = g_hash_table_lookup (connection->map_id_to_ei,
5242 GUINT_TO_POINTER (registration_id));
5243 if (ei == NULL)
5244 goto out;
5246 eo = ei->eo;
5248 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5249 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5250 /* unregister object path if we have no more exported interfaces */
5251 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5252 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5253 eo->object_path));
5255 ret = TRUE;
5257 out:
5258 CONNECTION_UNLOCK (connection);
5260 return ret;
5263 /* ---------------------------------------------------------------------------------------------------- */
5266 * g_dbus_connection_emit_signal:
5267 * @connection: A #GDBusConnection.
5268 * @destination_bus_name: (allow-none): The unique bus name for the destination
5269 * for the signal or %NULL to emit to all listeners.
5270 * @object_path: Path of remote object.
5271 * @interface_name: D-Bus interface to emit a signal on.
5272 * @signal_name: The name of the signal to emit.
5273 * @parameters: (allow-none): A #GVariant tuple with parameters for the signal
5274 * or %NULL if not passing parameters.
5275 * @error: Return location for error or %NULL.
5277 * Emits a signal.
5279 * If the parameters GVariant is floating, it is consumed.
5281 * This can only fail if @parameters is not compatible with the D-Bus protocol.
5283 * Returns: %TRUE unless @error is set.
5285 * Since: 2.26
5287 gboolean
5288 g_dbus_connection_emit_signal (GDBusConnection *connection,
5289 const gchar *destination_bus_name,
5290 const gchar *object_path,
5291 const gchar *interface_name,
5292 const gchar *signal_name,
5293 GVariant *parameters,
5294 GError **error)
5296 GDBusMessage *message;
5297 gboolean ret;
5299 message = NULL;
5300 ret = FALSE;
5302 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5303 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5304 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5305 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5306 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5307 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5308 g_return_val_if_fail (check_initialized (connection), FALSE);
5310 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5312 _g_dbus_debug_print_lock ();
5313 g_print ("========================================================================\n"
5314 "GDBus-debug:Emission:\n"
5315 " >>>> SIGNAL EMISSION %s.%s()\n"
5316 " on object %s\n"
5317 " destination %s\n",
5318 interface_name, signal_name,
5319 object_path,
5320 destination_bus_name != NULL ? destination_bus_name : "(none)");
5321 _g_dbus_debug_print_unlock ();
5324 message = g_dbus_message_new_signal (object_path,
5325 interface_name,
5326 signal_name);
5328 if (destination_bus_name != NULL)
5329 g_dbus_message_set_header (message,
5330 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5331 g_variant_new_string (destination_bus_name));
5333 if (parameters != NULL)
5334 g_dbus_message_set_body (message, parameters);
5336 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5337 g_object_unref (message);
5339 return ret;
5342 static void
5343 add_call_flags (GDBusMessage *message,
5344 GDBusCallFlags flags)
5346 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5347 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
5350 static GVariant *
5351 decode_method_reply (GDBusMessage *reply,
5352 const gchar *method_name,
5353 const GVariantType *reply_type,
5354 GUnixFDList **out_fd_list,
5355 GError **error)
5357 GVariant *result;
5359 result = NULL;
5360 switch (g_dbus_message_get_message_type (reply))
5362 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5363 result = g_dbus_message_get_body (reply);
5364 if (result == NULL)
5366 result = g_variant_new ("()");
5367 g_variant_ref_sink (result);
5369 else
5371 g_variant_ref (result);
5374 if (!g_variant_is_of_type (result, reply_type))
5376 gchar *type_string = g_variant_type_dup_string (reply_type);
5378 g_set_error (error,
5379 G_IO_ERROR,
5380 G_IO_ERROR_INVALID_ARGUMENT,
5381 _("Method '%s' returned type '%s', but expected '%s'"),
5382 method_name, g_variant_get_type_string (result), type_string);
5384 g_variant_unref (result);
5385 g_free (type_string);
5386 result = NULL;
5389 #ifdef G_OS_UNIX
5390 if (result != NULL)
5392 if (out_fd_list != NULL)
5394 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5395 if (*out_fd_list != NULL)
5396 g_object_ref (*out_fd_list);
5399 #endif
5400 break;
5402 case G_DBUS_MESSAGE_TYPE_ERROR:
5403 g_dbus_message_to_gerror (reply, error);
5404 break;
5406 default:
5407 g_assert_not_reached ();
5408 break;
5411 return result;
5415 typedef struct
5417 GSimpleAsyncResult *simple;
5418 GVariantType *reply_type;
5419 gchar *method_name; /* for error message */
5420 guint32 serial;
5422 GVariant *value;
5423 GUnixFDList *fd_list;
5424 } CallState;
5426 static void
5427 call_state_free (CallState *state)
5429 g_variant_type_free (state->reply_type);
5430 g_free (state->method_name);
5432 if (state->value != NULL)
5433 g_variant_unref (state->value);
5434 if (state->fd_list != NULL)
5435 g_object_unref (state->fd_list);
5436 g_slice_free (CallState, state);
5439 /* called in any thread, with the connection's lock not held */
5440 static void
5441 g_dbus_connection_call_done (GObject *source,
5442 GAsyncResult *result,
5443 gpointer user_data)
5445 GSimpleAsyncResult *simple;
5446 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5447 CallState *state = user_data;
5448 GError *error;
5449 GDBusMessage *reply;
5451 error = NULL;
5452 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5453 result,
5454 &error);
5456 if (G_UNLIKELY (_g_dbus_debug_call ()))
5458 _g_dbus_debug_print_lock ();
5459 g_print ("========================================================================\n"
5460 "GDBus-debug:Call:\n"
5461 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5462 " ",
5463 state->method_name,
5464 state->serial);
5465 if (reply != NULL)
5467 g_print ("SUCCESS\n");
5469 else
5471 g_print ("FAILED: %s\n",
5472 error->message);
5474 _g_dbus_debug_print_unlock ();
5477 if (reply != NULL)
5478 state->value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5480 simple = state->simple; /* why? because state is freed before we unref simple.. */
5481 if (error != NULL)
5483 g_simple_async_result_take_error (state->simple, error);
5484 g_simple_async_result_complete (state->simple);
5485 call_state_free (state);
5487 else
5489 g_simple_async_result_set_op_res_gpointer (state->simple, state, (GDestroyNotify) call_state_free);
5490 g_simple_async_result_complete (state->simple);
5492 g_clear_object (&reply);
5493 g_object_unref (simple);
5496 /* called in any thread, with the connection's lock not held */
5497 static void
5498 g_dbus_connection_call_internal (GDBusConnection *connection,
5499 const gchar *bus_name,
5500 const gchar *object_path,
5501 const gchar *interface_name,
5502 const gchar *method_name,
5503 GVariant *parameters,
5504 const GVariantType *reply_type,
5505 GDBusCallFlags flags,
5506 gint timeout_msec,
5507 GUnixFDList *fd_list,
5508 GCancellable *cancellable,
5509 GAsyncReadyCallback callback,
5510 gpointer user_data)
5512 GDBusMessage *message;
5513 guint32 serial;
5515 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5516 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5517 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5518 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5519 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5520 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5521 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5522 g_return_if_fail (check_initialized (connection));
5523 #ifdef G_OS_UNIX
5524 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5525 #else
5526 g_return_if_fail (fd_list == NULL);
5527 #endif
5529 message = g_dbus_message_new_method_call (bus_name,
5530 object_path,
5531 interface_name,
5532 method_name);
5533 add_call_flags (message, flags);
5534 if (parameters != NULL)
5535 g_dbus_message_set_body (message, parameters);
5537 #ifdef G_OS_UNIX
5538 if (fd_list != NULL)
5539 g_dbus_message_set_unix_fd_list (message, fd_list);
5540 #endif
5542 /* If the user has no callback then we can just send the message with
5543 * the G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set and skip all
5544 * the logic for processing the reply. If the service sends the reply
5545 * anyway then it will just be ignored.
5547 if (callback != NULL)
5549 CallState *state;
5551 state = g_slice_new0 (CallState);
5552 state->simple = g_simple_async_result_new (G_OBJECT (connection),
5553 callback, user_data,
5554 g_dbus_connection_call_internal);
5555 g_simple_async_result_set_check_cancellable (state->simple, cancellable);
5556 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5558 if (reply_type == NULL)
5559 reply_type = G_VARIANT_TYPE_ANY;
5561 state->reply_type = g_variant_type_copy (reply_type);
5563 g_dbus_connection_send_message_with_reply (connection,
5564 message,
5565 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5566 timeout_msec,
5567 &state->serial,
5568 cancellable,
5569 g_dbus_connection_call_done,
5570 state);
5571 serial = state->serial;
5573 else
5575 GDBusMessageFlags flags;
5577 flags = g_dbus_message_get_flags (message);
5578 flags |= G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
5579 g_dbus_message_set_flags (message, flags);
5581 g_dbus_connection_send_message (connection,
5582 message,
5583 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5584 &serial, NULL);
5587 if (G_UNLIKELY (_g_dbus_debug_call ()))
5589 _g_dbus_debug_print_lock ();
5590 g_print ("========================================================================\n"
5591 "GDBus-debug:Call:\n"
5592 " >>>> ASYNC %s.%s()\n"
5593 " on object %s\n"
5594 " owned by name %s (serial %d)\n",
5595 interface_name,
5596 method_name,
5597 object_path,
5598 bus_name != NULL ? bus_name : "(none)",
5599 serial);
5600 _g_dbus_debug_print_unlock ();
5603 if (message != NULL)
5604 g_object_unref (message);
5607 /* called in any thread, with the connection's lock not held */
5608 static GVariant *
5609 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
5610 GUnixFDList **out_fd_list,
5611 GAsyncResult *res,
5612 GError **error)
5614 GSimpleAsyncResult *simple;
5615 CallState *state;
5617 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5618 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
5619 g_dbus_connection_call_internal), NULL);
5620 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5622 simple = G_SIMPLE_ASYNC_RESULT (res);
5624 if (g_simple_async_result_propagate_error (simple, error))
5625 return NULL;
5627 state = g_simple_async_result_get_op_res_gpointer (simple);
5628 if (out_fd_list != NULL)
5629 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
5630 return g_variant_ref (state->value);
5633 /* called in any user thread, with the connection's lock not held */
5634 static GVariant *
5635 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
5636 const gchar *bus_name,
5637 const gchar *object_path,
5638 const gchar *interface_name,
5639 const gchar *method_name,
5640 GVariant *parameters,
5641 const GVariantType *reply_type,
5642 GDBusCallFlags flags,
5643 gint timeout_msec,
5644 GUnixFDList *fd_list,
5645 GUnixFDList **out_fd_list,
5646 GCancellable *cancellable,
5647 GError **error)
5649 GDBusMessage *message;
5650 GDBusMessage *reply;
5651 GVariant *result;
5652 GError *local_error;
5653 GDBusSendMessageFlags send_flags;
5655 message = NULL;
5656 reply = NULL;
5657 result = NULL;
5659 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5660 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5661 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5662 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5663 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5664 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5665 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5666 #ifdef G_OS_UNIX
5667 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
5668 #else
5669 g_return_val_if_fail (fd_list == NULL, NULL);
5670 #endif
5671 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5673 if (!(flags & CALL_FLAGS_INITIALIZING))
5674 g_return_val_if_fail (check_initialized (connection), FALSE);
5676 if (reply_type == NULL)
5677 reply_type = G_VARIANT_TYPE_ANY;
5679 message = g_dbus_message_new_method_call (bus_name,
5680 object_path,
5681 interface_name,
5682 method_name);
5683 add_call_flags (message, flags);
5684 if (parameters != NULL)
5685 g_dbus_message_set_body (message, parameters);
5687 #ifdef G_OS_UNIX
5688 if (fd_list != NULL)
5689 g_dbus_message_set_unix_fd_list (message, fd_list);
5690 #endif
5692 if (G_UNLIKELY (_g_dbus_debug_call ()))
5694 _g_dbus_debug_print_lock ();
5695 g_print ("========================================================================\n"
5696 "GDBus-debug:Call:\n"
5697 " >>>> SYNC %s.%s()\n"
5698 " on object %s\n"
5699 " owned by name %s\n",
5700 interface_name,
5701 method_name,
5702 object_path,
5703 bus_name != NULL ? bus_name : "(none)");
5704 _g_dbus_debug_print_unlock ();
5707 local_error = NULL;
5709 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
5711 /* translate from one flavour of flags to another... */
5712 if (flags & CALL_FLAGS_INITIALIZING)
5713 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
5715 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5716 message,
5717 send_flags,
5718 timeout_msec,
5719 NULL, /* volatile guint32 *out_serial */
5720 cancellable,
5721 &local_error);
5723 if (G_UNLIKELY (_g_dbus_debug_call ()))
5725 _g_dbus_debug_print_lock ();
5726 g_print ("========================================================================\n"
5727 "GDBus-debug:Call:\n"
5728 " <<<< SYNC COMPLETE %s.%s()\n"
5729 " ",
5730 interface_name,
5731 method_name);
5732 if (reply != NULL)
5734 g_print ("SUCCESS\n");
5736 else
5738 g_print ("FAILED: %s\n",
5739 local_error->message);
5741 _g_dbus_debug_print_unlock ();
5744 if (reply == NULL)
5746 if (error != NULL)
5747 *error = local_error;
5748 else
5749 g_error_free (local_error);
5750 goto out;
5753 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
5755 out:
5756 if (message != NULL)
5757 g_object_unref (message);
5758 if (reply != NULL)
5759 g_object_unref (reply);
5761 return result;
5764 /* ---------------------------------------------------------------------------------------------------- */
5767 * g_dbus_connection_call:
5768 * @connection: A #GDBusConnection.
5769 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5770 * @connection is not a message bus connection.
5771 * @object_path: Path of remote object.
5772 * @interface_name: D-Bus interface to invoke method on.
5773 * @method_name: The name of the method to invoke.
5774 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5775 * or %NULL if not passing parameters.
5776 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5777 * @flags: Flags from the #GDBusCallFlags enumeration.
5778 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5779 * timeout or %G_MAXINT for no timeout.
5780 * @cancellable: (allow-none): A #GCancellable or %NULL.
5781 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5782 * satisfied or %NULL if you don't care about the result of the
5783 * method invocation.
5784 * @user_data: The data to pass to @callback.
5786 * Asynchronously invokes the @method_name method on the
5787 * @interface_name D-Bus interface on the remote object at
5788 * @object_path owned by @bus_name.
5790 * If @connection is closed then the operation will fail with
5791 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
5792 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
5793 * not compatible with the D-Bus protocol, the operation fails with
5794 * %G_IO_ERROR_INVALID_ARGUMENT.
5796 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
5797 * error will be raised if it does not match. Said another way, if you give a @reply_type
5798 * then any non-%NULL return value will be of this type.
5800 * If the @parameters #GVariant is floating, it is consumed. This allows
5801 * convenient 'inline' use of g_variant_new(), e.g.:
5802 * |[
5803 * g_dbus_connection_call (connection,
5804 * "org.freedesktop.StringThings",
5805 * "/org/freedesktop/StringThings",
5806 * "org.freedesktop.StringThings",
5807 * "TwoStrings",
5808 * g_variant_new ("(ss)",
5809 * "Thing One",
5810 * "Thing Two"),
5811 * NULL,
5812 * G_DBUS_CALL_FLAGS_NONE,
5813 * -1,
5814 * NULL,
5815 * (GAsyncReadyCallback) two_strings_done,
5816 * NULL);
5817 * ]|
5819 * This is an asynchronous method. When the operation is finished, @callback will be invoked
5820 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
5821 * of the thread you are calling this method from. You can then call
5822 * g_dbus_connection_call_finish() to get the result of the operation.
5823 * See g_dbus_connection_call_sync() for the synchronous version of this
5824 * function.
5826 * If @callback is %NULL then the D-Bus method call message will be sent with
5827 * the %G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set.
5829 * Since: 2.26
5831 void
5832 g_dbus_connection_call (GDBusConnection *connection,
5833 const gchar *bus_name,
5834 const gchar *object_path,
5835 const gchar *interface_name,
5836 const gchar *method_name,
5837 GVariant *parameters,
5838 const GVariantType *reply_type,
5839 GDBusCallFlags flags,
5840 gint timeout_msec,
5841 GCancellable *cancellable,
5842 GAsyncReadyCallback callback,
5843 gpointer user_data)
5845 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);
5849 * g_dbus_connection_call_finish:
5850 * @connection: A #GDBusConnection.
5851 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
5852 * @error: Return location for error or %NULL.
5854 * Finishes an operation started with g_dbus_connection_call().
5856 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5857 * return values. Free with g_variant_unref().
5859 * Since: 2.26
5861 GVariant *
5862 g_dbus_connection_call_finish (GDBusConnection *connection,
5863 GAsyncResult *res,
5864 GError **error)
5866 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
5870 * g_dbus_connection_call_sync:
5871 * @connection: A #GDBusConnection.
5872 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5873 * @connection is not a message bus connection.
5874 * @object_path: Path of remote object.
5875 * @interface_name: D-Bus interface to invoke method on.
5876 * @method_name: The name of the method to invoke.
5877 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5878 * or %NULL if not passing parameters.
5879 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5880 * @flags: Flags from the #GDBusCallFlags enumeration.
5881 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5882 * timeout or %G_MAXINT for no timeout.
5883 * @cancellable: (allow-none): A #GCancellable or %NULL.
5884 * @error: Return location for error or %NULL.
5886 * Synchronously invokes the @method_name method on the
5887 * @interface_name D-Bus interface on the remote object at
5888 * @object_path owned by @bus_name.
5890 * If @connection is closed then the operation will fail with
5891 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
5892 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
5893 * contains a value not compatible with the D-Bus protocol, the operation
5894 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
5896 * If @reply_type is non-%NULL then the reply will be checked for having
5897 * this type and an error will be raised if it does not match. Said
5898 * another way, if you give a @reply_type then any non-%NULL return
5899 * value will be of this type.
5901 * If the @parameters #GVariant is floating, it is consumed.
5902 * This allows convenient 'inline' use of g_variant_new(), e.g.:
5903 * |[
5904 * g_dbus_connection_call_sync (connection,
5905 * "org.freedesktop.StringThings",
5906 * "/org/freedesktop/StringThings",
5907 * "org.freedesktop.StringThings",
5908 * "TwoStrings",
5909 * g_variant_new ("(ss)",
5910 * "Thing One",
5911 * "Thing Two"),
5912 * NULL,
5913 * G_DBUS_CALL_FLAGS_NONE,
5914 * -1,
5915 * NULL,
5916 * &amp;error);
5917 * ]|
5919 * The calling thread is blocked until a reply is received. See
5920 * g_dbus_connection_call() for the asynchronous version of
5921 * this method.
5923 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5924 * return values. Free with g_variant_unref().
5926 * Since: 2.26
5928 GVariant *
5929 g_dbus_connection_call_sync (GDBusConnection *connection,
5930 const gchar *bus_name,
5931 const gchar *object_path,
5932 const gchar *interface_name,
5933 const gchar *method_name,
5934 GVariant *parameters,
5935 const GVariantType *reply_type,
5936 GDBusCallFlags flags,
5937 gint timeout_msec,
5938 GCancellable *cancellable,
5939 GError **error)
5941 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);
5944 /* ---------------------------------------------------------------------------------------------------- */
5946 #ifdef G_OS_UNIX
5949 * g_dbus_connection_call_with_unix_fd_list:
5950 * @connection: A #GDBusConnection.
5951 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5952 * @connection is not a message bus connection.
5953 * @object_path: Path of remote object.
5954 * @interface_name: D-Bus interface to invoke method on.
5955 * @method_name: The name of the method to invoke.
5956 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5957 * or %NULL if not passing parameters.
5958 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5959 * @flags: Flags from the #GDBusCallFlags enumeration.
5960 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5961 * timeout or %G_MAXINT for no timeout.
5962 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
5963 * @cancellable: (allow-none): A #GCancellable or %NULL.
5964 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5965 * satisfied or %NULL if you don't * care about the result of the
5966 * method invocation.
5967 * @user_data: The data to pass to @callback.
5969 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
5971 * This method is only available on UNIX.
5973 * Since: 2.30
5975 void
5976 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
5977 const gchar *bus_name,
5978 const gchar *object_path,
5979 const gchar *interface_name,
5980 const gchar *method_name,
5981 GVariant *parameters,
5982 const GVariantType *reply_type,
5983 GDBusCallFlags flags,
5984 gint timeout_msec,
5985 GUnixFDList *fd_list,
5986 GCancellable *cancellable,
5987 GAsyncReadyCallback callback,
5988 gpointer user_data)
5990 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);
5994 * g_dbus_connection_call_with_unix_fd_list_finish:
5995 * @connection: A #GDBusConnection.
5996 * @out_fd_list: (out) (allow-none): Return location for a #GUnixFDList or %NULL.
5997 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call_with_unix_fd_list().
5998 * @error: Return location for error or %NULL.
6000 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
6002 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6003 * return values. Free with g_variant_unref().
6005 * Since: 2.30
6007 GVariant *
6008 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
6009 GUnixFDList **out_fd_list,
6010 GAsyncResult *res,
6011 GError **error)
6013 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
6017 * g_dbus_connection_call_with_unix_fd_list_sync:
6018 * @connection: A #GDBusConnection.
6019 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
6020 * @connection is not a message bus connection.
6021 * @object_path: Path of remote object.
6022 * @interface_name: D-Bus interface to invoke method on.
6023 * @method_name: The name of the method to invoke.
6024 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
6025 * or %NULL if not passing parameters.
6026 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
6027 * @flags: Flags from the #GDBusCallFlags enumeration.
6028 * @timeout_msec: The timeout in milliseconds, -1 to use the default
6029 * timeout or %G_MAXINT for no timeout.
6030 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
6031 * @out_fd_list: (out) (allow-none): Return location for a #GUnixFDList or %NULL.
6032 * @cancellable: (allow-none): A #GCancellable or %NULL.
6033 * @error: Return location for error or %NULL.
6035 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
6037 * This method is only available on UNIX.
6039 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6040 * return values. Free with g_variant_unref().
6042 * Since: 2.30
6044 GVariant *
6045 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
6046 const gchar *bus_name,
6047 const gchar *object_path,
6048 const gchar *interface_name,
6049 const gchar *method_name,
6050 GVariant *parameters,
6051 const GVariantType *reply_type,
6052 GDBusCallFlags flags,
6053 gint timeout_msec,
6054 GUnixFDList *fd_list,
6055 GUnixFDList **out_fd_list,
6056 GCancellable *cancellable,
6057 GError **error)
6059 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);
6062 #endif /* G_OS_UNIX */
6064 /* ---------------------------------------------------------------------------------------------------- */
6066 struct ExportedSubtree
6068 guint id;
6069 gchar *object_path;
6070 GDBusConnection *connection;
6071 GDBusSubtreeVTable *vtable;
6072 GDBusSubtreeFlags flags;
6074 GMainContext *context;
6075 gpointer user_data;
6076 GDestroyNotify user_data_free_func;
6079 static void
6080 exported_subtree_free (ExportedSubtree *es)
6082 call_destroy_notify (es->context,
6083 es->user_data_free_func,
6084 es->user_data);
6086 g_main_context_unref (es->context);
6088 _g_dbus_subtree_vtable_free (es->vtable);
6089 g_free (es->object_path);
6090 g_free (es);
6093 /* called without lock held in the thread where the caller registered
6094 * the subtree
6096 static gboolean
6097 handle_subtree_introspect (GDBusConnection *connection,
6098 ExportedSubtree *es,
6099 GDBusMessage *message)
6101 GString *s;
6102 gboolean handled;
6103 GDBusMessage *reply;
6104 gchar **children;
6105 gboolean is_root;
6106 const gchar *sender;
6107 const gchar *requested_object_path;
6108 const gchar *requested_node;
6109 GDBusInterfaceInfo **interfaces;
6110 guint n;
6111 gchar **subnode_paths;
6112 gboolean has_properties_interface;
6113 gboolean has_introspectable_interface;
6115 handled = FALSE;
6117 requested_object_path = g_dbus_message_get_path (message);
6118 sender = g_dbus_message_get_sender (message);
6119 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6121 s = g_string_new (NULL);
6122 introspect_append_header (s);
6124 /* Strictly we don't need the children in dynamic mode, but we avoid the
6125 * conditionals to preserve code clarity
6127 children = es->vtable->enumerate (es->connection,
6128 sender,
6129 es->object_path,
6130 es->user_data);
6132 if (!is_root)
6134 requested_node = strrchr (requested_object_path, '/') + 1;
6136 /* Assert existence of object if we are not dynamic */
6137 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
6138 !_g_strv_has_string ((const gchar * const *) children, requested_node))
6139 goto out;
6141 else
6143 requested_node = NULL;
6146 interfaces = es->vtable->introspect (es->connection,
6147 sender,
6148 es->object_path,
6149 requested_node,
6150 es->user_data);
6151 if (interfaces != NULL)
6153 has_properties_interface = FALSE;
6154 has_introspectable_interface = FALSE;
6156 for (n = 0; interfaces[n] != NULL; n++)
6158 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
6159 has_properties_interface = TRUE;
6160 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
6161 has_introspectable_interface = TRUE;
6163 if (!has_properties_interface)
6164 g_string_append (s, introspect_properties_interface);
6165 if (!has_introspectable_interface)
6166 g_string_append (s, introspect_introspectable_interface);
6168 for (n = 0; interfaces[n] != NULL; n++)
6170 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
6171 g_dbus_interface_info_unref (interfaces[n]);
6173 g_free (interfaces);
6176 /* then include <node> entries from the Subtree for the root */
6177 if (is_root)
6179 for (n = 0; children != NULL && children[n] != NULL; n++)
6180 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
6183 /* finally include nodes registered below us */
6184 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
6185 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
6186 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
6187 g_strfreev (subnode_paths);
6189 g_string_append (s, "</node>\n");
6191 reply = g_dbus_message_new_method_reply (message);
6192 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6193 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6194 g_object_unref (reply);
6196 handled = TRUE;
6198 out:
6199 g_string_free (s, TRUE);
6200 g_strfreev (children);
6201 return handled;
6204 /* called without lock held in the thread where the caller registered
6205 * the subtree
6207 static gboolean
6208 handle_subtree_method_invocation (GDBusConnection *connection,
6209 ExportedSubtree *es,
6210 GDBusMessage *message)
6212 gboolean handled;
6213 const gchar *sender;
6214 const gchar *interface_name;
6215 const gchar *member;
6216 const gchar *signature;
6217 const gchar *requested_object_path;
6218 const gchar *requested_node;
6219 gboolean is_root;
6220 GDBusInterfaceInfo *interface_info;
6221 const GDBusInterfaceVTable *interface_vtable;
6222 gpointer interface_user_data;
6223 guint n;
6224 GDBusInterfaceInfo **interfaces;
6225 gboolean is_property_get;
6226 gboolean is_property_set;
6227 gboolean is_property_get_all;
6229 handled = FALSE;
6230 interfaces = NULL;
6232 requested_object_path = g_dbus_message_get_path (message);
6233 sender = g_dbus_message_get_sender (message);
6234 interface_name = g_dbus_message_get_interface (message);
6235 member = g_dbus_message_get_member (message);
6236 signature = g_dbus_message_get_signature (message);
6237 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6239 is_property_get = FALSE;
6240 is_property_set = FALSE;
6241 is_property_get_all = FALSE;
6242 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6244 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6245 is_property_get = TRUE;
6246 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6247 is_property_set = TRUE;
6248 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6249 is_property_get_all = TRUE;
6252 if (!is_root)
6254 requested_node = strrchr (requested_object_path, '/') + 1;
6256 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6258 /* We don't want to dispatch to unenumerated
6259 * nodes, so ensure that the child exists.
6261 gchar **children;
6262 gboolean exists;
6264 children = es->vtable->enumerate (es->connection,
6265 sender,
6266 es->object_path,
6267 es->user_data);
6269 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6270 g_strfreev (children);
6272 if (!exists)
6273 goto out;
6276 else
6278 requested_node = NULL;
6281 /* get introspection data for the node */
6282 interfaces = es->vtable->introspect (es->connection,
6283 sender,
6284 requested_object_path,
6285 requested_node,
6286 es->user_data);
6288 if (interfaces == NULL)
6289 goto out;
6291 interface_info = NULL;
6292 for (n = 0; interfaces[n] != NULL; n++)
6294 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6295 interface_info = interfaces[n];
6298 /* dispatch the call if the user wants to handle it */
6299 if (interface_info != NULL)
6301 /* figure out where to dispatch the method call */
6302 interface_user_data = NULL;
6303 interface_vtable = es->vtable->dispatch (es->connection,
6304 sender,
6305 es->object_path,
6306 interface_name,
6307 requested_node,
6308 &interface_user_data,
6309 es->user_data);
6310 if (interface_vtable == NULL)
6311 goto out;
6313 CONNECTION_LOCK (connection);
6314 handled = validate_and_maybe_schedule_method_call (es->connection,
6315 message,
6317 es->id,
6318 interface_info,
6319 interface_vtable,
6320 es->context,
6321 interface_user_data);
6322 CONNECTION_UNLOCK (connection);
6324 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6325 else if (is_property_get || is_property_set || is_property_get_all)
6327 if (is_property_get)
6328 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6329 else if (is_property_set)
6330 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6331 else if (is_property_get_all)
6332 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6333 else
6334 g_assert_not_reached ();
6336 /* see if the object supports this interface at all */
6337 for (n = 0; interfaces[n] != NULL; n++)
6339 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6340 interface_info = interfaces[n];
6343 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6344 * claims it won't support the interface
6346 if (interface_info == NULL)
6348 GDBusMessage *reply;
6349 reply = g_dbus_message_new_method_error (message,
6350 "org.freedesktop.DBus.Error.InvalidArgs",
6351 _("No such interface '%s'"),
6352 interface_name);
6353 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6354 g_object_unref (reply);
6355 handled = TRUE;
6356 goto out;
6359 /* figure out where to dispatch the property get/set/getall calls */
6360 interface_user_data = NULL;
6361 interface_vtable = es->vtable->dispatch (es->connection,
6362 sender,
6363 es->object_path,
6364 interface_name,
6365 requested_node,
6366 &interface_user_data,
6367 es->user_data);
6368 if (interface_vtable == NULL)
6370 g_warning ("The subtree introspection function indicates that '%s' "
6371 "is a valid interface name, but calling the dispatch "
6372 "function on that interface gave us NULL", interface_name);
6373 goto out;
6376 if (is_property_get || is_property_set)
6378 CONNECTION_LOCK (connection);
6379 handled = validate_and_maybe_schedule_property_getset (es->connection,
6380 message,
6382 es->id,
6383 is_property_get,
6384 interface_info,
6385 interface_vtable,
6386 es->context,
6387 interface_user_data);
6388 CONNECTION_UNLOCK (connection);
6390 else if (is_property_get_all)
6392 CONNECTION_LOCK (connection);
6393 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6394 message,
6396 es->id,
6397 interface_info,
6398 interface_vtable,
6399 es->context,
6400 interface_user_data);
6401 CONNECTION_UNLOCK (connection);
6405 out:
6406 if (interfaces != NULL)
6408 for (n = 0; interfaces[n] != NULL; n++)
6409 g_dbus_interface_info_unref (interfaces[n]);
6410 g_free (interfaces);
6413 return handled;
6416 typedef struct
6418 GDBusMessage *message;
6419 ExportedSubtree *es;
6420 } SubtreeDeferredData;
6422 static void
6423 subtree_deferred_data_free (SubtreeDeferredData *data)
6425 g_object_unref (data->message);
6426 g_free (data);
6429 /* called without lock held in the thread where the caller registered the subtree */
6430 static gboolean
6431 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6433 SubtreeDeferredData *data = _data;
6434 gboolean handled;
6436 handled = FALSE;
6438 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6439 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6440 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6441 handled = handle_subtree_introspect (data->es->connection,
6442 data->es,
6443 data->message);
6444 else
6445 handled = handle_subtree_method_invocation (data->es->connection,
6446 data->es,
6447 data->message);
6449 if (!handled)
6451 CONNECTION_LOCK (data->es->connection);
6452 handled = handle_generic_unlocked (data->es->connection, data->message);
6453 CONNECTION_UNLOCK (data->es->connection);
6456 /* if we couldn't handle the request, just bail with the UnknownMethod error */
6457 if (!handled)
6459 GDBusMessage *reply;
6460 reply = g_dbus_message_new_method_error (data->message,
6461 "org.freedesktop.DBus.Error.UnknownMethod",
6462 _("Method '%s' on interface '%s' with signature '%s' does not exist"),
6463 g_dbus_message_get_member (data->message),
6464 g_dbus_message_get_interface (data->message),
6465 g_dbus_message_get_signature (data->message));
6466 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6467 g_object_unref (reply);
6470 return FALSE;
6473 /* called in GDBusWorker thread with connection's lock held */
6474 static gboolean
6475 subtree_message_func (GDBusConnection *connection,
6476 ExportedSubtree *es,
6477 GDBusMessage *message)
6479 GSource *idle_source;
6480 SubtreeDeferredData *data;
6482 data = g_new0 (SubtreeDeferredData, 1);
6483 data->message = g_object_ref (message);
6484 data->es = es;
6486 /* defer this call to an idle handler in the right thread */
6487 idle_source = g_idle_source_new ();
6488 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
6489 g_source_set_callback (idle_source,
6490 process_subtree_vtable_message_in_idle_cb,
6491 data,
6492 (GDestroyNotify) subtree_deferred_data_free);
6493 g_source_attach (idle_source, es->context);
6494 g_source_unref (idle_source);
6496 /* since we own the entire subtree, handlers for objects not in the subtree have been
6497 * tried already by libdbus-1 - so we just need to ensure that we're always going
6498 * to reply to the message
6500 return TRUE;
6504 * g_dbus_connection_register_subtree:
6505 * @connection: A #GDBusConnection.
6506 * @object_path: The object path to register the subtree at.
6507 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
6508 * @flags: Flags used to fine tune the behavior of the subtree.
6509 * @user_data: Data to pass to functions in @vtable.
6510 * @user_data_free_func: Function to call when the subtree is unregistered.
6511 * @error: Return location for error or %NULL.
6513 * Registers a whole subtree of <quote>dynamic</quote> objects.
6515 * The @enumerate and @introspection functions in @vtable are used to
6516 * convey, to remote callers, what nodes exist in the subtree rooted
6517 * by @object_path.
6519 * When handling remote calls into any node in the subtree, first the
6520 * @enumerate function is used to check if the node exists. If the node exists
6521 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6522 * the @introspection function is used to check if the node supports the
6523 * requested method. If so, the @dispatch function is used to determine
6524 * where to dispatch the call. The collected #GDBusInterfaceVTable and
6525 * #gpointer will be used to call into the interface vtable for processing
6526 * the request.
6528 * All calls into user-provided code will be invoked in the <link
6529 * linkend="g-main-context-push-thread-default">thread-default main
6530 * loop</link> of the thread you are calling this method from.
6532 * If an existing subtree is already registered at @object_path or
6533 * then @error is set to #G_IO_ERROR_EXISTS.
6535 * Note that it is valid to register regular objects (using
6536 * g_dbus_connection_register_object()) in a subtree registered with
6537 * g_dbus_connection_register_subtree() - if so, the subtree handler
6538 * is tried as the last resort. One way to think about a subtree
6539 * handler is to consider it a <quote>fallback handler</quote>
6540 * for object paths not registered via g_dbus_connection_register_object()
6541 * or other bindings.
6543 * Note that @vtable will be copied so you cannot change it after
6544 * registration.
6546 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
6548 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
6549 * that can be used with g_dbus_connection_unregister_subtree() .
6551 * Since: 2.26
6553 guint
6554 g_dbus_connection_register_subtree (GDBusConnection *connection,
6555 const gchar *object_path,
6556 const GDBusSubtreeVTable *vtable,
6557 GDBusSubtreeFlags flags,
6558 gpointer user_data,
6559 GDestroyNotify user_data_free_func,
6560 GError **error)
6562 guint ret;
6563 ExportedSubtree *es;
6565 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
6566 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
6567 g_return_val_if_fail (vtable != NULL, 0);
6568 g_return_val_if_fail (error == NULL || *error == NULL, 0);
6569 g_return_val_if_fail (check_initialized (connection), 0);
6571 ret = 0;
6573 CONNECTION_LOCK (connection);
6575 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6576 if (es != NULL)
6578 g_set_error (error,
6579 G_IO_ERROR,
6580 G_IO_ERROR_EXISTS,
6581 _("A subtree is already exported for %s"),
6582 object_path);
6583 goto out;
6586 es = g_new0 (ExportedSubtree, 1);
6587 es->object_path = g_strdup (object_path);
6588 es->connection = connection;
6590 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
6591 es->flags = flags;
6592 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
6593 es->user_data = user_data;
6594 es->user_data_free_func = user_data_free_func;
6595 es->context = g_main_context_ref_thread_default ();
6597 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
6598 g_hash_table_insert (connection->map_id_to_es,
6599 GUINT_TO_POINTER (es->id),
6600 es);
6602 ret = es->id;
6604 out:
6605 CONNECTION_UNLOCK (connection);
6607 return ret;
6610 /* ---------------------------------------------------------------------------------------------------- */
6613 * g_dbus_connection_unregister_subtree:
6614 * @connection: A #GDBusConnection.
6615 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
6617 * Unregisters a subtree.
6619 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
6621 * Since: 2.26
6623 gboolean
6624 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
6625 guint registration_id)
6627 ExportedSubtree *es;
6628 gboolean ret;
6630 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
6631 g_return_val_if_fail (check_initialized (connection), FALSE);
6633 ret = FALSE;
6635 CONNECTION_LOCK (connection);
6637 es = g_hash_table_lookup (connection->map_id_to_es,
6638 GUINT_TO_POINTER (registration_id));
6639 if (es == NULL)
6640 goto out;
6642 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
6643 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
6645 ret = TRUE;
6647 out:
6648 CONNECTION_UNLOCK (connection);
6650 return ret;
6653 /* ---------------------------------------------------------------------------------------------------- */
6655 /* may be called in any thread, with connection's lock held */
6656 static void
6657 handle_generic_ping_unlocked (GDBusConnection *connection,
6658 const gchar *object_path,
6659 GDBusMessage *message)
6661 GDBusMessage *reply;
6662 reply = g_dbus_message_new_method_reply (message);
6663 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6664 g_object_unref (reply);
6667 /* may be called in any thread, with connection's lock held */
6668 static void
6669 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
6670 const gchar *object_path,
6671 GDBusMessage *message)
6673 GDBusMessage *reply;
6675 reply = NULL;
6676 if (connection->machine_id == NULL)
6678 GError *error;
6680 error = NULL;
6681 connection->machine_id = _g_dbus_get_machine_id (&error);
6682 if (connection->machine_id == NULL)
6684 reply = g_dbus_message_new_method_error_literal (message,
6685 "org.freedesktop.DBus.Error.Failed",
6686 error->message);
6687 g_error_free (error);
6691 if (reply == NULL)
6693 reply = g_dbus_message_new_method_reply (message);
6694 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
6696 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6697 g_object_unref (reply);
6700 /* may be called in any thread, with connection's lock held */
6701 static void
6702 handle_generic_introspect_unlocked (GDBusConnection *connection,
6703 const gchar *object_path,
6704 GDBusMessage *message)
6706 guint n;
6707 GString *s;
6708 gchar **registered;
6709 GDBusMessage *reply;
6711 /* first the header */
6712 s = g_string_new (NULL);
6713 introspect_append_header (s);
6715 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
6716 for (n = 0; registered != NULL && registered[n] != NULL; n++)
6717 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
6718 g_strfreev (registered);
6719 g_string_append (s, "</node>\n");
6721 reply = g_dbus_message_new_method_reply (message);
6722 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6723 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6724 g_object_unref (reply);
6725 g_string_free (s, TRUE);
6728 /* may be called in any thread, with connection's lock held */
6729 static gboolean
6730 handle_generic_unlocked (GDBusConnection *connection,
6731 GDBusMessage *message)
6733 gboolean handled;
6734 const gchar *interface_name;
6735 const gchar *member;
6736 const gchar *signature;
6737 const gchar *path;
6739 CONNECTION_ENSURE_LOCK (connection);
6741 handled = FALSE;
6743 interface_name = g_dbus_message_get_interface (message);
6744 member = g_dbus_message_get_member (message);
6745 signature = g_dbus_message_get_signature (message);
6746 path = g_dbus_message_get_path (message);
6748 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
6749 g_strcmp0 (member, "Introspect") == 0 &&
6750 g_strcmp0 (signature, "") == 0)
6752 handle_generic_introspect_unlocked (connection, path, message);
6753 handled = TRUE;
6755 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6756 g_strcmp0 (member, "Ping") == 0 &&
6757 g_strcmp0 (signature, "") == 0)
6759 handle_generic_ping_unlocked (connection, path, message);
6760 handled = TRUE;
6762 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6763 g_strcmp0 (member, "GetMachineId") == 0 &&
6764 g_strcmp0 (signature, "") == 0)
6766 handle_generic_get_machine_id_unlocked (connection, path, message);
6767 handled = TRUE;
6770 return handled;
6773 /* ---------------------------------------------------------------------------------------------------- */
6775 /* called in GDBusWorker thread with connection's lock held */
6776 static void
6777 distribute_method_call (GDBusConnection *connection,
6778 GDBusMessage *message)
6780 GDBusMessage *reply;
6781 ExportedObject *eo;
6782 ExportedSubtree *es;
6783 const gchar *object_path;
6784 const gchar *interface_name;
6785 const gchar *member;
6786 const gchar *path;
6787 gchar *subtree_path;
6788 gchar *needle;
6790 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
6792 interface_name = g_dbus_message_get_interface (message);
6793 member = g_dbus_message_get_member (message);
6794 path = g_dbus_message_get_path (message);
6795 subtree_path = g_strdup (path);
6796 needle = strrchr (subtree_path, '/');
6797 if (needle != NULL && needle != subtree_path)
6799 *needle = '\0';
6801 else
6803 g_free (subtree_path);
6804 subtree_path = NULL;
6808 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
6810 _g_dbus_debug_print_lock ();
6811 g_print ("========================================================================\n"
6812 "GDBus-debug:Incoming:\n"
6813 " <<<< METHOD INVOCATION %s.%s()\n"
6814 " on object %s\n"
6815 " invoked by name %s\n"
6816 " serial %d\n",
6817 interface_name, member,
6818 path,
6819 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
6820 g_dbus_message_get_serial (message));
6821 _g_dbus_debug_print_unlock ();
6824 object_path = g_dbus_message_get_path (message);
6825 g_assert (object_path != NULL);
6827 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
6828 if (eo != NULL)
6830 if (obj_message_func (connection, eo, message))
6831 goto out;
6834 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6835 if (es != NULL)
6837 if (subtree_message_func (connection, es, message))
6838 goto out;
6841 if (subtree_path != NULL)
6843 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
6844 if (es != NULL)
6846 if (subtree_message_func (connection, es, message))
6847 goto out;
6851 if (handle_generic_unlocked (connection, message))
6852 goto out;
6854 /* if we end up here, the message has not been not handled - so return an error saying this */
6855 reply = g_dbus_message_new_method_error (message,
6856 "org.freedesktop.DBus.Error.UnknownMethod",
6857 _("No such interface '%s' on object at path %s"),
6858 interface_name,
6859 object_path);
6860 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6861 g_object_unref (reply);
6863 out:
6864 g_free (subtree_path);
6867 /* ---------------------------------------------------------------------------------------------------- */
6869 /* Called in any user thread, with the message_bus_lock held. */
6870 static GWeakRef *
6871 message_bus_get_singleton (GBusType bus_type,
6872 GError **error)
6874 GWeakRef *ret;
6875 const gchar *starter_bus;
6877 ret = NULL;
6879 switch (bus_type)
6881 case G_BUS_TYPE_SESSION:
6882 ret = &the_session_bus;
6883 break;
6885 case G_BUS_TYPE_SYSTEM:
6886 ret = &the_system_bus;
6887 break;
6889 case G_BUS_TYPE_STARTER:
6890 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
6891 if (g_strcmp0 (starter_bus, "session") == 0)
6893 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
6894 goto out;
6896 else if (g_strcmp0 (starter_bus, "system") == 0)
6898 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
6899 goto out;
6901 else
6903 if (starter_bus != NULL)
6905 g_set_error (error,
6906 G_IO_ERROR,
6907 G_IO_ERROR_INVALID_ARGUMENT,
6908 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
6909 " - unknown value '%s'"),
6910 starter_bus);
6912 else
6914 g_set_error_literal (error,
6915 G_IO_ERROR,
6916 G_IO_ERROR_INVALID_ARGUMENT,
6917 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
6918 "variable is not set"));
6921 break;
6923 default:
6924 g_assert_not_reached ();
6925 break;
6928 out:
6929 return ret;
6932 /* Called in any user thread, without holding locks. */
6933 static GDBusConnection *
6934 get_uninitialized_connection (GBusType bus_type,
6935 GCancellable *cancellable,
6936 GError **error)
6938 GWeakRef *singleton;
6939 GDBusConnection *ret;
6941 ret = NULL;
6943 G_LOCK (message_bus_lock);
6944 singleton = message_bus_get_singleton (bus_type, error);
6945 if (singleton == NULL)
6946 goto out;
6948 ret = g_weak_ref_get (singleton);
6950 if (ret == NULL)
6952 gchar *address;
6953 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
6954 if (address == NULL)
6955 goto out;
6956 ret = g_object_new (G_TYPE_DBUS_CONNECTION,
6957 "address", address,
6958 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
6959 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
6960 "exit-on-close", TRUE,
6961 NULL);
6963 g_weak_ref_set (singleton, ret);
6964 g_free (address);
6967 g_assert (ret != NULL);
6969 out:
6970 G_UNLOCK (message_bus_lock);
6971 return ret;
6974 /* May be called from any thread. Must not hold message_bus_lock. */
6975 GDBusConnection *
6976 _g_bus_get_singleton_if_exists (GBusType bus_type)
6978 GWeakRef *singleton;
6979 GDBusConnection *ret = NULL;
6981 G_LOCK (message_bus_lock);
6982 singleton = message_bus_get_singleton (bus_type, NULL);
6983 if (singleton == NULL)
6984 goto out;
6986 ret = g_weak_ref_get (singleton);
6988 out:
6989 G_UNLOCK (message_bus_lock);
6990 return ret;
6994 * g_bus_get_sync:
6995 * @bus_type: A #GBusType.
6996 * @cancellable: (allow-none): A #GCancellable or %NULL.
6997 * @error: Return location for error or %NULL.
6999 * Synchronously connects to the message bus specified by @bus_type.
7000 * Note that the returned object may shared with other callers,
7001 * e.g. if two separate parts of a process calls this function with
7002 * the same @bus_type, they will share the same object.
7004 * This is a synchronous failable function. See g_bus_get() and
7005 * g_bus_get_finish() for the asynchronous version.
7007 * The returned object is a singleton, that is, shared with other
7008 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7009 * event that you need a private message bus connection, use
7010 * g_dbus_address_get_for_bus_sync() and
7011 * g_dbus_connection_new_for_address().
7013 * Note that the returned #GDBusConnection object will (usually) have
7014 * the #GDBusConnection:exit-on-close property set to %TRUE.
7016 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
7018 * Since: 2.26
7020 GDBusConnection *
7021 g_bus_get_sync (GBusType bus_type,
7022 GCancellable *cancellable,
7023 GError **error)
7025 GDBusConnection *connection;
7027 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7029 connection = get_uninitialized_connection (bus_type, cancellable, error);
7030 if (connection == NULL)
7031 goto out;
7033 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
7035 g_object_unref (connection);
7036 connection = NULL;
7039 out:
7040 return connection;
7043 static void
7044 bus_get_async_initable_cb (GObject *source_object,
7045 GAsyncResult *res,
7046 gpointer user_data)
7048 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
7049 GError *error;
7051 error = NULL;
7052 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
7053 res,
7054 &error))
7056 g_assert (error != NULL);
7057 g_simple_async_result_take_error (simple, error);
7058 g_object_unref (source_object);
7060 else
7062 g_simple_async_result_set_op_res_gpointer (simple,
7063 source_object,
7064 g_object_unref);
7066 g_simple_async_result_complete_in_idle (simple);
7067 g_object_unref (simple);
7071 * g_bus_get:
7072 * @bus_type: A #GBusType.
7073 * @cancellable: (allow-none): A #GCancellable or %NULL.
7074 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
7075 * @user_data: The data to pass to @callback.
7077 * Asynchronously connects to the message bus specified by @bus_type.
7079 * When the operation is finished, @callback will be invoked. You can
7080 * then call g_bus_get_finish() to get the result of the operation.
7082 * This is a asynchronous failable function. See g_bus_get_sync() for
7083 * the synchronous version.
7085 * Since: 2.26
7087 void
7088 g_bus_get (GBusType bus_type,
7089 GCancellable *cancellable,
7090 GAsyncReadyCallback callback,
7091 gpointer user_data)
7093 GDBusConnection *connection;
7094 GSimpleAsyncResult *simple;
7095 GError *error;
7097 simple = g_simple_async_result_new (NULL,
7098 callback,
7099 user_data,
7100 g_bus_get);
7101 g_simple_async_result_set_check_cancellable (simple, cancellable);
7103 error = NULL;
7104 connection = get_uninitialized_connection (bus_type, cancellable, &error);
7105 if (connection == NULL)
7107 g_assert (error != NULL);
7108 g_simple_async_result_take_error (simple, error);
7109 g_simple_async_result_complete_in_idle (simple);
7110 g_object_unref (simple);
7112 else
7114 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
7115 G_PRIORITY_DEFAULT,
7116 cancellable,
7117 bus_get_async_initable_cb,
7118 simple);
7123 * g_bus_get_finish:
7124 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
7125 * @error: Return location for error or %NULL.
7127 * Finishes an operation started with g_bus_get().
7129 * The returned object is a singleton, that is, shared with other
7130 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7131 * event that you need a private message bus connection, use
7132 * g_dbus_address_get_for_bus_sync() and
7133 * g_dbus_connection_new_for_address().
7135 * Note that the returned #GDBusConnection object will (usually) have
7136 * the #GDBusConnection:exit-on-close property set to %TRUE.
7138 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
7140 * Since: 2.26
7142 GDBusConnection *
7143 g_bus_get_finish (GAsyncResult *res,
7144 GError **error)
7146 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
7147 GObject *object;
7148 GDBusConnection *ret;
7150 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7152 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
7154 ret = NULL;
7156 if (g_simple_async_result_propagate_error (simple, error))
7157 goto out;
7159 object = g_simple_async_result_get_op_res_gpointer (simple);
7160 g_assert (object != NULL);
7161 ret = g_object_ref (G_DBUS_CONNECTION (object));
7163 out:
7164 return ret;
7167 /* ---------------------------------------------------------------------------------------------------- */