1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright © 2021 Endless OS Foundation, LLC
5 * SPDX-License-Identifier: LGPL-2.1-or-later
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General
18 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
20 * SPDX-License-Identifier: LGPL-2.1-or-later
26 #include "gdebugcontroller.h"
27 #include "gdebugcontrollerdbus.h"
28 #include "giomodule-priv.h"
30 #include "gio/gdbusprivate.h"
31 #include "gio/gmarshal-internal.h"
34 * SECTION:gdebugcontrollerdbus
35 * @title: GDebugControllerDBus
36 * @short_description: Debugging controller D-Bus implementation
39 * #GDebugControllerDBus is an implementation of #GDebugController which exposes
40 * debug settings as a D-Bus object.
42 * It is a #GInitable object, and will register an object at
43 * `/org/gtk/Debugging` on the bus given as
44 * #GDebugControllerDBus:connection once it’s initialized. The object will be
45 * unregistered when the last reference to the #GDebugControllerDBus is dropped.
47 * This D-Bus object can be used by remote processes to enable or disable debug
48 * output in this process. Remote processes calling
49 * `org.gtk.Debugging.SetDebugEnabled()` will affect the value of
50 * #GDebugController:debug-enabled and, by default, g_log_get_debug_enabled().
53 * By default, no processes are allowed to call `SetDebugEnabled()` unless a
54 * #GDebugControllerDBus::authorize signal handler is installed. This is because
55 * the process may be privileged, or might expose sensitive information in its
56 * debug output. You may want to restrict the ability to enable debug output to
57 * privileged users or processes.
59 * One option is to install a D-Bus security policy which restricts access to
60 * `SetDebugEnabled()`, installing something like the following in
61 * `$datadir/dbus-1/system.d/`:
62 * |[<!-- language="XML" -->
63 * <?xml version="1.0"?> <!--*-nxml-*-->
64 * <!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
65 * "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
67 * <policy user="root">
68 * <allow send_destination="com.example.MyService" send_interface="org.gtk.Debugging"/>
70 * <policy context="default">
71 * <deny send_destination="com.example.MyService" send_interface="org.gtk.Debugging"/>
76 * This will prevent the `SetDebugEnabled()` method from being called by all
77 * except root. It will not prevent the `DebugEnabled` property from being read,
78 * as it’s accessed through the `org.freedesktop.DBus.Properties` interface.
80 * Another option is to use polkit to allow or deny requests on a case-by-case
81 * basis, allowing for the possibility of dynamic authorisation. To do this,
82 * connect to the #GDebugControllerDBus::authorize signal and query polkit in
84 * |[<!-- language="C" -->
85 * g_autoptr(GError) child_error = NULL;
86 * g_autoptr(GDBusConnection) connection = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, NULL);
87 * gulong debug_controller_authorize_id = 0;
89 * // Set up the debug controller.
90 * debug_controller = G_DEBUG_CONTROLLER (g_debug_controller_dbus_new (priv->connection, NULL, &child_error));
91 * if (debug_controller == NULL)
93 * g_error ("Could not register debug controller on bus: %s"),
94 * child_error->message);
97 * debug_controller_authorize_id = g_signal_connect (debug_controller,
99 * G_CALLBACK (debug_controller_authorize_cb),
103 * debug_controller_authorize_cb (GDebugControllerDBus *debug_controller,
104 * GDBusMethodInvocation *invocation,
105 * gpointer user_data)
107 * g_autoptr(PolkitAuthority) authority = NULL;
108 * g_autoptr(PolkitSubject) subject = NULL;
109 * g_autoptr(PolkitAuthorizationResult) auth_result = NULL;
110 * g_autoptr(GError) local_error = NULL;
111 * GDBusMessage *message;
112 * GDBusMessageFlags message_flags;
113 * PolkitCheckAuthorizationFlags flags = POLKIT_CHECK_AUTHORIZATION_FLAGS_NONE;
115 * message = g_dbus_method_invocation_get_message (invocation);
116 * message_flags = g_dbus_message_get_flags (message);
118 * authority = polkit_authority_get_sync (NULL, &local_error);
119 * if (authority == NULL)
121 * g_warning ("Failed to get polkit authority: %s", local_error->message);
125 * if (message_flags & G_DBUS_MESSAGE_FLAGS_ALLOW_INTERACTIVE_AUTHORIZATION)
126 * flags |= POLKIT_CHECK_AUTHORIZATION_FLAGS_ALLOW_USER_INTERACTION;
128 * subject = polkit_system_bus_name_new (g_dbus_method_invocation_get_sender (invocation));
130 * auth_result = polkit_authority_check_authorization_sync (authority,
132 * "com.example.MyService.set-debug-enabled",
137 * if (auth_result == NULL)
139 * g_warning ("Failed to get check polkit authorization: %s", local_error->message);
143 * return polkit_authorization_result_get_is_authorized (auth_result);
150 static const gchar org_gtk_Debugging_xml[] =
152 "<interface name='org.gtk.Debugging'>"
153 "<property name='DebugEnabled' type='b' access='read'/>"
154 "<method name='SetDebugEnabled'>"
155 "<arg type='b' name='debug-enabled' direction='in'/>"
160 static GDBusInterfaceInfo *org_gtk_Debugging;
162 #define G_DEBUG_CONTROLLER_DBUS_GET_INITABLE_IFACE(o) (G_TYPE_INSTANCE_GET_INTERFACE ((o), G_TYPE_INITABLE, GInitable))
164 static void g_debug_controller_dbus_iface_init (GDebugControllerInterface *iface);
165 static void g_debug_controller_dbus_initable_iface_init (GInitableIface *iface);
166 static gboolean g_debug_controller_dbus_authorize_default (GDebugControllerDBus *self,
167 GDBusMethodInvocation *invocation);
174 } GDebugControllerDBusProperty;
176 static GParamSpec *props[PROP_CONNECTION + 1] = { NULL, };
181 } GDebugControllerDBusSignal;
183 static guint signals[SIGNAL_AUTHORIZE + 1] = {0};
187 GObject parent_instance;
189 GCancellable *cancellable; /* (owned) */
190 GDBusConnection *connection; /* (owned) */
192 GPtrArray *pending_authorize_tasks; /* (element-type GWeakRef) (owned) (nullable) */
194 gboolean debug_enabled;
195 } GDebugControllerDBusPrivate;
197 G_DEFINE_TYPE_WITH_CODE (GDebugControllerDBus, g_debug_controller_dbus, G_TYPE_OBJECT,
198 G_ADD_PRIVATE (GDebugControllerDBus)
199 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
200 g_debug_controller_dbus_initable_iface_init)
201 G_IMPLEMENT_INTERFACE (G_TYPE_DEBUG_CONTROLLER,
202 g_debug_controller_dbus_iface_init)
203 _g_io_modules_ensure_extension_points_registered ();
204 g_io_extension_point_implement (G_DEBUG_CONTROLLER_EXTENSION_POINT_NAME,
210 g_debug_controller_dbus_init (GDebugControllerDBus *self)
212 GDebugControllerDBusPrivate *priv = g_debug_controller_dbus_get_instance_private (self);
214 priv->cancellable = g_cancellable_new ();
218 set_debug_enabled (GDebugControllerDBus *self,
219 gboolean debug_enabled)
221 GDebugControllerDBusPrivate *priv = g_debug_controller_dbus_get_instance_private (self);
223 if (g_cancellable_is_cancelled (priv->cancellable))
226 if (debug_enabled != priv->debug_enabled)
228 GVariantBuilder builder;
230 priv->debug_enabled = debug_enabled;
232 /* Change the default log writer’s behaviour in GLib. */
233 g_log_set_debug_enabled (debug_enabled);
235 /* Notify internally and externally of the property change. */
236 g_object_notify (G_OBJECT (self), "debug-enabled");
238 g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}"));
239 g_variant_builder_add (&builder, "{sv}", "DebugEnabled", g_variant_new_boolean (priv->debug_enabled));
241 g_dbus_connection_emit_signal (priv->connection,
243 "/org/gtk/Debugging",
244 "org.freedesktop.DBus.Properties",
246 g_variant_new ("(sa{sv}as)",
252 g_debug ("Debug output %s", debug_enabled ? "enabled" : "disabled");
256 /* Called in the #GMainContext which was default when the #GDebugControllerDBus
257 * was initialised. */
259 dbus_get_property (GDBusConnection *connection,
261 const gchar *object_path,
262 const gchar *interface_name,
263 const gchar *property_name,
267 GDebugControllerDBus *self = user_data;
268 GDebugControllerDBusPrivate *priv = g_debug_controller_dbus_get_instance_private (self);
270 if (g_str_equal (property_name, "DebugEnabled"))
271 return g_variant_new_boolean (priv->debug_enabled);
273 g_assert_not_reached ();
279 weak_ref_new (GObject *obj)
281 GWeakRef *weak_ref = g_new0 (GWeakRef, 1);
283 g_weak_ref_init (weak_ref, obj);
285 return g_steal_pointer (&weak_ref);
289 weak_ref_free (GWeakRef *weak_ref)
291 g_weak_ref_clear (weak_ref);
295 /* Called in the #GMainContext which was default when the #GDebugControllerDBus
296 * was initialised. */
298 garbage_collect_weak_refs (GDebugControllerDBus *self)
300 GDebugControllerDBusPrivate *priv = g_debug_controller_dbus_get_instance_private (self);
303 if (priv->pending_authorize_tasks == NULL)
306 /* Iterate in reverse order so that if we remove an element the hole won’t be
307 * filled by an element we haven’t checked yet. */
308 for (i = priv->pending_authorize_tasks->len; i > 0; i--)
310 GWeakRef *weak_ref = g_ptr_array_index (priv->pending_authorize_tasks, i - 1);
311 GObject *obj = g_weak_ref_get (weak_ref);
314 g_ptr_array_remove_index_fast (priv->pending_authorize_tasks, i - 1);
316 g_object_unref (obj);
319 /* Don’t need to keep the array around any more if it’s empty. */
320 if (priv->pending_authorize_tasks->len == 0)
321 g_clear_pointer (&priv->pending_authorize_tasks, g_ptr_array_unref);
324 /* Called in a worker thread. */
326 authorize_task_cb (GTask *task,
327 gpointer source_object,
329 GCancellable *cancellable)
331 GDebugControllerDBus *self = G_DEBUG_CONTROLLER_DBUS (source_object);
332 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (task_data);
333 gboolean authorized = TRUE;
335 g_signal_emit (self, signals[SIGNAL_AUTHORIZE], 0, invocation, &authorized);
337 g_task_return_boolean (task, authorized);
340 /* Called in the #GMainContext which was default when the #GDebugControllerDBus
341 * was initialised. */
343 authorize_cb (GObject *object,
344 GAsyncResult *result,
347 GDebugControllerDBus *self = G_DEBUG_CONTROLLER_DBUS (object);
348 GDebugControllerDBusPrivate *priv G_GNUC_UNUSED /* when compiling with G_DISABLE_ASSERT */;
349 GTask *task = G_TASK (result);
350 GDBusMethodInvocation *invocation = g_task_get_task_data (task);
351 GVariant *parameters = g_dbus_method_invocation_get_parameters (invocation);
352 gboolean enabled = FALSE;
355 priv = g_debug_controller_dbus_get_instance_private (self);
356 authorized = g_task_propagate_boolean (task, NULL);
360 GError *local_error = g_error_new (G_DBUS_ERROR, G_DBUS_ERROR_ACCESS_DENIED,
361 _("Not authorized to change debug settings"));
362 g_dbus_method_invocation_take_error (invocation, g_steal_pointer (&local_error));
366 /* Update the property value. */
367 g_variant_get (parameters, "(b)", &enabled);
368 set_debug_enabled (self, enabled);
370 g_dbus_method_invocation_return_value (invocation, NULL);
373 /* The GTask will stay alive for a bit longer as the worker thread is
374 * potentially still in the process of dropping its reference to it. */
375 g_assert (priv->pending_authorize_tasks != NULL && priv->pending_authorize_tasks->len > 0);
378 /* Called in the #GMainContext which was default when the #GDebugControllerDBus
379 * was initialised. */
381 dbus_method_call (GDBusConnection *connection,
383 const gchar *object_path,
384 const gchar *interface_name,
385 const gchar *method_name,
386 GVariant *parameters,
387 GDBusMethodInvocation *invocation,
390 GDebugControllerDBus *self = user_data;
391 GDebugControllerDBusPrivate *priv = g_debug_controller_dbus_get_instance_private (self);
392 GDebugControllerDBusClass *klass = G_DEBUG_CONTROLLER_DBUS_GET_CLASS (self);
394 /* Only on the org.gtk.Debugging interface */
395 if (g_str_equal (method_name, "SetDebugEnabled"))
399 task = g_task_new (self, priv->cancellable, authorize_cb, NULL);
400 g_task_set_source_tag (task, dbus_method_call);
401 g_task_set_task_data (task, g_object_ref (invocation), (GDestroyNotify) g_object_unref);
403 /* Track the pending #GTask with a weak ref as its final strong ref could
404 * be dropped from this thread or an arbitrary #GTask worker thread. The
405 * weak refs will be evaluated in g_debug_controller_dbus_stop(). */
406 if (priv->pending_authorize_tasks == NULL)
407 priv->pending_authorize_tasks = g_ptr_array_new_with_free_func ((GDestroyNotify) weak_ref_free);
408 g_ptr_array_add (priv->pending_authorize_tasks, weak_ref_new (G_OBJECT (task)));
410 /* Take the opportunity to clean up a bit. */
411 garbage_collect_weak_refs (self);
413 /* Check the calling peer is authorised to change the debug mode. So that
414 * the signal handler can block on checking polkit authorisation (which
415 * definitely involves D-Bus calls, and might involve user interaction),
416 * emit the #GDebugControllerDBus::authorize signal in a worker thread, so
417 * that handlers can synchronously block it. This is similar to how
418 * #GDBusInterfaceSkeleton::g-authorize-method works.
420 * If no signal handlers are connected, don’t bother running the worker
421 * thread, and just return a default value of %FALSE. Fail closed. */
422 if (g_signal_has_handler_pending (self, signals[SIGNAL_AUTHORIZE], 0, FALSE) ||
423 klass->authorize != g_debug_controller_dbus_authorize_default)
424 g_task_run_in_thread (task, authorize_task_cb);
426 g_task_return_boolean (task, FALSE);
428 g_clear_object (&task);
431 g_assert_not_reached ();
435 g_debug_controller_dbus_initable_init (GInitable *initable,
436 GCancellable *cancellable,
439 GDebugControllerDBus *self = G_DEBUG_CONTROLLER_DBUS (initable);
440 GDebugControllerDBusPrivate *priv = g_debug_controller_dbus_get_instance_private (self);
441 static const GDBusInterfaceVTable vtable = {
444 NULL /* set_property */,
448 if (org_gtk_Debugging == NULL)
450 GError *local_error = NULL;
453 info = g_dbus_node_info_new_for_xml (org_gtk_Debugging_xml, &local_error);
454 if G_UNLIKELY (info == NULL)
455 g_error ("%s", local_error->message);
456 org_gtk_Debugging = g_dbus_node_info_lookup_interface (info, "org.gtk.Debugging");
457 g_assert (org_gtk_Debugging != NULL);
458 g_dbus_interface_info_ref (org_gtk_Debugging);
459 g_dbus_node_info_unref (info);
462 priv->object_id = g_dbus_connection_register_object (priv->connection,
463 "/org/gtk/Debugging",
465 &vtable, self, NULL, error);
466 if (priv->object_id == 0)
473 g_debug_controller_dbus_get_property (GObject *object,
478 GDebugControllerDBus *self = G_DEBUG_CONTROLLER_DBUS (object);
479 GDebugControllerDBusPrivate *priv = g_debug_controller_dbus_get_instance_private (self);
481 switch ((GDebugControllerDBusProperty) prop_id)
483 case PROP_CONNECTION:
484 g_value_set_object (value, priv->connection);
486 case PROP_DEBUG_ENABLED:
487 g_value_set_boolean (value, priv->debug_enabled);
490 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
496 g_debug_controller_dbus_set_property (GObject *object,
501 GDebugControllerDBus *self = G_DEBUG_CONTROLLER_DBUS (object);
502 GDebugControllerDBusPrivate *priv = g_debug_controller_dbus_get_instance_private (self);
504 switch ((GDebugControllerDBusProperty) prop_id)
506 case PROP_CONNECTION:
508 g_assert (priv->connection == NULL);
509 priv->connection = g_value_dup_object (value);
511 case PROP_DEBUG_ENABLED:
512 set_debug_enabled (self, g_value_get_boolean (value));
515 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
521 g_debug_controller_dbus_dispose (GObject *object)
523 GDebugControllerDBus *self = G_DEBUG_CONTROLLER_DBUS (object);
524 GDebugControllerDBusPrivate *priv = g_debug_controller_dbus_get_instance_private (self);
526 g_debug_controller_dbus_stop (self);
527 g_assert (priv->pending_authorize_tasks == NULL);
528 g_clear_object (&priv->connection);
529 g_clear_object (&priv->cancellable);
531 G_OBJECT_CLASS (g_debug_controller_dbus_parent_class)->dispose (object);
535 g_debug_controller_dbus_authorize_default (GDebugControllerDBus *self,
536 GDBusMethodInvocation *invocation)
542 g_debug_controller_dbus_class_init (GDebugControllerDBusClass *klass)
544 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
546 gobject_class->get_property = g_debug_controller_dbus_get_property;
547 gobject_class->set_property = g_debug_controller_dbus_set_property;
548 gobject_class->dispose = g_debug_controller_dbus_dispose;
550 klass->authorize = g_debug_controller_dbus_authorize_default;
553 * GDebugControllerDBus:connection:
555 * The D-Bus connection to expose the debugging interface on.
557 * Typically this will be the same connection (to the system or session bus)
558 * which the rest of the application or service’s D-Bus objects are registered
563 props[PROP_CONNECTION] =
564 g_param_spec_object ("connection", "D-Bus Connection",
565 "The D-Bus connection to expose the debugging interface on.",
566 G_TYPE_DBUS_CONNECTION,
568 G_PARAM_CONSTRUCT_ONLY |
569 G_PARAM_STATIC_STRINGS);
571 g_object_class_install_properties (gobject_class, G_N_ELEMENTS (props), props);
573 g_object_class_override_property (gobject_class, PROP_DEBUG_ENABLED, "debug-enabled");
576 * GDebugControllerDBus::authorize:
577 * @controller: The #GDebugControllerDBus emitting the signal.
578 * @invocation: A #GDBusMethodInvocation.
580 * Emitted when a D-Bus peer is trying to change the debug settings and used
581 * to determine if that is authorized.
583 * This signal is emitted in a dedicated worker thread, so handlers are
584 * allowed to perform blocking I/O. This means that, for example, it is
585 * appropriate to call `polkit_authority_check_authorization_sync()` to check
586 * authorization using polkit.
588 * If %FALSE is returned then no further handlers are run and the request to
589 * change the debug settings is rejected.
591 * Otherwise, if %TRUE is returned, signal emission continues. If no handlers
592 * return %FALSE, then the debug settings are allowed to be changed.
594 * Signal handlers must not modify @invocation, or cause it to return a value.
596 * The default class handler just returns %TRUE.
598 * Returns: %TRUE if the call is authorized, %FALSE otherwise.
602 signals[SIGNAL_AUTHORIZE] =
603 g_signal_new ("authorize",
604 G_TYPE_DEBUG_CONTROLLER_DBUS,
606 G_STRUCT_OFFSET (GDebugControllerDBusClass, authorize),
607 _g_signal_accumulator_false_handled,
609 _g_cclosure_marshal_BOOLEAN__OBJECT,
612 G_TYPE_DBUS_METHOD_INVOCATION);
613 g_signal_set_va_marshaller (signals[SIGNAL_AUTHORIZE],
614 G_TYPE_FROM_CLASS (klass),
615 _g_cclosure_marshal_BOOLEAN__OBJECTv);
619 g_debug_controller_dbus_iface_init (GDebugControllerInterface *iface)
624 g_debug_controller_dbus_initable_iface_init (GInitableIface *iface)
626 iface->init = g_debug_controller_dbus_initable_init;
630 * g_debug_controller_dbus_new:
631 * @connection: a #GDBusConnection to register the debug object on
632 * @cancellable: (nullable): a #GCancellable, or %NULL
633 * @error: return location for a #GError, or %NULL
635 * Create a new #GDebugControllerDBus and synchronously initialize it.
637 * Initializing the object will export the debug object on @connection. The
638 * object will remain registered until the last reference to the
639 * #GDebugControllerDBus is dropped.
641 * Initialization may fail if registering the object on @connection fails.
643 * Returns: (nullable) (transfer full): a new #GDebugControllerDBus, or %NULL
647 GDebugControllerDBus *
648 g_debug_controller_dbus_new (GDBusConnection *connection,
649 GCancellable *cancellable,
652 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
653 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL);
654 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
656 return g_initable_new (G_TYPE_DEBUG_CONTROLLER_DBUS,
659 "connection", connection,
664 * g_debug_controller_dbus_stop:
665 * @self: a #GDebugControllerDBus
667 * Stop the debug controller, unregistering its object from the bus.
669 * Any pending method calls to the object will complete successfully, but new
670 * ones will return an error. This method will block until all pending
671 * #GDebugControllerDBus::authorize signals have been handled. This is expected
672 * to not take long, as it will just be waiting for threads to join. If any
673 * #GDebugControllerDBus::authorize signal handlers are still executing in other
674 * threads, this will block until after they have returned.
676 * This method will be called automatically when the final reference to the
677 * #GDebugControllerDBus is dropped. You may want to call it explicitly to know
678 * when the controller has been fully removed from the bus, or to break
679 * reference count cycles.
681 * Calling this method from within a #GDebugControllerDBus::authorize signal
682 * handler will cause a deadlock and must not be done.
687 g_debug_controller_dbus_stop (GDebugControllerDBus *self)
689 GDebugControllerDBusPrivate *priv = g_debug_controller_dbus_get_instance_private (self);
691 g_cancellable_cancel (priv->cancellable);
693 if (priv->object_id != 0)
695 g_dbus_connection_unregister_object (priv->connection, priv->object_id);
699 /* Wait for any pending authorize tasks to finish. These will just be waiting
700 * for threads to join at this point, as the D-Bus object has been
701 * unregistered and the cancellable cancelled.
703 * The loop will never terminate if g_debug_controller_dbus_stop() is
704 * called from within an ::authorize callback.
706 * See discussion in https://gitlab.gnome.org/GNOME/glib/-/merge_requests/2486 */
707 while (priv->pending_authorize_tasks != NULL)
709 garbage_collect_weak_refs (self);