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.1 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, see <http://www.gnu.org/licenses/>.
18 * Author: David Zeuthen <davidz@redhat.com>
26 #include "gdbusutils.h"
27 #include "gdbusnamewatching.h"
28 #include "gdbuserror.h"
29 #include "gdbusprivate.h"
30 #include "gdbusconnection.h"
35 * SECTION:gdbusnamewatching
36 * @title: Watching Bus Names
37 * @short_description: Simple API for watching bus names
40 * Convenience API for watching bus names.
42 * A simple example for watching a name can be found in
43 * [gdbus-example-watch-name.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-watch-name.c)
46 G_LOCK_DEFINE_STATIC (lock);
48 /* ---------------------------------------------------------------------------------------------------- */
52 PREVIOUS_CALL_NONE = 0,
53 PREVIOUS_CALL_APPEARED,
54 PREVIOUS_CALL_VANISHED,
59 gint ref_count; /* (atomic) */
62 GBusNameWatcherFlags flags;
64 GBusNameAppearedCallback name_appeared_handler;
65 GBusNameVanishedCallback name_vanished_handler;
67 GDestroyNotify user_data_free_func;
68 GMainContext *main_context;
70 GDBusConnection *connection;
71 gulong disconnected_signal_handler_id;
72 guint name_owner_changed_subscription_id;
74 PreviousCall previous_call;
80 /* Must be accessed atomically. */
81 static guint next_global_id = 1; /* (atomic) */
83 /* Must be accessed with @lock held. */
84 static GHashTable *map_id_to_client = NULL;
87 client_ref (Client *client)
89 g_atomic_int_inc (&client->ref_count);
94 client_unref (Client *client)
96 if (g_atomic_int_dec_and_test (&client->ref_count))
98 if (client->connection != NULL)
100 if (client->name_owner_changed_subscription_id > 0)
101 g_dbus_connection_signal_unsubscribe (client->connection, client->name_owner_changed_subscription_id);
102 if (client->disconnected_signal_handler_id > 0)
103 g_signal_handler_disconnect (client->connection, client->disconnected_signal_handler_id);
104 g_object_unref (client->connection);
106 g_free (client->name);
107 g_free (client->name_owner);
108 g_main_context_unref (client->main_context);
109 if (client->user_data_free_func != NULL)
110 client->user_data_free_func (client->user_data);
115 /* ---------------------------------------------------------------------------------------------------- */
119 CALL_TYPE_NAME_APPEARED,
120 CALL_TYPE_NAME_VANISHED
127 /* keep this separate because client->connection may
128 * be set to NULL after scheduling the call
130 GDBusConnection *connection;
139 call_handler_data_free (CallHandlerData *data)
141 if (data->connection != NULL)
142 g_object_unref (data->connection);
143 g_free (data->name_owner);
144 client_unref (data->client);
149 actually_do_call (Client *client, GDBusConnection *connection, const gchar *name_owner, CallType call_type)
151 /* The client might have been cancelled (g_bus_unwatch_name()) while we were
152 * sitting in the #GMainContext dispatch queue. */
153 if (client->cancelled)
158 case CALL_TYPE_NAME_APPEARED:
159 if (client->name_appeared_handler != NULL)
161 client->name_appeared_handler (connection,
168 case CALL_TYPE_NAME_VANISHED:
169 if (client->name_vanished_handler != NULL)
171 client->name_vanished_handler (connection,
178 g_assert_not_reached ();
184 call_in_idle_cb (gpointer _data)
186 CallHandlerData *data = _data;
187 actually_do_call (data->client, data->connection, data->name_owner, data->call_type);
192 schedule_call_in_idle (Client *client, CallType call_type)
194 CallHandlerData *data;
195 GSource *idle_source;
197 data = g_new0 (CallHandlerData, 1);
198 data->client = client_ref (client);
199 data->connection = client->connection != NULL ? g_object_ref (client->connection) : NULL;
200 data->name_owner = g_strdup (client->name_owner);
201 data->call_type = call_type;
203 idle_source = g_idle_source_new ();
204 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
205 g_source_set_callback (idle_source,
208 (GDestroyNotify) call_handler_data_free);
209 g_source_set_name (idle_source, "[gio, gdbusnamewatching.c] call_in_idle_cb");
210 g_source_attach (idle_source, client->main_context);
211 g_source_unref (idle_source);
215 do_call (Client *client, CallType call_type)
217 GMainContext *current_context;
219 /* only schedule in idle if we're not in the right thread */
220 current_context = g_main_context_ref_thread_default ();
221 if (current_context != client->main_context)
222 schedule_call_in_idle (client, call_type);
224 actually_do_call (client, client->connection, client->name_owner, call_type);
225 g_main_context_unref (current_context);
229 call_appeared_handler (Client *client)
231 if (client->previous_call != PREVIOUS_CALL_APPEARED)
233 client->previous_call = PREVIOUS_CALL_APPEARED;
234 if (!client->cancelled && client->name_appeared_handler != NULL)
236 do_call (client, CALL_TYPE_NAME_APPEARED);
242 call_vanished_handler (Client *client)
244 if (client->previous_call != PREVIOUS_CALL_VANISHED)
246 client->previous_call = PREVIOUS_CALL_VANISHED;
247 if (!client->cancelled && client->name_vanished_handler != NULL)
249 do_call (client, CALL_TYPE_NAME_VANISHED);
254 /* ---------------------------------------------------------------------------------------------------- */
256 /* Return a reference to the #Client for @watcher_id, or %NULL if it’s been
257 * unwatched. This is safe to call from any thread. */
259 dup_client (guint watcher_id)
265 g_assert (watcher_id != 0);
266 g_assert (map_id_to_client != NULL);
268 client = g_hash_table_lookup (map_id_to_client, GUINT_TO_POINTER (watcher_id));
278 /* Could be called from any thread, so it could be called after client_unref()
279 * has started finalising the #Client. Avoid that by looking up the #Client
282 on_connection_disconnected (GDBusConnection *connection,
283 gboolean remote_peer_vanished,
287 guint watcher_id = GPOINTER_TO_UINT (user_data);
288 Client *client = NULL;
290 client = dup_client (watcher_id);
294 if (client->name_owner_changed_subscription_id > 0)
295 g_dbus_connection_signal_unsubscribe (client->connection, client->name_owner_changed_subscription_id);
296 if (client->disconnected_signal_handler_id > 0)
297 g_signal_handler_disconnect (client->connection, client->disconnected_signal_handler_id);
298 g_object_unref (client->connection);
299 client->disconnected_signal_handler_id = 0;
300 client->name_owner_changed_subscription_id = 0;
301 client->connection = NULL;
303 call_vanished_handler (client);
305 client_unref (client);
308 /* ---------------------------------------------------------------------------------------------------- */
310 /* Will always be called from the thread which acquired client->main_context. */
312 on_name_owner_changed (GDBusConnection *connection,
313 const gchar *sender_name,
314 const gchar *object_path,
315 const gchar *interface_name,
316 const gchar *signal_name,
317 GVariant *parameters,
320 guint watcher_id = GPOINTER_TO_UINT (user_data);
321 Client *client = NULL;
323 const gchar *old_owner;
324 const gchar *new_owner;
326 client = dup_client (watcher_id);
330 if (!client->initialized)
333 if (g_strcmp0 (object_path, "/org/freedesktop/DBus") != 0 ||
334 g_strcmp0 (interface_name, "org.freedesktop.DBus") != 0 ||
335 g_strcmp0 (sender_name, "org.freedesktop.DBus") != 0)
338 g_variant_get (parameters,
344 /* we only care about a specific name */
345 if (g_strcmp0 (name, client->name) != 0)
348 if ((old_owner != NULL && strlen (old_owner) > 0) && client->name_owner != NULL)
350 g_free (client->name_owner);
351 client->name_owner = NULL;
352 call_vanished_handler (client);
355 if (new_owner != NULL && strlen (new_owner) > 0)
357 g_warn_if_fail (client->name_owner == NULL);
358 g_free (client->name_owner);
359 client->name_owner = g_strdup (new_owner);
360 call_appeared_handler (client);
364 client_unref (client);
367 /* ---------------------------------------------------------------------------------------------------- */
370 get_name_owner_cb (GObject *source_object,
374 Client *client = user_data;
376 const char *name_owner;
381 result = g_dbus_connection_call_finish (client->connection,
386 g_variant_get (result, "(&s)", &name_owner);
389 if (name_owner != NULL)
391 g_warn_if_fail (client->name_owner == NULL);
392 client->name_owner = g_strdup (name_owner);
393 call_appeared_handler (client);
397 call_vanished_handler (client);
400 client->initialized = TRUE;
403 g_variant_unref (result);
404 client_unref (client);
407 /* ---------------------------------------------------------------------------------------------------- */
410 invoke_get_name_owner (Client *client)
412 g_dbus_connection_call (client->connection,
413 "org.freedesktop.DBus", /* bus name */
414 "/org/freedesktop/DBus", /* object path */
415 "org.freedesktop.DBus", /* interface name */
416 "GetNameOwner", /* method name */
417 g_variant_new ("(s)", client->name),
418 G_VARIANT_TYPE ("(s)"),
419 G_DBUS_CALL_FLAGS_NONE,
422 (GAsyncReadyCallback) get_name_owner_cb,
423 client_ref (client));
426 /* ---------------------------------------------------------------------------------------------------- */
429 start_service_by_name_cb (GObject *source_object,
433 Client *client = user_data;
438 result = g_dbus_connection_call_finish (client->connection,
443 guint32 start_service_result;
444 g_variant_get (result, "(u)", &start_service_result);
446 if (start_service_result == 1) /* DBUS_START_REPLY_SUCCESS */
448 invoke_get_name_owner (client);
450 else if (start_service_result == 2) /* DBUS_START_REPLY_ALREADY_RUNNING */
452 invoke_get_name_owner (client);
456 g_warning ("Unexpected reply %d from StartServiceByName() method", start_service_result);
457 call_vanished_handler (client);
458 client->initialized = TRUE;
463 /* Errors are not unexpected; the bus will reply e.g.
465 * org.freedesktop.DBus.Error.ServiceUnknown: The name org.gnome.Epiphany2
466 * was not provided by any .service files
468 * This doesn't mean that the name doesn't have an owner, just
469 * that it's not provided by a .service file. So proceed to
470 * invoke GetNameOwner().
472 invoke_get_name_owner (client);
476 g_variant_unref (result);
477 client_unref (client);
480 /* ---------------------------------------------------------------------------------------------------- */
483 has_connection (Client *client)
485 /* listen for disconnection */
486 client->disconnected_signal_handler_id = g_signal_connect (client->connection,
488 G_CALLBACK (on_connection_disconnected),
489 GUINT_TO_POINTER (client->id));
491 /* start listening to NameOwnerChanged messages immediately */
492 client->name_owner_changed_subscription_id = g_dbus_connection_signal_subscribe (client->connection,
493 "org.freedesktop.DBus", /* name */
494 "org.freedesktop.DBus", /* if */
495 "NameOwnerChanged", /* signal */
496 "/org/freedesktop/DBus", /* path */
498 G_DBUS_SIGNAL_FLAGS_NONE,
499 on_name_owner_changed,
500 GUINT_TO_POINTER (client->id),
503 if (client->flags & G_BUS_NAME_WATCHER_FLAGS_AUTO_START)
505 g_dbus_connection_call (client->connection,
506 "org.freedesktop.DBus", /* bus name */
507 "/org/freedesktop/DBus", /* object path */
508 "org.freedesktop.DBus", /* interface name */
509 "StartServiceByName", /* method name */
510 g_variant_new ("(su)", client->name, 0),
511 G_VARIANT_TYPE ("(u)"),
512 G_DBUS_CALL_FLAGS_NONE,
515 (GAsyncReadyCallback) start_service_by_name_cb,
516 client_ref (client));
521 invoke_get_name_owner (client);
527 connection_get_cb (GObject *source_object,
531 Client *client = user_data;
533 client->connection = g_bus_get_finish (res, NULL);
534 if (client->connection == NULL)
536 call_vanished_handler (client);
540 has_connection (client);
543 client_unref (client);
546 /* ---------------------------------------------------------------------------------------------------- */
550 * @bus_type: The type of bus to watch a name on.
551 * @name: The name (well-known or unique) to watch.
552 * @flags: Flags from the #GBusNameWatcherFlags enumeration.
553 * @name_appeared_handler: (nullable): Handler to invoke when @name is known to exist or %NULL.
554 * @name_vanished_handler: (nullable): Handler to invoke when @name is known to not exist or %NULL.
555 * @user_data: User data to pass to handlers.
556 * @user_data_free_func: (nullable): Function for freeing @user_data or %NULL.
558 * Starts watching @name on the bus specified by @bus_type and calls
559 * @name_appeared_handler and @name_vanished_handler when the name is
560 * known to have an owner respectively known to lose its
561 * owner. Callbacks will be invoked in the
562 * [thread-default main context][g-main-context-push-thread-default]
563 * of the thread you are calling this function from.
565 * You are guaranteed that one of the handlers will be invoked after
566 * calling this function. When you are done watching the name, just
567 * call g_bus_unwatch_name() with the watcher id this function
570 * If the name vanishes or appears (for example the application owning
571 * the name could restart), the handlers are also invoked. If the
572 * #GDBusConnection that is used for watching the name disconnects, then
573 * @name_vanished_handler is invoked since it is no longer
574 * possible to access the name.
576 * Another guarantee is that invocations of @name_appeared_handler
577 * and @name_vanished_handler are guaranteed to alternate; that
578 * is, if @name_appeared_handler is invoked then you are
579 * guaranteed that the next time one of the handlers is invoked, it
580 * will be @name_vanished_handler. The reverse is also true.
582 * This behavior makes it very simple to write applications that want
583 * to take action when a certain [name exists][gdbus-watching-names].
584 * Basically, the application should create object proxies in
585 * @name_appeared_handler and destroy them again (if any) in
586 * @name_vanished_handler.
588 * Returns: An identifier (never 0) that can be used with
589 * g_bus_unwatch_name() to stop watching the name.
594 g_bus_watch_name (GBusType bus_type,
596 GBusNameWatcherFlags flags,
597 GBusNameAppearedCallback name_appeared_handler,
598 GBusNameVanishedCallback name_vanished_handler,
600 GDestroyNotify user_data_free_func)
604 g_return_val_if_fail (g_dbus_is_name (name), 0);
608 client = g_new0 (Client, 1);
609 client->ref_count = 1;
610 client->id = (guint) g_atomic_int_add (&next_global_id, 1); /* TODO: uh oh, handle overflow */
611 client->name = g_strdup (name);
612 client->flags = flags;
613 client->name_appeared_handler = name_appeared_handler;
614 client->name_vanished_handler = name_vanished_handler;
615 client->user_data = user_data;
616 client->user_data_free_func = user_data_free_func;
617 client->main_context = g_main_context_ref_thread_default ();
619 if (map_id_to_client == NULL)
621 map_id_to_client = g_hash_table_new (g_direct_hash, g_direct_equal);
623 g_hash_table_insert (map_id_to_client,
624 GUINT_TO_POINTER (client->id),
630 client_ref (client));
638 * g_bus_watch_name_on_connection:
639 * @connection: A #GDBusConnection.
640 * @name: The name (well-known or unique) to watch.
641 * @flags: Flags from the #GBusNameWatcherFlags enumeration.
642 * @name_appeared_handler: (nullable): Handler to invoke when @name is known to exist or %NULL.
643 * @name_vanished_handler: (nullable): Handler to invoke when @name is known to not exist or %NULL.
644 * @user_data: User data to pass to handlers.
645 * @user_data_free_func: (nullable): Function for freeing @user_data or %NULL.
647 * Like g_bus_watch_name() but takes a #GDBusConnection instead of a
650 * Returns: An identifier (never 0) that can be used with
651 * g_bus_unwatch_name() to stop watching the name.
655 guint g_bus_watch_name_on_connection (GDBusConnection *connection,
657 GBusNameWatcherFlags flags,
658 GBusNameAppearedCallback name_appeared_handler,
659 GBusNameVanishedCallback name_vanished_handler,
661 GDestroyNotify user_data_free_func)
665 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
666 g_return_val_if_fail (g_dbus_is_name (name), 0);
670 client = g_new0 (Client, 1);
671 client->ref_count = 1;
672 client->id = (guint) g_atomic_int_add (&next_global_id, 1); /* TODO: uh oh, handle overflow */
673 client->name = g_strdup (name);
674 client->flags = flags;
675 client->name_appeared_handler = name_appeared_handler;
676 client->name_vanished_handler = name_vanished_handler;
677 client->user_data = user_data;
678 client->user_data_free_func = user_data_free_func;
679 client->main_context = g_main_context_ref_thread_default ();
681 if (map_id_to_client == NULL)
682 map_id_to_client = g_hash_table_new (g_direct_hash, g_direct_equal);
684 g_hash_table_insert (map_id_to_client,
685 GUINT_TO_POINTER (client->id),
688 client->connection = g_object_ref (connection);
691 has_connection (client);
697 GClosure *name_appeared_closure;
698 GClosure *name_vanished_closure;
701 static WatchNameData *
702 watch_name_data_new (GClosure *name_appeared_closure,
703 GClosure *name_vanished_closure)
707 data = g_new0 (WatchNameData, 1);
709 if (name_appeared_closure != NULL)
711 data->name_appeared_closure = g_closure_ref (name_appeared_closure);
712 g_closure_sink (name_appeared_closure);
713 if (G_CLOSURE_NEEDS_MARSHAL (name_appeared_closure))
714 g_closure_set_marshal (name_appeared_closure, g_cclosure_marshal_generic);
717 if (name_vanished_closure != NULL)
719 data->name_vanished_closure = g_closure_ref (name_vanished_closure);
720 g_closure_sink (name_vanished_closure);
721 if (G_CLOSURE_NEEDS_MARSHAL (name_vanished_closure))
722 g_closure_set_marshal (name_vanished_closure, g_cclosure_marshal_generic);
729 watch_with_closures_on_name_appeared (GDBusConnection *connection,
731 const gchar *name_owner,
734 WatchNameData *data = user_data;
735 GValue params[3] = { G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT };
737 g_value_init (¶ms[0], G_TYPE_DBUS_CONNECTION);
738 g_value_set_object (¶ms[0], connection);
740 g_value_init (¶ms[1], G_TYPE_STRING);
741 g_value_set_string (¶ms[1], name);
743 g_value_init (¶ms[2], G_TYPE_STRING);
744 g_value_set_string (¶ms[2], name_owner);
746 g_closure_invoke (data->name_appeared_closure, NULL, 3, params, NULL);
748 g_value_unset (params + 0);
749 g_value_unset (params + 1);
750 g_value_unset (params + 2);
754 watch_with_closures_on_name_vanished (GDBusConnection *connection,
758 WatchNameData *data = user_data;
759 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
761 g_value_init (¶ms[0], G_TYPE_DBUS_CONNECTION);
762 g_value_set_object (¶ms[0], connection);
764 g_value_init (¶ms[1], G_TYPE_STRING);
765 g_value_set_string (¶ms[1], name);
767 g_closure_invoke (data->name_vanished_closure, NULL, 2, params, NULL);
769 g_value_unset (params + 0);
770 g_value_unset (params + 1);
774 bus_watch_name_free_func (gpointer user_data)
776 WatchNameData *data = user_data;
778 if (data->name_appeared_closure != NULL)
779 g_closure_unref (data->name_appeared_closure);
781 if (data->name_vanished_closure != NULL)
782 g_closure_unref (data->name_vanished_closure);
788 * g_bus_watch_name_with_closures: (rename-to g_bus_watch_name)
789 * @bus_type: The type of bus to watch a name on.
790 * @name: The name (well-known or unique) to watch.
791 * @flags: Flags from the #GBusNameWatcherFlags enumeration.
792 * @name_appeared_closure: (nullable): #GClosure to invoke when @name is known
794 * @name_vanished_closure: (nullable): #GClosure to invoke when @name is known
795 * to not exist or %NULL.
797 * Version of g_bus_watch_name() using closures instead of callbacks for
798 * easier binding in other languages.
800 * Returns: An identifier (never 0) that can be used with
801 * g_bus_unwatch_name() to stop watching the name.
806 g_bus_watch_name_with_closures (GBusType bus_type,
808 GBusNameWatcherFlags flags,
809 GClosure *name_appeared_closure,
810 GClosure *name_vanished_closure)
812 return g_bus_watch_name (bus_type,
815 name_appeared_closure != NULL ? watch_with_closures_on_name_appeared : NULL,
816 name_vanished_closure != NULL ? watch_with_closures_on_name_vanished : NULL,
817 watch_name_data_new (name_appeared_closure, name_vanished_closure),
818 bus_watch_name_free_func);
822 * g_bus_watch_name_on_connection_with_closures: (rename-to g_bus_watch_name_on_connection)
823 * @connection: A #GDBusConnection.
824 * @name: The name (well-known or unique) to watch.
825 * @flags: Flags from the #GBusNameWatcherFlags enumeration.
826 * @name_appeared_closure: (nullable): #GClosure to invoke when @name is known
828 * @name_vanished_closure: (nullable): #GClosure to invoke when @name is known
829 * to not exist or %NULL.
831 * Version of g_bus_watch_name_on_connection() using closures instead of callbacks for
832 * easier binding in other languages.
834 * Returns: An identifier (never 0) that can be used with
835 * g_bus_unwatch_name() to stop watching the name.
839 guint g_bus_watch_name_on_connection_with_closures (
840 GDBusConnection *connection,
842 GBusNameWatcherFlags flags,
843 GClosure *name_appeared_closure,
844 GClosure *name_vanished_closure)
846 return g_bus_watch_name_on_connection (connection,
849 name_appeared_closure != NULL ? watch_with_closures_on_name_appeared : NULL,
850 name_vanished_closure != NULL ? watch_with_closures_on_name_vanished : NULL,
851 watch_name_data_new (name_appeared_closure, name_vanished_closure),
852 bus_watch_name_free_func);
856 * g_bus_unwatch_name:
857 * @watcher_id: An identifier obtained from g_bus_watch_name()
859 * Stops watching a name.
861 * Note that there may still be D-Bus traffic to process (relating to watching
862 * and unwatching the name) in the current thread-default #GMainContext after
863 * this function has returned. You should continue to iterate the #GMainContext
864 * until the #GDestroyNotify function passed to g_bus_watch_name() is called, in
865 * order to avoid memory leaks through callbacks queued on the #GMainContext
866 * after it’s stopped being iterated.
871 g_bus_unwatch_name (guint watcher_id)
875 g_return_if_fail (watcher_id > 0);
880 if (watcher_id == 0 ||
881 map_id_to_client == NULL ||
882 (client = g_hash_table_lookup (map_id_to_client, GUINT_TO_POINTER (watcher_id))) == NULL)
884 g_warning ("Invalid id %d passed to g_bus_unwatch_name()", watcher_id);
888 client->cancelled = TRUE;
889 g_warn_if_fail (g_hash_table_remove (map_id_to_client, GUINT_TO_POINTER (watcher_id)));
894 /* do callback without holding lock */
897 client_unref (client);