如何在使用 gdbus-codegen 框架时验证 D-Bus 属性

How to validate a D-Bus property when using gdbus-codegen skeleton

本文关键字:验证 D-Bus 属性 框架 gdbus-codegen      更新时间:2023-10-16

我正在使用gdbusgdbus-codegen在D-Bus上创建一个服务。

内省是这样的:

<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"
                      "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
<node>
  <interface name="com.example.foo">
    <property name="Bar" type="s" access="readwrite" />
  </interface>
</node>

我正在执行这样的gdbus-codegen

gdbus-codegen --interface-prefix com.example --generate-c-code=foo foo.xml

而我的主要.cpp看起来像这样:

#include <iostream>
#include "foo.h"
void OnBarChanged(GObject * gobject, GParamSpec * pspec, gpointer user_data)
{
  std::cout << "Bar: " << foo_get_bar((Foo *)gobject) << std::endl;
}
void OnBusNameAquired(GDBusConnection * connection,
                      const gchar *     name,
                      gpointer          user_data)
{
  Foo * foo = foo_skeleton_new();
  g_signal_connect(foo, "notify::bar", G_CALLBACK(&OnBarChanged), NULL);
  g_dbus_interface_skeleton_export(G_DBUS_INTERFACE_SKELETON(foo),
                                   connection,
                                   "/com/example/foo",
                                   NULL);
}
int main()
{
  std::cout << "Testing DBus properties" << std::endl;
  GMainLoop * loop;
  loop = g_main_loop_new(NULL, FALSE);
  g_bus_own_name(G_BUS_TYPE_SESSION,
                 "com.example.foo",
                 G_BUS_NAME_OWNER_FLAGS_NONE,
                 NULL,
                 OnBusNameAquired,
                 NULL,
                 NULL,
                 NULL);
  g_main_loop_run(loop);
  return 0;
}

这按预期工作,我能够使用以下方法设置和获取属性:

gdbus call --session --dest com.example.foo --object-path /com/example/foo --method org.freedesktop.DBus.Properties.Set "com.example.foo" "Bar" "<'baz'>"

gdbus call --session --dest com.example.foo --object-path /com/example/foo --method org.freedesktop.DBus.Properties.Get "com.example.foo" "Bar"
(<'baz'>,)

问题:

我想同步验证属性的设置,并在失败时返回错误。如何使用gdbus-codegen生成的代码完成此操作?

附注:

代码泄漏,通常未做好生产准备。我现在很好:-)

编辑

经过继续研究,D-Bus 属性似乎正在使用基础GObject属性功能。当所有这些都由gdbus-codegen代码设置时,是否可以安装自定义验证器?

连接到来自foo骨架的GDBusInterfaceSkeleton::g-authorize-method信号。导出的对象处理的每个 D-Bus 方法调用都将调用您的回调 — 您可以匹配org.freedesktop.DBus.Properties.Set调用并执行验证。

在flatpak中有一个这样的示例(对于任意方法调用,而不是D-Bus属性设置;但原理是相同的):https://github.com/flatpak/flatpak/blob/c915f73b41688a7dc2ec7f0ab2fbcf1a7c738841/system-helper/flatpak-system-helper.c#L1192