Migrate bluetooth-policy to DynamicTable 64/239164/2
authorSangwan Kwon <sangwan.kwon@samsung.com>
Wed, 22 Jul 2020 08:11:40 +0000 (17:11 +0900)
committerSangwan Kwon <sangwan.kwon@samsung.com>
Wed, 22 Jul 2020 08:16:10 +0000 (17:16 +0900)
Change-Id: I7646bd813c310523fed86d17eea286594b159dbb
Signed-off-by: Sangwan Kwon <sangwan.kwon@samsung.com>
15 files changed:
packaging/vist.spec
src/vist/table/CMakeLists.txt
src/vist/table/dynamic-table.hpp
src/vist/table/policy/bluetooth/CMakeLists.txt [new file with mode: 0644]
src/vist/table/policy/bluetooth/policy.cpp [new file with mode: 0644]
src/vist/table/policy/bluetooth/policy.hpp [new file with mode: 0644]
src/vist/table/policy/bluetooth/table.cpp [new file with mode: 0644]
src/vist/table/policy/bluetooth/table.hpp [new file with mode: 0644]
src/vist/table/policy/bluetooth/tests/bluetooth.cpp [new file with mode: 0644]
src/vist/table/policy/sample/CMakeLists.txt
src/vist/table/policy/sample/policy.hpp [new file with mode: 0644]
src/vist/table/policy/sample/sample.cpp [deleted file]
src/vist/table/policy/sample/sample.hpp [deleted file]
src/vist/table/policy/sample/table.cpp [new file with mode: 0644]
src/vist/table/policy/sample/table.hpp [new file with mode: 0644]

index e28e68463ad560358d154de7eba8f847d9164c40..b6329c552069ddfaab0f841076400c24bc08b788 100644 (file)
@@ -77,6 +77,7 @@ make %{?jobs:-j%jobs}
 %install
 %make_install
 mkdir -p %{buildroot}/%{vist_db_dir}
+mkdir -p %{buildroot}/%{vist_table_dir}
 mkdir -p %{buildroot}/%{vist_plugin_dir}
 mkdir -p %{buildroot}/%{vist_script_dir}
 
@@ -110,7 +111,7 @@ fi
 %{_unitdir}/sockets.target.wants/vist.socket
 %{vist_script_dir}/*.sql
 %dir %attr(-, %{user_name}, %{group_name}) %{vist_db_dir}
-%dir %attr(-, %{user_name}, %{group_name}) %{vist_plugin_dir}
+%dir %attr(-, %{user_name}, %{group_name}) %{vist_table_dir}
 %dir %attr(-, %{user_name}, %{group_name}) %{vist_script_dir}
 
 ## Test Package ##############################################################
@@ -120,14 +121,16 @@ Group: Security/Testing
 BuildRequires: gtest-devel
 Requires: gtest
 
-%description test 
+%description test
 Provides internal testcases for ViST implementation.
 
 %files test
 %manifest packaging/%{name}-test.manifest
 %{_bindir}/osquery-test
 %attr(4755 %{user_name}, %{group_name}) %{_bindir}/vist-test
-%dir %attr(-, %{user_name}, %{group_name}) %{vist_plugin_dir}/sample
+%dir %attr(-, %{user_name}, %{group_name}) %{vist_table_dir}
+%attr(-, %{user_name}, %{group_name}) %{vist_table_dir}/libvist-table-sample.so
+%attr(-, %{user_name}, %{group_name}) %{vist_plugin_dir}/libtest-plugin.so
 
 ## ViST Plugins #############################################################
 %package plugins
@@ -147,12 +150,10 @@ Requires: klay
 Provides plugins for controlling policies.
 
 %pre plugins
-rm -f %{vist_plugin_dir}/bluetooth
-rm -f %{vist_plugin_dir}/wifi
+#rm -f %{vist_plugin_dir}/bluetooth
+#rm -f %{vist_plugin_dir}/wifi
 
 %files plugins
 %manifest packaging/%{name}-plugins.manifest
-%{vist_plugin_dir}/bluetooth
-%{vist_plugin_dir}/wifi
-%{_bindir}/vist-plugin-bluetooth-test
-%{_bindir}/vist-plugin-wifi-test
+%attr(-, %{user_name}, %{group_name}) %{vist_table_dir}/libvist-bluetooth-policy.so
+%attr(4755 %{user_name}, %{group_name}) %{_bindir}/vist-bluetooth-policy-test
index f05ce017251a04983a224c8143e1f49b4bd226c3..aefd1ef729c853c82b3fda6ed397d8f1a33aa056 100644 (file)
@@ -18,3 +18,7 @@ ADD_VIST_LIBRARY(vist_table policy/policy-admin.cpp
 
 ## dynamic virtual table
 ADD_SUBDIRECTORY(policy/sample)
+
+IF(DEFINED GBS_BUILD)
+       ADD_SUBDIRECTORY(policy/bluetooth)
+ENDIF(DEFINED GBS_BUILD)
index b04de070780f350b20dc9f9f8393ab8c47619d32..7b8278185f1b79f8d9c189b9d006860f332650d1 100644 (file)
  *  limitations under the License
  */
 
+#include <memory>
+
+#include <osquery/registry.h>
+#include <osquery/sql/dynamic_table_row.h>
 #include <osquery/tables.h>
 
+using namespace osquery;
+
 namespace vist {
 namespace table {
 
-class DynamicTable : public osquery::TablePlugin {
+class DynamicTable : public TablePlugin {
 public:
        using FactoryType = DynamicTable* (*)();
 
        virtual void init() = 0;
+
+       template <typename T>
+       static void Register(const std::string& name, std::shared_ptr<T>&& table)
+       {
+               // Register virtual table to sqlite3
+               auto tables = RegistryFactory::get().registry("table");
+               tables->add(name, std::move(table));
+       }
 };
 
 } // namespace table
diff --git a/src/vist/table/policy/bluetooth/CMakeLists.txt b/src/vist/table/policy/bluetooth/CMakeLists.txt
new file mode 100644 (file)
index 0000000..6f63912
--- /dev/null
@@ -0,0 +1,51 @@
+# Copyright (c) 2019-present Samsung Electronics Co., Ltd All Rights Reserved
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+SET(TARGET "vist-bluetooth-policy")
+SET(TARGET_TEST ${TARGET}-test)
+
+SET(DEPENDENCY bluetooth-api
+                          capi-network-bluetooth)
+
+PKG_CHECK_MODULES(PLUGIN_DEPS REQUIRED ${DEPENDENCY})
+
+INCLUDE_DIRECTORIES(SYSTEM ${PLUGIN_DEPS_INCLUDE_DIRS})
+
+## LIB ###########################################
+ADD_LIBRARY(${TARGET} SHARED policy.cpp table.cpp)
+TARGET_LINK_LIBRARIES(${TARGET} ${PLUGIN_DEPS_LIBRARIES}
+                                                               ${TARGET_VIST_COMMON_LIB}
+                                                               ${TARGET_VIST_POLICY_LIB})
+
+INSTALL(TARGETS ${TARGET} DESTINATION ${TABLE_INSTALL_DIR})
+
+## TEST #############################################
+ADD_EXECUTABLE(${TARGET_TEST} ../../../main/tests.cpp
+                                                         policy.cpp
+                                                         table.cpp
+                                                         tests/bluetooth.cpp)
+TARGET_LINK_LIBRARIES(${TARGET_TEST} ${PLUGIN_DEPS_LIBRARIES}
+                                                                        ${TARGET_VIST_CLIENT_LIB}
+                                                                        ${TARGET_VIST_LIB}
+                                                                        gtest
+                                                                        pthread)
+INSTALL(TARGETS ${TARGET_TEST}
+               DESTINATION ${CMAKE_INSTALL_BINDIR}
+               PERMISSIONS OWNER_READ
+                                       OWNER_WRITE
+                                       OWNER_EXECUTE
+                                       GROUP_READ
+                                       GROUP_EXECUTE
+                                       WORLD_READ
+                                       WORLD_EXECUTE)
diff --git a/src/vist/table/policy/bluetooth/policy.cpp b/src/vist/table/policy/bluetooth/policy.cpp
new file mode 100644 (file)
index 0000000..49ba0b4
--- /dev/null
@@ -0,0 +1,96 @@
+/*
+ *  Copyright (c) 2019-present Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+
+#include "policy.hpp"
+
+#include <vist/logger.hpp>
+#include <vist/exception.hpp>
+
+#include <bluetooth.h>
+#include <bluetooth-api.h>
+#include <bluetooth_internal.h>
+
+namespace vist {
+namespace policy {
+
+namespace {
+
+bool failed(int value)
+{
+       return value == BLUETOOTH_DPM_RESULT_ACCESS_DENIED || value == BLUETOOTH_DPM_RESULT_FAIL;
+}
+
+auto allowed(int value)
+{
+       return value ? BLUETOOTH_DPM_ALLOWED : BLUETOOTH_DPM_RESTRICTED;
+}
+
+auto bt_allowed(int value)
+{
+       return value ? BLUETOOTH_DPM_BT_ALLOWED : BLUETOOTH_DPM_BT_RESTRICTED;
+}
+
+} // anonymous namespace
+
+void BluetoothState::onChanged(const PolicyValue& value)
+{
+       auto enable = bt_allowed(value);
+       auto ret = ::bluetooth_dpm_set_allow_mode(enable);
+       if (failed(ret))
+               THROW(ErrCode::RuntimeError) << "Failed to change bluetooth state: " << ret;
+
+       INFO(VIST_PLUGIN) << "Bluetooth state is changed to " << enable;
+}
+
+void DesktopConnectivity::onChanged(const PolicyValue& value)
+{
+       auto enable = allowed(value);
+       auto ret = ::bluetooth_dpm_set_desktop_connectivity_state(enable);
+       if (failed(ret))
+               THROW(ErrCode::RuntimeError) << "Failed to change bt_desktop_connectivity: " << ret;
+
+       INFO(VIST_PLUGIN) << "Bluetooth desktop connectivity state is changed to " << enable;
+}
+
+void Pairing::onChanged(const PolicyValue& value)
+{
+       auto enable = allowed(value);
+       auto ret = ::bluetooth_dpm_set_pairing_state(enable);
+       if (failed(ret))
+               THROW(ErrCode::RuntimeError) << "Failed to change bluetooth pairing: " << ret;
+
+       INFO(VIST_PLUGIN) << "Bluetooth pairing state is changed to " << enable;
+}
+
+void Tethering::onChanged(const PolicyValue& value)
+{
+       auto enable = value;
+       INFO(VIST_PLUGIN) << "Bluetooth tethering state is changed to " << enable;
+}
+
+Bluetooth::Bluetooth(const std::string& name) : PolicyProvider(name)
+{
+       if (::bt_initialize() != BT_ERROR_NONE)
+               THROW(ErrCode::RuntimeError) << "Failed to init bluetooth provider.";
+}
+
+Bluetooth::~Bluetooth()
+{
+       ::bt_deinitialize();
+}
+
+} // namespace policy
+} // namespace vist
diff --git a/src/vist/table/policy/bluetooth/policy.hpp b/src/vist/table/policy/bluetooth/policy.hpp
new file mode 100644 (file)
index 0000000..3c927df
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ *  Copyright (c) 2019-present Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+
+#pragma once
+
+#include <vist/sdk/policy-model.hpp>
+#include <vist/sdk/policy-provider.hpp>
+#include <vist/sdk/policy-value.hpp>
+
+namespace vist {
+namespace policy {
+
+class BluetoothState : public PolicyModel {
+public:
+       BluetoothState() : PolicyModel("bluetooth", PolicyValue(1)) {}
+       void onChanged(const PolicyValue& value) override;
+};
+
+class DesktopConnectivity : public PolicyModel {
+public:
+       DesktopConnectivity() : PolicyModel("bluetooth-desktop-connectivity", PolicyValue(1)) {}
+       void onChanged(const PolicyValue& value) override;
+};
+
+class Pairing: public PolicyModel {
+public:
+       Pairing() : PolicyModel("bluetooth-pairing", PolicyValue(1)) {}
+       void onChanged(const PolicyValue& value) override;
+};
+
+class Tethering: public PolicyModel {
+public:
+       Tethering() : PolicyModel("bluetooth-tethering", PolicyValue(1)) {}
+       void onChanged(const PolicyValue&);
+};
+
+class Bluetooth final : public PolicyProvider {
+public:
+       Bluetooth(const std::string& name);
+       ~Bluetooth();
+};
+
+} // namespace policy
+} // namespace vist
diff --git a/src/vist/table/policy/bluetooth/table.cpp b/src/vist/table/policy/bluetooth/table.cpp
new file mode 100644 (file)
index 0000000..4af0a16
--- /dev/null
@@ -0,0 +1,134 @@
+/*
+ *  Copyright (c) 2020-present Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+
+#include "policy.hpp"
+#include "table.hpp"
+
+#include <vist/exception.hpp>
+#include <vist/json.hpp>
+#include <vist/logger.hpp>
+#include <vist/policy/api.hpp>
+
+extern "C" vist::table::DynamicTable* DynamicTableFactory()
+{
+       return new vist::table::BluetoothTable;
+}
+
+namespace vist {
+namespace table {
+
+namespace {
+
+std::map<std::string, std::string> ALIAS = {
+       { "state", "bluetooth" },
+       { "desktopConnectivity", "bluetooth-desktop-connectivity" },
+       { "pairing", "bluetooth-pairing" },
+       { "tethering", "bluetooth-tethering"}
+};
+
+void setPolicy(const std::string& name, int value)
+{
+       vist::policy::API::Admin::Set(name, vist::policy::PolicyValue(value));
+}
+
+} // anonymous namespace
+
+void BluetoothTable::init()
+{
+       DynamicTable::Register("bluetooth", std::make_shared<BluetoothTable>());
+
+       auto provider = std::make_shared<policy::Bluetooth>("bluetooth");
+       provider->add(std::make_shared<policy::BluetoothState>());
+       provider->add(std::make_shared<policy::DesktopConnectivity>());
+       provider->add(std::make_shared<policy::Pairing>());
+       provider->add(std::make_shared<policy::Tethering>());
+
+       policy::API::Admin::AddProvider(provider);
+
+       INFO(VIST_PLUGIN) << "Bluetooth plugin loaded.";
+}
+
+TableColumns BluetoothTable::columns() const
+{
+       return {
+               std::make_tuple("state", INTEGER_TYPE, ColumnOptions::DEFAULT),
+               std::make_tuple("desktopConnectivity", INTEGER_TYPE, ColumnOptions::DEFAULT),
+               std::make_tuple("pairing", INTEGER_TYPE, ColumnOptions::DEFAULT),
+               std::make_tuple("tethering", INTEGER_TYPE, ColumnOptions::DEFAULT),
+       };
+}
+
+TableRows BluetoothTable::generate(QueryContext&) try
+{
+       INFO(VIST) << "Select query about bluetooth table.";
+
+       Row row;
+       for (const auto& [schemaName, policyName] : ALIAS) {
+               int value = vist::policy::API::Get(policyName);
+               row[schemaName] = std::to_string(value);
+       }
+
+       QueryData results;
+       results.emplace_back(std::move(row));
+
+       return osquery::tableRowsFromQueryData(std::move(results));
+} catch (const vist::Exception<ErrCode>& e)
+{
+       ERROR(VIST) << "Failed to query: " << e.what();
+       Row r;
+       return osquery::tableRowsFromQueryData({ r });
+} catch (...)
+{
+       ERROR(VIST) << "Failed to query with unknown exception.";
+       Row r;
+       return osquery::tableRowsFromQueryData({ r });
+}
+
+QueryData BluetoothTable::update(QueryContext&, const PluginRequest& request) try
+{
+       INFO(VIST) << "Update query about bluetooth table.";
+       if (request.count("json_values") == 0)
+               throw std::runtime_error("Wrong request format. Not found json value.");
+
+       DEBUG(VIST) << "Request values: " << request.at("json_values");
+       json::Json document = json::Json::Parse(request.at("json_values"));
+       json::Array values = document.get<json::Array>("values");
+       if (values.size() != 4)
+               throw std::runtime_error("Wrong request format.");
+
+       /// TODO(Sangwan): Sync vtab schema with policy definition
+       setPolicy("bluetooth", static_cast<int>(values.at(0)));
+       setPolicy("bluetooth-desktop-connectivity", static_cast<int>(values.at(1)));
+       setPolicy("bluetooth-pairing", static_cast<int>(values.at(2)));
+       setPolicy("bluetooth-tethering", static_cast<int>(values.at(3)));
+
+       Row r;
+       r["status"] = "success";
+       return { r };
+} catch (const vist::Exception<ErrCode>& e)
+{
+       ERROR(VIST) << "Failed to query: " << e.what();
+       Row r;
+       return { r };
+} catch (...)
+{
+       ERROR(VIST) << "Failed to query with unknown exception.";
+       Row r;
+       return { r };
+}
+
+} // namespace table
+} // namespace vist
diff --git a/src/vist/table/policy/bluetooth/table.hpp b/src/vist/table/policy/bluetooth/table.hpp
new file mode 100644 (file)
index 0000000..67996b0
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ *  Copyright (c) 2020-present Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/*
+ * Query example
+ * - SELECT * FROM bluetooth
+ * - UPDATE bluetooth SET state = 1 // enable
+ * - UPDATE bluetooth SET state = 0 // disable
+ */
+
+#include <vist/table/dynamic-table.hpp>
+
+namespace vist {
+namespace table {
+
+class BluetoothTable final : public DynamicTable {
+public:
+       void init();
+
+private:
+       TableColumns columns() const override;
+       TableRows generate(QueryContext&) override;
+       QueryData update(QueryContext&, const PluginRequest& request) override;
+};
+
+} // namespace table
+} // namespace vist
diff --git a/src/vist/table/policy/bluetooth/tests/bluetooth.cpp b/src/vist/table/policy/bluetooth/tests/bluetooth.cpp
new file mode 100644 (file)
index 0000000..d682805
--- /dev/null
@@ -0,0 +1,83 @@
+/*
+ *  Copyright (c) 2019-present Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+
+#include "../policy.hpp"
+
+#include <vist/client/query.hpp>
+#include <vist/exception.hpp>
+#include <vist/sdk/policy-model.hpp>
+#include <vist/sdk/policy-value.hpp>
+
+#include <iostream>
+
+#include <gtest/gtest.h>
+
+using namespace vist;
+using namespace vist::policy;
+
+namespace {
+
+template <typename T>
+void change_policy_state()
+{
+       std::shared_ptr<PolicyModel> policy = std::make_shared<T>();
+       /// enable policy
+       policy->onChanged(PolicyValue(1));
+       /// disable policy
+       policy->onChanged(PolicyValue(0));
+}
+
+} // anonymous namespace
+
+TEST(BluetoothTests, change_policy_state)
+{
+       try {
+               change_policy_state<BluetoothState>();
+               change_policy_state<DesktopConnectivity>();
+               change_policy_state<Pairing>();
+               change_policy_state<Tethering>();
+       } catch(const vist::Exception<ErrCode>& e) {
+               EXPECT_TRUE(false) << e.what();
+       }
+}
+
+TEST(BluetoothTests, get_policies)
+{
+       auto rows = Query::Execute("SELECT * FROM bluetooth");
+
+       EXPECT_TRUE(rows.size() == 1);
+}
+
+TEST(BluetoothTests, set_policies)
+{
+       // Binany should be enrolled as admin to control policy.
+       Query::Execute("INSERT INTO policy_admin (name) VALUES ('vist-bluetooth-policy-test')");
+
+       Query::Execute("UPDATE bluetooth SET desktopConnectivity = 3, state = 7");
+       Query::Execute("UPDATE bluetooth SET pairing = 2, tethering = 9");
+
+       auto rows = Query::Execute("SELECT * FROM bluetooth");
+       if (rows.size() == 1) {
+               EXPECT_EQ(rows[0]["state"], "7");
+               EXPECT_EQ(rows[0]["desktopConnectivity"], "3");
+               EXPECT_EQ(rows[0]["pairing"], "2");
+               EXPECT_EQ(rows[0]["tethering"], "9");
+       } else {
+               EXPECT_TRUE(false);
+       }
+
+       Query::Execute("DELETE FROM policy_admin WHERE name = 'vist-bluetooth-policy-test'");
+}
index d97eea6689009b21ca455d33d4810859bcda20e2..9a1765a668306468b62d752cf04fa4d1de1f4cef 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 #
-SET(TARGET "vist-plugin-sample")
+SET(TARGET "vist-table-sample")
 
 INCLUDE_DIRECTORIES(SYSTEM)
 
-ADD_LIBRARY(${TARGET} SHARED sample.cpp)
+ADD_LIBRARY(${TARGET} SHARED table.cpp)
 TARGET_LINK_LIBRARIES(${TARGET} vist-common ${TARGET_VIST_POLICY_LIB})
 
 INSTALL(TARGETS ${TARGET} DESTINATION ${TABLE_INSTALL_DIR})
diff --git a/src/vist/table/policy/sample/policy.hpp b/src/vist/table/policy/sample/policy.hpp
new file mode 100644 (file)
index 0000000..b9c309f
--- /dev/null
@@ -0,0 +1,79 @@
+/*
+ *  Copyright (c) 2020-present Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+
+#pragma once
+
+#include <vist/logger.hpp>
+#include <vist/sdk/policy-model.hpp>
+#include <vist/sdk/policy-provider.hpp>
+#include <vist/sdk/policy-value.hpp>
+
+#include <memory>
+#include <string>
+
+namespace vist {
+namespace policy {
+
+class SampleIntPolicy : public PolicyModel {
+public:
+       SampleIntPolicy() : PolicyModel("sample_int_policy", PolicyValue(7))
+       {
+       }
+
+       void onChanged(const PolicyValue& value) override
+       {
+               INFO(VIST_PLUGIN) << "sample_int_policy is changed to "
+                                                 << static_cast<int>(value);
+       }
+};
+
+class SampleStrPolicy : public PolicyModel {
+public:
+       SampleStrPolicy() : PolicyModel("sample_str_policy", PolicyValue("TEST"))
+       {
+       }
+
+       void onChanged(const PolicyValue& value) override
+       {
+               INFO(VIST_PLUGIN) << "sample_str_policy is changed to "
+                                                 << static_cast<std::string>(value);
+       }
+
+       int compare(const PolicyValue& lhs, const PolicyValue& rhs) const override
+       {
+               std::string lvalue = lhs;
+               std::string rvalue = rhs;
+
+               INFO(VIST_PLUGIN) << "Custom compare method is called with [" << lvalue
+                                                 << "], [" << rvalue << "]";
+
+               return lvalue.compare(rvalue);
+       }
+};
+
+class SampleProvider : public PolicyProvider {
+public:
+       SampleProvider(const std::string& name) : PolicyProvider(name)
+       {
+       }
+
+       ~SampleProvider()
+       {
+       }
+};
+
+} // namespace policy
+} // namespace vist
diff --git a/src/vist/table/policy/sample/sample.cpp b/src/vist/table/policy/sample/sample.cpp
deleted file mode 100644 (file)
index f5d02a2..0000000
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- *  Copyright (c) 2019-present Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License
- */
-
-#include "sample.hpp"
-
-#include <vist/sdk/policy-model.hpp>
-#include <vist/sdk/policy-value.hpp>
-#include <vist/sdk/policy-provider.hpp>
-
-#include <vist/logger.hpp>
-#include <vist/policy/api.hpp>
-
-#include <osquery/registry.h>
-#include <osquery/sql/dynamic_table_row.h>
-
-extern "C" vist::table::DynamicTable* DynamicTableFactory()
-{
-       return new vist::table::SamplePolicyTable;
-}
-
-namespace vist {
-namespace table {
-
-using namespace osquery;
-
-void SamplePolicyTable::init()
-{
-       // Register virtual table to sqlite3
-       auto tables = RegistryFactory::get().registry("table");
-       tables->add("sample_policy", std::make_shared<SamplePolicyTable>());
-
-       // Register policy to policy-manager
-       auto provider = std::make_shared<policy::Sample>("sample-provider");
-       provider->add(std::make_shared<policy::SampleIntPolicy>());
-       provider->add(std::make_shared<policy::SampleStrPolicy>());
-
-       policy::API::Admin::AddProvider(std::move(provider));
-
-       INFO(VIST_PLUGIN) << "Sample plugin loaded.";
-}
-
-TableColumns SamplePolicyTable::columns() const
-{
-       return {
-               std::make_tuple("sample_int_policy", INTEGER_TYPE, ColumnOptions::DEFAULT),
-               std::make_tuple("sample_str_policy", TEXT_TYPE, ColumnOptions::DEFAULT),
-       };
-}
-
-TableRows SamplePolicyTable::generate(QueryContext&) try
-{
-       INFO(VIST) << "Select query about sample-policy table.";
-
-       Row row;
-       int intPolicy = vist::policy::API::Get("sample_int_policy");
-       row["sample_int_policy"] = std::to_string(intPolicy);
-
-       std::string strPolicy = vist::policy::API::Get("sample_str_policy");
-       row["sample_str_policy"] = strPolicy;
-
-       QueryData results;
-       results.emplace_back(std::move(row));
-
-       return osquery::tableRowsFromQueryData(std::move(results));
-} catch (const vist::Exception<ErrCode>& e)
-{
-       ERROR(VIST) << "Failed to query: " << e.what();
-       Row r;
-       return osquery::tableRowsFromQueryData({ r });
-} catch (...)
-{
-       ERROR(VIST) << "Failed to query with unknown exception.";
-       Row r;
-       return osquery::tableRowsFromQueryData({ r });
-}
-
-QueryData SamplePolicyTable::update(QueryContext&, const PluginRequest& request) try
-{
-       INFO(VIST) << "Update query about sample-policy table.";
-       if (request.count("json_values") == 0)
-               throw std::runtime_error("Wrong request format. Not found json value.");
-
-       DEBUG(VIST) << "Request values: " << request.at("json_values");
-       json::Json document = json::Json::Parse(request.at("json_values"));
-       json::Array values = document.get<json::Array>("values");
-       if (values.size() != 2)
-               throw std::runtime_error("Wrong request format.");
-
-       policy::API::Admin::Set("sample_int_policy",
-                       policy::PolicyValue(static_cast<int>(values.at(0))));
-       policy::API::Admin::Set("sample_str_policy",
-                       policy::PolicyValue(static_cast<std::string>(values.at(1))));
-
-       Row r;
-       r["status"] = "success";
-       return { r };
-} catch (const vist::Exception<ErrCode>& e)
-{
-       ERROR(VIST) << "Failed to query: " << e.what();
-       Row r;
-       return { r };
-} catch (...)
-{
-       ERROR(VIST) << "Failed to query with unknown exception.";
-       Row r;
-       return { r };
-}
-
-} // namespace table
-} // namespace vist
diff --git a/src/vist/table/policy/sample/sample.hpp b/src/vist/table/policy/sample/sample.hpp
deleted file mode 100644 (file)
index 3b241f5..0000000
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- *  Copyright (c) 2020-present Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License
- */
-/*
- * Query example
- * - SELECT * FROM sample_policy
- * - UPDATE sample_policy SET sample_int_policy = 99
- * - UPDATE sample_policy SET sample_str_policy = 'TEST_VALUE'
- */
-
-#include <vist/logger.hpp>
-#include <vist/table/dynamic-table.hpp>
-
-#include <vist/sdk/policy-model.hpp>
-#include <vist/sdk/policy-provider.hpp>
-#include <vist/sdk/policy-value.hpp>
-
-#include <osquery/tables.h>
-
-#include <memory>
-#include <string>
-
-namespace vist {
-namespace policy {
-
-class SampleIntPolicy : public PolicyModel {
-public:
-       SampleIntPolicy() : PolicyModel("sample_int_policy", PolicyValue(7))
-       {
-       }
-
-       void onChanged(const PolicyValue& value) override
-       {
-               INFO(VIST_PLUGIN) << "sample_int_policy is changed to "
-                                                 << static_cast<int>(value);
-       }
-};
-
-class SampleStrPolicy : public PolicyModel {
-public:
-       SampleStrPolicy() : PolicyModel("sample_str_policy", PolicyValue("TEST"))
-       {
-       }
-
-       void onChanged(const PolicyValue& value) override
-       {
-               INFO(VIST_PLUGIN) << "sample_str_policy is changed to "
-                                                 << static_cast<std::string>(value);
-       }
-
-       int compare(const PolicyValue& lhs, const PolicyValue& rhs) const override
-       {
-               std::string lvalue = lhs;
-               std::string rvalue = rhs;
-
-               INFO(VIST_PLUGIN) << "Custom compare method is called with [" << lvalue
-                                                 << "], [" << rvalue << "]";
-
-               return lvalue.compare(rvalue);
-       }
-};
-
-class Sample : public PolicyProvider {
-public:
-       Sample(const std::string& name) : PolicyProvider(name)
-       {
-       }
-
-       ~Sample()
-       {
-       }
-};
-} // namespace policy
-
-namespace table {
-
-using namespace osquery;
-
-class SamplePolicyTable final : public DynamicTable {
-public:
-       void init();
-
-private:
-       TableColumns columns() const override;
-       TableRows generate(QueryContext&) override;
-       QueryData update(QueryContext&, const PluginRequest& request) override;
-};
-
-} // namespace table
-} // namespace vist
diff --git a/src/vist/table/policy/sample/table.cpp b/src/vist/table/policy/sample/table.cpp
new file mode 100644 (file)
index 0000000..3fc8019
--- /dev/null
@@ -0,0 +1,116 @@
+/*
+ *  Copyright (c) 2020-present Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+
+#include "policy.hpp"
+#include "table.hpp"
+
+#include <vist/exception.hpp>
+#include <vist/json.hpp>
+#include <vist/logger.hpp>
+#include <vist/policy/api.hpp>
+
+extern "C" vist::table::DynamicTable* DynamicTableFactory()
+{
+       return new vist::table::SamplePolicyTable;
+}
+
+namespace vist {
+namespace table {
+
+void SamplePolicyTable::init()
+{
+       DynamicTable::Register("sample_policy", std::make_shared<SamplePolicyTable>());
+
+       // Register policy to policy-manager
+       using namespace policy;
+       auto provider = std::make_shared<SampleProvider>("sample-provider");
+       provider->add(std::make_shared<SampleIntPolicy>());
+       provider->add(std::make_shared<SampleStrPolicy>());
+
+       policy::API::Admin::AddProvider(std::move(provider));
+
+       INFO(VIST_PLUGIN) << "Sample plugin loaded.";
+}
+
+TableColumns SamplePolicyTable::columns() const
+{
+       return {
+               std::make_tuple("sample_int_policy", INTEGER_TYPE, ColumnOptions::DEFAULT),
+               std::make_tuple("sample_str_policy", TEXT_TYPE, ColumnOptions::DEFAULT),
+       };
+}
+
+TableRows SamplePolicyTable::generate(QueryContext&) try
+{
+       INFO(VIST) << "Select query about sample-policy table.";
+
+       Row row;
+       int intPolicy = vist::policy::API::Get("sample_int_policy");
+       row["sample_int_policy"] = std::to_string(intPolicy);
+
+       std::string strPolicy = vist::policy::API::Get("sample_str_policy");
+       row["sample_str_policy"] = strPolicy;
+
+       QueryData results;
+       results.emplace_back(std::move(row));
+
+       return osquery::tableRowsFromQueryData(std::move(results));
+} catch (const vist::Exception<ErrCode>& e)
+{
+       ERROR(VIST) << "Failed to query: " << e.what();
+       Row r;
+       return osquery::tableRowsFromQueryData({ r });
+} catch (...)
+{
+       ERROR(VIST) << "Failed to query with unknown exception.";
+       Row r;
+       return osquery::tableRowsFromQueryData({ r });
+}
+
+QueryData SamplePolicyTable::update(QueryContext&, const PluginRequest& request) try
+{
+       INFO(VIST) << "Update query about sample-policy table.";
+       if (request.count("json_values") == 0)
+               throw std::runtime_error("Wrong request format. Not found json value.");
+
+       DEBUG(VIST) << "Request values: " << request.at("json_values");
+       json::Json document = json::Json::Parse(request.at("json_values"));
+       json::Array values = document.get<json::Array>("values");
+       if (values.size() != 2)
+               throw std::runtime_error("Wrong request format.");
+
+       policy::API::Admin::Set("sample_int_policy",
+                       policy::PolicyValue(static_cast<int>(values.at(0))));
+       policy::API::Admin::Set("sample_str_policy",
+                       policy::PolicyValue(static_cast<std::string>(values.at(1))));
+
+       Row r;
+       r["status"] = "success";
+       return { r };
+} catch (const vist::Exception<ErrCode>& e)
+{
+       ERROR(VIST) << "Failed to query: " << e.what();
+       Row r;
+       return { r };
+} catch (...)
+{
+       ERROR(VIST) << "Failed to query with unknown exception.";
+       Row r;
+       return { r };
+}
+
+} // namespace table
+} // namespace vist
diff --git a/src/vist/table/policy/sample/table.hpp b/src/vist/table/policy/sample/table.hpp
new file mode 100644 (file)
index 0000000..ff80992
--- /dev/null
@@ -0,0 +1,40 @@
+/*
+ *  Copyright (c) 2020-present Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/*
+ * Query example
+ * - SELECT * FROM sample_policy
+ * - UPDATE sample_policy SET sample_int_policy = 99
+ * - UPDATE sample_policy SET sample_str_policy = 'TEST_VALUE'
+ */
+
+#include <vist/logger.hpp>
+#include <vist/table/dynamic-table.hpp>
+
+namespace vist {
+namespace table {
+
+class SamplePolicyTable final : public DynamicTable {
+public:
+       void init();
+
+private:
+       TableColumns columns() const override;
+       TableRows generate(QueryContext&) override;
+       QueryData update(QueryContext&, const PluginRequest& request) override;
+};
+
+} // namespace table
+} // namespace vist