Make virtual table at runtime
authorSangwan Kwon <sangwan.kwon@samsung.com>
Mon, 27 Apr 2020 09:59:55 +0000 (18:59 +0900)
committer권상완/Security 2Lab(SR)/Engineer/삼성전자 <sangwan.kwon@samsung.com>
Tue, 28 Apr 2020 07:13:55 +0000 (16:13 +0900)
Signed-off-by: Sangwan Kwon <sangwan.kwon@samsung.com>
31 files changed:
CMakeLists.txt
plugins/bluetooth/bluetooth-test.cpp
specs/CMakeLists.txt [deleted file]
specs/blacklist [deleted file]
specs/tizen/bluetooth.table [deleted file]
specs/tizen/policy.table [deleted file]
specs/tizen/policy_admin.table [deleted file]
specs/utility/time.table [deleted file]
src/osquery/CMakeLists.txt
src/osquery/tables/CMakeLists.txt [deleted file]
src/osquery/tables/tizen/bluetooth.cpp [deleted file]
src/osquery/tables/tizen/policy.cpp [deleted file]
src/osquery/tables/tizen/policy_admin.cpp [deleted file]
src/osquery/tables/tizen/tests/policy.cpp [deleted file]
src/osquery/tables/utility/time.cpp [deleted file]
src/vist/CMakeLists.txt
src/vist/client/schema/bluetooth.hpp [deleted file]
src/vist/client/schema/policy.hpp [deleted file]
src/vist/client/schema/time.hpp [deleted file]
src/vist/client/tests/virtual-table.cpp
src/vist/client/virtual-table.cpp
src/vist/schema/bluetooth.hpp [new file with mode: 0644]
src/vist/schema/policy.hpp [new file with mode: 0644]
src/vist/service/vistd.cpp
src/vist/table/CMakeLists.txt [new file with mode: 0644]
src/vist/table/bluetooth.cpp [new file with mode: 0644]
src/vist/table/bluetooth.hpp [new file with mode: 0644]
src/vist/table/policy-admin.cpp [new file with mode: 0644]
src/vist/table/policy-admin.hpp [new file with mode: 0644]
src/vist/table/policy.cpp [new file with mode: 0644]
src/vist/table/policy.hpp [new file with mode: 0644]

index ce8c0be95c8d42c1b13aa2f995bf51e52ceeda2b..d28a2bdb89f60e237bd7e53e953dcd7680310f57 100644 (file)
@@ -49,8 +49,9 @@ ADD_DEFINITIONS(-DOSQUERY_VERSION=${OSQUERY_VERSION}
                                -DOSQUERY_BUILD_VERSION=${OSQUERY_VERSION}
                                -DOSQUERY_BUILD_SDK_VERSION=${OSQUERY_VERSION})
 
-INCLUDE_DIRECTORIES("${CMAKE_SOURCE_DIR}/src")
-INCLUDE_DIRECTORIES("${CMAKE_SOURCE_DIR}/src/osquery/include")
+# Suppresse SYSTEM header's warnings:
+INCLUDE_DIRECTORIES(SYSTEM "${CMAKE_SOURCE_DIR}/src")
+INCLUDE_DIRECTORIES(SYSTEM "${CMAKE_SOURCE_DIR}/src/osquery/include")
 INCLUDE_DIRECTORIES("/usr/local/include")
 
 ENABLE_TESTING()
@@ -59,7 +60,6 @@ ENABLE_TESTING()
 EXECUTE_PROCESS(COMMAND mkdir -p "${CMAKE_BINARY_DIR}/generated")
 
 ADD_SUBDIRECTORY(data)
-ADD_SUBDIRECTORY(specs)
 ADD_SUBDIRECTORY(src)
 ADD_SUBDIRECTORY(plugins)
 
index 6a68d7b201ffedf7186d166ac5d513df2308791a..1c282a82a069d75c2a8921a13be37524f2b6320b 100644 (file)
@@ -18,7 +18,7 @@
 #include "../test-util.hpp"
 
 #include <vist/client/query.hpp>
-#include <vist/client/schema/bluetooth.hpp>
+#include <vist/schema/bluetooth.hpp>
 #include <vist/exception.hpp>
 
 #include <iostream>
diff --git a/specs/CMakeLists.txt b/specs/CMakeLists.txt
deleted file mode 100644 (file)
index 56724b4..0000000
+++ /dev/null
@@ -1,68 +0,0 @@
-#  Copyright (c) 2019 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(OSQUERY_CODEGEN_PATH "${CMAKE_SOURCE_DIR}/tools/codegen")
-SET(OSQUERY_TABLES_PATH "${CMAKE_SOURCE_DIR}")
-SET(OSQUERY_GENERATED_PATH "${CMAKE_BINARY_DIR}/generated")
-
-SET(GENERATED_TABLES "")
-
-FILE(GLOB TABLE_FILES "${CMAKE_SOURCE_DIR}/specs/*.table")
-FILE(GLOB TABLE_FILES_LINUX "${CMAKE_SOURCE_DIR}/specs/linux/*.table")
-FILE(GLOB TABLE_FILES_UTILITY "${CMAKE_SOURCE_DIR}/specs/utility/*.table")
-FILE(GLOB TABLE_FILES_TIZEN "${CMAKE_SOURCE_DIR}/specs/tizen/*.table")
-LIST(APPEND TABLE_FILES ${TABLE_FILES_LINUX})
-LIST(APPEND TABLE_FILES ${TABLE_FILES_UTILITY})
-LIST(APPEND TABLE_FILES ${TABLE_FILES_TIZEN})
-
-FILE(GLOB TABLE_FILES_TEMPLATES "${CMAKE_SOURCE_DIR}/tools/codegen/templates/*.in")
-SET(GENERATION_DEPENDENCIES "${OSQUERY_CODEGEN_PATH}/gentable.py"
-                                                       "${OSQUERY_CODEGEN_PATH}/amalgamate.py"
-                                                       "${OSQUERY_TABLES_PATH}/specs/blacklist")
-
-LIST(APPEND GENERATION_DEPENDENCIES ${TABLE_FILES_TEMPLATES})
-
-FOREACH(TABLE_FILE ${TABLE_FILES})
-       SET(TABLE_FILE_GEN ${TABLE_FILE})
-       STRING(REPLACE "${OSQUERY_TABLES_PATH}/specs"
-                                  "${OSQUERY_GENERATED_PATH}/tables"
-                                  TABLE_FILE_GEN
-                                  ${TABLE_FILE_GEN})
-       STRING(REPLACE "linux/" "" TABLE_FILE_GEN ${TABLE_FILE_GEN})
-       STRING(REPLACE "" "" TABLE_FILE_GEN ${TABLE_FILE_GEN})
-       STRING(REPLACE ".table" ".cpp" TABLE_FILE_GEN ${TABLE_FILE_GEN})
-       ADD_CUSTOM_COMMAND(
-               OUTPUT ${TABLE_FILE_GEN}
-               COMMAND
-                       python "${OSQUERY_CODEGEN_PATH}/gentable.py" "${TABLE_FILE}" "${TABLE_FILE_GEN}" "$ENV{DISABLE_BLACKLIST}"
-               DEPENDS
-                       ${TABLE_FILE} ${GENERATION_DEPENDENCIES}
-
-               WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
-       LIST(APPEND GENERATED_TABLES ${TABLE_FILE_GEN})
-ENDFOREACH()
-
-SET(AMALGAMATION_FILE_GEN "${OSQUERY_GENERATED_PATH}/amalgamation.cpp")
-ADD_CUSTOM_COMMAND(
-       OUTPUT ${AMALGAMATION_FILE_GEN}
-       COMMAND
-               python "${OSQUERY_CODEGEN_PATH}/amalgamate.py"
-                       --templates "${OSQUERY_CODEGEN_PATH}/templates"
-                       --sources "${OSQUERY_GENERATED_PATH}"
-                       --output "${AMALGAMATION_FILE_GEN}"
-       DEPENDS
-               ${GENERATED_TABLES}
-       WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
-
-ADD_LIBRARY(osquery_generated_tables OBJECT "${AMALGAMATION_FILE_GEN}")
diff --git a/specs/blacklist b/specs/blacklist
deleted file mode 100644 (file)
index 376bf40..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-# osquery/tables/specs/blacklist
-# Usage: add table spec names to this list to prevent table generation
-# Example: add tables that are not yet ready for release
-
-quarantine
diff --git a/specs/tizen/bluetooth.table b/specs/tizen/bluetooth.table
deleted file mode 100644 (file)
index a803826..0000000
+++ /dev/null
@@ -1,10 +0,0 @@
-table_name("bluetooth")
-description("The policies related bluetooth.")
-schema([
-    Column("state", INTEGER, "The policy value about bluetooth state"),
-    Column("desktopConnectivity", INTEGER, "The policy value about bt desktop connectivity"),
-    Column("pairing", INTEGER, "The policy value about bluetooth pairing"),
-    Column("tethering", INTEGER, "The policy value about bluetooth tethering"),
-])
-implementation("tizen/bluetooth@genBluetooth")
-implementation_update("tizen/bluetooth@updateBluetooth")
diff --git a/specs/tizen/policy.table b/specs/tizen/policy.table
deleted file mode 100644 (file)
index 32eaa4f..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-table_name("policy")
-description("Device polices.")
-schema([
-    Column("name", TEXT, "Policy name"),
-    Column("value", TEXT, "Policy value"),
-])
-implementation("tizen/policy@genPolicy")
-implementation_update("tizen/policy@updatePolicy")
-examples([
-  "select * from policy where name = 'bluetooth'",
-  "update policy set value = 'I/1' where name = 'bluetooth'",
-])
diff --git a/specs/tizen/policy_admin.table b/specs/tizen/policy_admin.table
deleted file mode 100644 (file)
index 6c6ee9b..0000000
+++ /dev/null
@@ -1,10 +0,0 @@
-table_name("policy_admin")
-description("Policy administrator.")
-schema([
-    Column("name", TEXT, "Policy admin name"),
-    Column("activated", INTEGER, "State of activation"),
-])
-implementation("tizen/policy_admin@genPolicyAdmin")
-implementation_delete("tizen/policy_admin@deletePolicyAdmin")
-implementation_insert("tizen/policy_admin@insertPolicyAdmin")
-implementation_update("tizen/policy_admin@updatePolicyAdmin")
diff --git a/specs/utility/time.table b/specs/utility/time.table
deleted file mode 100644 (file)
index 6177722..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-table_name("time")
-description("Track current date and time in the system.")
-schema([
-    Column("weekday", TEXT, "Current weekday in the system"),
-    Column("year", INTEGER, "Current year in the system"),
-    Column("month", INTEGER, "Current month in the system"),
-    Column("day", INTEGER, "Current day in the system"),
-    Column("hour", INTEGER, "Current hour in the system"),
-    Column("minutes", INTEGER, "Current minutes in the system"),
-    Column("seconds", INTEGER, "Current seconds in the system"),
-    Column("timezone", TEXT, "Current timezone in the system"),
-    Column("local_time", INTEGER, "Current local UNIX time in the system",
-        aliases=["localtime"]),
-    Column("local_timezone", TEXT, "Current local timezone in the system"),
-    Column("unix_time", INTEGER,
-        "Current UNIX time in the system, converted to UTC if --utc enabled"),
-    Column("timestamp", TEXT, "Current timestamp (log format) in the system"),
-    Column("datetime", TEXT, "Current date and time (ISO format) in the system",
-        aliases=["date_time"]),
-    Column("iso_8601", TEXT, "Current time (ISO format) in the system"),
-])
-extended_schema(WINDOWS, [
-    Column("win_timestamp", BIGINT, "Timestamp value in 100 nanosecond units."),
-])
-attributes(utility=True)
-implementation("time@genTime")
index a61e584d50859e72d9f8a09bef6feae8629c3bae..216fd9231dbeb4eee16b6a24280f83242d12d6e7 100644 (file)
@@ -1,4 +1,4 @@
-#  Copyright (c) 2019 Samsung Electronics Co., Ltd All Rights Reserved
+#  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.
@@ -38,12 +38,9 @@ ENDIF(DEFINED GBS_BUILD)
 ADD_SUBDIRECTORY(core)
 ADD_SUBDIRECTORY(registry)
 ADD_SUBDIRECTORY(sql)
-ADD_SUBDIRECTORY(tables)
 ADD_SUBDIRECTORY(utils)
 
-ADD_LIBRARY(${TARGET_OSQUERY_LIB}
-                               STATIC $<TARGET_OBJECTS:osquery_generated_tables>
-                                          ${${TARGET_OSQUERY_LIB}_SRCS})
+ADD_LIBRARY(${TARGET_OSQUERY_LIB} STATIC ${${TARGET_OSQUERY_LIB}_SRCS})
 
 TARGET_LINK_LIBRARIES(${TARGET_OSQUERY_LIB} ${${TARGET_OSQUERY_LIB}_DEPS})
 
diff --git a/src/osquery/tables/CMakeLists.txt b/src/osquery/tables/CMakeLists.txt
deleted file mode 100644 (file)
index 0a9370d..0000000
+++ /dev/null
@@ -1,31 +0,0 @@
-#  Copyright (c) 2019 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
-
-FILE(GLOB OSQUERY_LINUX_TABLES "*/linux/*.cpp")
-ADD_OSQUERY_LIBRARY(osquery_linux_tables ${OSQUERY_LINUX_TABLES})
-
-FILE(GLOB OSQUERY_CROSS_TABLES "[!t]*/*.cpp")
-ADD_OSQUERY_LIBRARY(osquery_tables ${OSQUERY_CROSS_TABLES})
-
-FILE(GLOB OSQUERY_CROSS_TABLES_TESTS "[!uot]*/tests/*.cpp")
-ADD_OSQUERY_TEST(${OSQUERY_CROSS_TABLES_TESTS})
-
-### Tizen
-ADD_OSQUERY_LINK(vist-policy)
-
-FILE(GLOB OSQUERY_TIZEN_TABLES "tizen/*.cpp")
-ADD_OSQUERY_LIBRARY(osquery_tizen_tables ${OSQUERY_TIZEN_TABLES})
-
-FILE(GLOB OSQUERY_TIZEN_TESTS "tizen/tests/*.cpp")
-ADD_OSQUERY_TEST(${OSQUERY_TIZEN_TESTS})
diff --git a/src/osquery/tables/tizen/bluetooth.cpp b/src/osquery/tables/tizen/bluetooth.cpp
deleted file mode 100644 (file)
index 38aeace..0000000
+++ /dev/null
@@ -1,108 +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
- */
-
-#include <string>
-#include <memory>
-#include <stdexcept>
-
-#include <osquery/sql.h>
-#include <osquery/tables.h>
-
-#include <vist/policy/api.hpp>
-#include <vist/exception.hpp>
-#include <vist/logger.hpp>
-
-namespace osquery {
-
-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
-
-namespace tables {
-
-using namespace vist;
-
-QueryData genBluetooth(QueryContext& context) try {
-       INFO(VIST) << "Select query about bluetooth table.";
-
-       QueryData results;
-
-       Row row;
-
-       for (const auto&[schemaName, policyName]: ALIAS) {
-               int value = vist::policy::API::Get(policyName);
-               row[schemaName] = std::to_string(value);
-       }
-
-       results.emplace_back(std::move(row));
-
-       return results;
-} 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 };
-}
-
-QueryData updateBluetooth(QueryContext& context, const PluginRequest& request) try {
-       INFO(VIST) << "Update query about bluetooth table.";
-       if (request.count("json_value_array") == 0)
-               throw std::runtime_error("Wrong request format. Not found json value.");
-
-       std::string str = request.at("json_value_array");
-       rapidjson::Document document;
-       document.Parse(str.c_str());
-       if (document.HasParseError() || !document.IsArray())
-               throw std::runtime_error("Cannot parse request.");
-
-       if (document.Size() != 4)
-               throw std::runtime_error("Wrong request format.");
-
-       /// TODO(Sangwan): Sync vtab schema with policy definition
-       setPolicy("bluetooth", document[0].GetInt());
-       setPolicy("bluetooth-desktop-connectivity", document[1].GetInt());
-       setPolicy("bluetooth-pairing", document[2].GetInt());
-       setPolicy("bluetooth-tethering", document[3].GetInt());
-
-       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 tables
-} // namespace osquery
diff --git a/src/osquery/tables/tizen/policy.cpp b/src/osquery/tables/tizen/policy.cpp
deleted file mode 100644 (file)
index 3d8041a..0000000
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- *  Copyright (c) 2019 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 <string>
-#include <memory>
-#include <stdexcept>
-
-#include <osquery/sql.h>
-#include <osquery/tables.h>
-
-#include <vist/policy/api.hpp>
-#include <vist/exception.hpp>
-#include <vist/logger.hpp>
-
-namespace osquery {
-
-namespace {
-
-Row convert(const std::string& name, const vist::policy::PolicyValue& value)
-{
-       Row r;
-       r["name"] = name;
-       r["value"] = value.dump();
-
-       return r;
-}
-
-} // anonymous namespace
-
-namespace tables {
-
-using namespace vist;
-
-QueryData genPolicy(QueryContext& context) try {
-       INFO(VIST) << "Select query about policy table.";
-
-       QueryData results;
-       if (context.constraints["name"].exists(EQUALS)) { /// where clause
-               auto names = context.constraints["name"].getAll(EQUALS);
-               for (const auto& name : names) {
-                       auto value = vist::policy::API::Get(name);
-                       auto row = convert(name, value);
-
-                       results.emplace_back(std::move(row));
-               }
-       } else { /// select *;
-               auto policies = vist::policy::API::GetAll();
-               for (auto& policy : policies) {
-                       auto row = convert(policy.first, policy.second);
-
-                       results.emplace_back(std::move(row));
-               }
-       }
-
-       return results;
-} 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 };
-}
-
-QueryData updatePolicy(QueryContext& context, const PluginRequest& request) try {
-       INFO(VIST) << "Update query about policy table.";
-       if (request.count("json_value_array") == 0)
-               throw std::runtime_error("Wrong request format. Not found json value.");
-
-       std::string str = request.at("json_value_array");
-       rapidjson::Document document;
-       document.Parse(str.c_str());
-       if (document.HasParseError() || !document.IsArray())
-               throw std::runtime_error("Cannot parse request.");
-
-       if (document.Size() != 2)
-               throw std::runtime_error("Wrong request format.");
-
-       std::string name = document[0].GetString();
-       std::string dumpedValue = document[1].GetString();
-
-       vist::policy::API::Admin::Set(name, vist::policy::PolicyValue(dumpedValue, true));
-
-       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 tables
-} // namespace osquery
diff --git a/src/osquery/tables/tizen/policy_admin.cpp b/src/osquery/tables/tizen/policy_admin.cpp
deleted file mode 100644 (file)
index 58a67f3..0000000
+++ /dev/null
@@ -1,183 +0,0 @@
-/*
- *  Copyright (c) 2019 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 <string>
-#include <memory>
-#include <stdexcept>
-
-#include <osquery/sql.h>
-#include <osquery/tables.h>
-
-#include <vist/policy/api.hpp>
-#include <vist/exception.hpp>
-#include <vist/logger.hpp>
-
-namespace osquery {
-
-namespace {
-
-std::string getValue(std::string&& alias, const std::string& key)
-{
-       auto pos = alias.find(";");
-       auto token = alias.substr(0, pos);
-
-       if (token == key)
-               return alias.erase(0, pos + 1);
-       else
-               return std::string();
-}
-
-std::string parseAdmin(const std::string& request, bool insert = true)
-{
-       rapidjson::Document document;
-       document.Parse(request.c_str());
-       if (document.HasParseError() || !document.IsArray())
-               throw std::runtime_error("Cannot parse request.");
-
-       if (insert)
-               return std::string(document[0].GetString());
-       else
-               return getValue(document[0].GetString(), "name");
-}
-
-} // anonymous namespace
-
-namespace tables {
-
-using namespace vist;
-
-QueryData genPolicyAdmin(QueryContext& context) try {
-       INFO(VIST) << "Select query about policy-admin table.";
-
-       QueryData results;
-       auto admins = vist::policy::API::Admin::GetAll();
-
-       for (auto& admin : admins) {
-               if (context.constraints["name"].exists(EQUALS)) { /// where clause
-                       auto names = context.constraints["name"].getAll(EQUALS);
-                       for (const auto& name : names) {
-                               if (name == admin.first) {
-                                       Row row;
-                                       row["name"] = admin.first;
-                                       row["activated"] = std::to_string(admin.second);
-
-                                       DEBUG(VIST) << "Admin info [name]: " << row["name"]
-                                                               << ", [activated]:" << row["activated"];
-
-                                       results.emplace_back(std::move(row));
-                               }
-                       }
-               } else { /// select *;
-                       Row row;
-                       row["name"] = admin.first;
-                       row["activated"] = std::to_string(admin.second);
-
-                       DEBUG(VIST) << "Admin info [name]: " << row["name"]
-                                               << ", [activated]:" << row["activated"];
-                       results.emplace_back(std::move(row));
-               }
-       }
-
-       return results;
-} 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 };
-}
-
-QueryData insertPolicyAdmin(QueryContext& context, const PluginRequest& request) try {
-       INFO(VIST) << "Insert query about policy-admin table.";
-       if (request.count("json_value_array") == 0)
-               throw std::runtime_error("Wrong request format. Not found json value.");
-
-       auto admin = parseAdmin(request.at("json_value_array"));
-       DEBUG(VIST) << "Admin info [name]: " << admin;
-       vist::policy::API::Admin::Enroll(admin);
-
-       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 };
-}
-
-QueryData deletePolicyAdmin(QueryContext& context, const PluginRequest& request) try {
-       INFO(VIST) << "Delete query about policy-admin table.";
-       if (request.count("json_value_array") == 0)
-               throw std::runtime_error("Wrong request format. Not found json value.");
-
-       auto admin = parseAdmin(request.at("json_value_array"), false);
-       DEBUG(VIST) << "Admin info [name]: " << admin;
-       vist::policy::API::Admin::Disenroll(admin);
-
-       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 };
-}
-
-QueryData updatePolicyAdmin(QueryContext& context, const PluginRequest& request) try {
-       INFO(VIST) << "Update query about policy-admin table.";
-       if (request.count("json_value_array") == 0)
-               throw std::runtime_error("Wrong request format. Not found json value.");
-
-       std::string str = request.at("json_value_array");
-       rapidjson::Document document;
-       document.Parse(str.c_str());
-       if (document.HasParseError() || !document.IsArray())
-               throw std::runtime_error("Cannot parse request.");
-
-       if (document.Size() != 2)
-               throw std::runtime_error("Wrong request format.");
-
-       std::string name = document[0].GetString();
-       int activated = document[1].GetInt();
-
-       vist::policy::API::Admin::Activate(name, activated);
-
-       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 tables
-} // namespace osquery
diff --git a/src/osquery/tables/tizen/tests/policy.cpp b/src/osquery/tables/tizen/tests/policy.cpp
deleted file mode 100644 (file)
index 482b4a7..0000000
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- *  Copyright (c) 2019 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 <gtest/gtest.h>
-
-#include <vist/policy/api.hpp>
-
-using namespace vist;
-
-class PolicyTests : public testing::Test {};
-
-TEST_F(PolicyTests, get_all) {
-       auto policies = policy::API::GetAll();
-
-       EXPECT_TRUE(policies.size() > 0);
-}
-
-TEST_F(PolicyTests, get_admin_all) {
-       auto admins = policy::API::Admin::GetAll();
-       EXPECT_EQ(admins.size(), 1);
-
-       policy::API::Admin::Enroll("testAdmin");
-       admins = policy::API::Admin::GetAll();
-       EXPECT_EQ(admins.size(), 2);
-
-       policy::API::Admin::Enroll("testAdmin1");
-       admins = policy::API::Admin::GetAll();
-       EXPECT_EQ(admins.size(), 3);
-
-       policy::API::Admin::Disenroll("testAdmin");
-       admins = policy::API::Admin::GetAll();
-       EXPECT_EQ(admins.size(), 2);
-
-       policy::API::Admin::Disenroll("testAdmin1");
-       admins = policy::API::Admin::GetAll();
-       EXPECT_EQ(admins.size(), 1);
-}
diff --git a/src/osquery/tables/utility/time.cpp b/src/osquery/tables/utility/time.cpp
deleted file mode 100644 (file)
index 42565e9..0000000
+++ /dev/null
@@ -1,89 +0,0 @@
-/**
- *  Copyright (c) 2014-present, Facebook, Inc.
- *  All rights reserved.
- *
- *  This source code is licensed in accordance with the terms specified in
- *  the LICENSE file found in the root directory of this source tree.
- */
-
-#include <ctime>
-
-#include <boost/algorithm/string/trim.hpp>
-
-#include <osquery/utils/system/time.h>
-
-#include <osquery/tables.h>
-
-namespace osquery {
-
-namespace tables {
-
-QueryData genTime(QueryContext& context) {
-  Row r;
-  time_t local_time = getUnixTime();
-  auto osquery_time = getUnixTime();
-  auto osquery_timestamp = getAsciiTime();
-
-  // The concept of 'now' is configurable.
-  struct tm gmt;
-  gmtime_r(&local_time, &gmt);
-
-  struct tm now;
-  localtime_r(&local_time, &now);
-
-  struct tm local;
-  localtime_r(&local_time, &local);
-  local_time = std::mktime(&local);
-
-  char weekday[10] = {0};
-  strftime(weekday, sizeof(weekday), "%A", &now);
-
-  char timezone[5] = {0};
-  strftime(timezone, sizeof(timezone), "%Z", &now);
-
-  char local_timezone[5] = {0};
-  strftime(local_timezone, sizeof(local_timezone), "%Z", &local);
-
-  char iso_8601[21] = {0};
-  strftime(iso_8601, sizeof(iso_8601), "%FT%TZ", &gmt);
-#ifdef WIN32
-  if (context.isColumnUsed("win_timestamp")) {
-    FILETIME ft = {0};
-    GetSystemTimeAsFileTime(&ft);
-    LARGE_INTEGER li = {0};
-    li.LowPart = ft.dwLowDateTime;
-    li.HighPart = ft.dwHighDateTime;
-    long long int hns = li.QuadPart;
-    r["win_timestamp"] = BIGINT(hns);
-  }
-#endif
-  r["weekday"] = SQL_TEXT(weekday);
-  r["year"] = INTEGER(now.tm_year + 1900);
-  r["month"] = INTEGER(now.tm_mon + 1);
-  r["day"] = INTEGER(now.tm_mday);
-  r["hour"] = INTEGER(now.tm_hour);
-  r["minutes"] = INTEGER(now.tm_min);
-  r["seconds"] = INTEGER(now.tm_sec);
-  r["timezone"] = SQL_TEXT(timezone);
-  if (r["timezone"].empty()) {
-    r["timezone"] = "UTC";
-  }
-
-  r["local_time"] = INTEGER(local_time);
-  r["local_timezone"] = SQL_TEXT(local_timezone);
-  if (r["local_timezone"].empty()) {
-    r["local_timezone"] = "UTC";
-  }
-
-  r["unix_time"] = INTEGER(osquery_time);
-  r["timestamp"] = SQL_TEXT(osquery_timestamp);
-  // Date time is provided in ISO 8601 format, then duplicated in iso_8601.
-  r["datetime"] = SQL_TEXT(iso_8601);
-  r["iso_8601"] = SQL_TEXT(iso_8601);
-
-  QueryData results;
-  results.push_back(r);
-  return results;
-}
-} // namespace tables
-} // namespace osquery
index 3f8619790e5052b5d51b54dc1b272c4cc8bf19f2..ec7a5a1c42cfeb63c405a339f5096cab320ba0d2 100644 (file)
@@ -26,7 +26,7 @@ IF(DEFINED GBS_BUILD)
                                   gflags
                                   libsystemd-daemon)
        PKG_CHECK_MODULES(VIST_COMMON_DEPS REQUIRED ${DEPENDENCY})
-       INCLUDE_DIRECTORIES(${VIST_COMMON_DEPS_INCLUDE_DIRS})
+       INCLUDE_DIRECTORIES(SYSTEM ${VIST_COMMON_DEPS_INCLUDE_DIRS})
        ADD_DEFINITIONS(-DTIZEN="TIZEN")
 ENDIF(DEFINED GBS_BUILD)
 
@@ -62,8 +62,9 @@ ADD_SUBDIRECTORY(policy)
 ADD_SUBDIRECTORY(client)
 
 # service
-ADD_SUBDIRECTORY(service)
 ADD_SUBDIRECTORY(notification)
+ADD_SUBDIRECTORY(service)
+ADD_SUBDIRECTORY(table)
 
 ADD_LIBRARY(${TARGET_VIST_COMMON_LIB} STATIC ${${TARGET_VIST_COMMON_LIB}_SRCS})
 
diff --git a/src/vist/client/schema/bluetooth.hpp b/src/vist/client/schema/bluetooth.hpp
deleted file mode 100644 (file)
index c7fda17..0000000
+++ /dev/null
@@ -1,42 +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
- */
-
-#pragma once
-
-#include <vist/query-builder.hpp>
-
-namespace vist {
-namespace schema {
-
-       struct Bluetooth {
-               int state;
-               int desktopConnectivity;
-               int pairing;
-               int tethering; 
-
-               DECLARE_COLUMN(State, "state", &Bluetooth::state);
-               DECLARE_COLUMN(DesktopConnectivity, "desktopConnectivity", &Bluetooth::desktopConnectivity);
-               DECLARE_COLUMN(Pairing, "pairing", &Bluetooth::pairing);
-               DECLARE_COLUMN(Tethering, "tethering", &Bluetooth::tethering);
-       };
-
-       DECLARE_TABLE(BluetoothTable, "bluetooth", Bluetooth::State,
-                                                                                          Bluetooth::DesktopConnectivity,
-                                                                                          Bluetooth::Pairing,
-                                                                                          Bluetooth::Tethering);
-
-} // namesapce schema
-} // namesapce vist
diff --git a/src/vist/client/schema/policy.hpp b/src/vist/client/schema/policy.hpp
deleted file mode 100644 (file)
index 92eb521..0000000
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- *  Copyright (c) 2019 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 <string>
-
-namespace vist {
-namespace schema {
-
-template <typename T>
-struct Policy {
-       std::string     name;
-       T value;
-};
-
-} // namesapce schema
-} // namesapce vist
diff --git a/src/vist/client/schema/time.hpp b/src/vist/client/schema/time.hpp
deleted file mode 100644 (file)
index 18a655d..0000000
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- *  Copyright (c) 2019 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
-
-namespace vist {
-namespace schema {
-
-struct Time {
-       int hour;
-       int minutes;
-       int seconds;
-};
-
-} // namesapce schema
-} // namesapce vist
index 27814ffc24d7c8883c5d0ba6e28aad7a81fcc13a..03fc974c8af983261a79836d9bf28b205687421f 100644 (file)
 #include <gtest/gtest.h>
 
 #include <vist/client/virtual-table.hpp>
-
-#include <vist/client/schema/policy.hpp>
-#include <vist/client/schema/time.hpp>
-
 #include <vist/logger.hpp>
+#include <vist/schema/policy.hpp>
 
 using namespace vist;
 using namespace vist::schema;
 
 class VirtualTableTests : public testing::Test {};
 
-TEST(VirtualTableTests, time_row_at)
-{
-       Time result = { -1, -1, -1 };
-
-       VirtualRow<Time> time;
-       result.hour = time.at(&Time::hour);
-       result.minutes = time.at(&Time::minutes);
-       result.seconds = time.at(&Time::seconds);
-
-       /// Once query execution
-       INFO(VIST_CLIENT) << "[Test] time table:";
-       INFO(VIST_CLIENT) << "\t hour: " << result.hour;
-       INFO(VIST_CLIENT) << "\t minutes: " << result.minutes;
-       INFO(VIST_CLIENT) << "\t seconds: " << result.seconds;
-
-       /// Each query execution
-       INFO(VIST_CLIENT) << "[Test] time table:";
-       INFO(VIST_CLIENT) << "\t hour: " << VirtualRow<Time>().at(&Time::hour);
-       INFO(VIST_CLIENT) << "\t minutes: " << VirtualRow<Time>().at(&Time::minutes);
-       INFO(VIST_CLIENT) << "\t seconds: " <<  VirtualRow<Time>().at(&Time::seconds);
-
-       EXPECT_NE(result.hour, -1);
-       EXPECT_NE(result.minutes, -1);
-       EXPECT_NE(result.seconds, -1);
-}
-
-TEST(VirtualTableTests, time_row_arry_op)
-{
-       Time result = { -1, -1, -1 };
-
-       VirtualRow<Time> time;
-       result.hour = time[&Time::hour];
-       result.minutes = time[&Time::minutes];
-       result.seconds = time[&Time::seconds];
-
-       /// Once query execution
-       INFO(VIST_CLIENT) << "[Test] time table:";
-       INFO(VIST_CLIENT) << "\t hour: " << result.hour;
-       INFO(VIST_CLIENT) << "\t minutes: " << result.minutes;
-       INFO(VIST_CLIENT) << "\t seconds: " << result.seconds;
-
-       EXPECT_NE(result.hour, -1);
-       EXPECT_NE(result.minutes, -1);
-       EXPECT_NE(result.seconds, -1);
-}
-
 TEST(VirtualTableTests, policy_int_table)
 {
        VirtualTable<Policy<int>> table;
index 2da7c73cccf7fc5074147bc7969ac66ba9e89422..02c58e789380739f37be6f4c5160bd7b34fa0aa0 100644 (file)
 #include "virtual-table.hpp"
 
 #include <vist/client/query.hpp>
-#include <vist/client/schema/policy.hpp>
-#include <vist/client/schema/time.hpp>
-
 #include <vist/exception.hpp>
-#include <vist/stringfy.hpp>
 #include <vist/logger.hpp>
 #include <vist/query-builder.hpp>
+#include <vist/schema/policy.hpp>
+#include <vist/stringfy.hpp>
 
 #include <boost/lexical_cast.hpp>
 
@@ -32,17 +30,13 @@ namespace {
 using namespace vist::tsqb;
 using namespace vist::schema;
 
-Table time { "time", Column("hour", &Time::hour),
-                                        Column("minutes", &Time::minutes),
-                                        Column("seconds", &Time::seconds) };
-
 Table policyInt { "policy", Column("name", &Policy<int>::name),
                                                        Column("value", &Policy<int>::value) };
 
 Table policyStr { "policy", Column("name", &Policy<std::string>::name),
                                                        Column("value", &Policy<std::string>::value) };
 
-Database metaDB { "db", time, policyInt, policyStr };
+Database metaDB { "db", policyInt, policyStr };
 
 } // anonymous namespace
 
@@ -119,12 +113,6 @@ VirtualTable<T>::VirtualTable()
        }
 }
 
-/// Explicit instantiation
-template class VirtualTable<Time>;
-template class VirtualRow<Time>;
-template int VirtualRow<Time>::at(int Time::*) const;
-template int VirtualRow<Time>::operator[](int Time::*) const;
-
 template class VirtualTable<Policy<int>>;
 template class VirtualRow<Policy<int>>;
 /// name column
diff --git a/src/vist/schema/bluetooth.hpp b/src/vist/schema/bluetooth.hpp
new file mode 100644 (file)
index 0000000..c7fda17
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ *  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/query-builder.hpp>
+
+namespace vist {
+namespace schema {
+
+       struct Bluetooth {
+               int state;
+               int desktopConnectivity;
+               int pairing;
+               int tethering; 
+
+               DECLARE_COLUMN(State, "state", &Bluetooth::state);
+               DECLARE_COLUMN(DesktopConnectivity, "desktopConnectivity", &Bluetooth::desktopConnectivity);
+               DECLARE_COLUMN(Pairing, "pairing", &Bluetooth::pairing);
+               DECLARE_COLUMN(Tethering, "tethering", &Bluetooth::tethering);
+       };
+
+       DECLARE_TABLE(BluetoothTable, "bluetooth", Bluetooth::State,
+                                                                                          Bluetooth::DesktopConnectivity,
+                                                                                          Bluetooth::Pairing,
+                                                                                          Bluetooth::Tethering);
+
+} // namesapce schema
+} // namesapce vist
diff --git a/src/vist/schema/policy.hpp b/src/vist/schema/policy.hpp
new file mode 100644 (file)
index 0000000..92eb521
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ *  Copyright (c) 2019 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 <string>
+
+namespace vist {
+namespace schema {
+
+template <typename T>
+struct Policy {
+       std::string     name;
+       T value;
+};
+
+} // namesapce schema
+} // namesapce vist
index 882d9f8164d39a1d959e5fbca8297e2f22223773..afe25c951a2f665fe466f78aa03c52a50d6e26b3 100644 (file)
 #include <vist/policy/policy-manager.hpp>
 #include <vist/rmi/gateway.hpp>
 
+#include <vist/table/bluetooth.hpp>
+#include <vist/table/policy-admin.hpp>
+#include <vist/table/policy.hpp>
+
 #include <osquery/registry_interface.h>
 #include <osquery/sql.h>
 
@@ -33,6 +37,10 @@ namespace vist {
 Vistd::Vistd()
 {
        osquery::registryAndPluginInit();
+
+       table::BluetoothTable::Init();
+       table::PolicyAdminTable::Init();
+       table::PolicyTable::Init();
 }
 
 void Vistd::start()
diff --git a/src/vist/table/CMakeLists.txt b/src/vist/table/CMakeLists.txt
new file mode 100644 (file)
index 0000000..77e5f50
--- /dev/null
@@ -0,0 +1,17 @@
+#  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
+
+ADD_VIST_LIBRARY(vist_table bluetooth.cpp
+                                                       policy-admin.cpp
+                                                       policy.cpp)
diff --git a/src/vist/table/bluetooth.cpp b/src/vist/table/bluetooth.cpp
new file mode 100644 (file)
index 0000000..5cfcf3a
--- /dev/null
@@ -0,0 +1,123 @@
+/*
+ *  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 "bluetooth.hpp"
+
+#include <vist/exception.hpp>
+#include <vist/logger.hpp>
+#include <vist/policy/api.hpp>
+
+#include <osquery/registry.h>
+#include <osquery/sql/dynamic_table_row.h>
+
+#include <memory>
+#include <stdexcept>
+#include <string>
+
+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()
+{
+       auto tables = RegistryFactory::get().registry("table");
+       tables->add("bluetooth", std::make_shared<BluetoothTable>());
+}
+
+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.";
+
+       QueryData results;
+
+       Row row;
+
+       for (const auto&[schemaName, policyName]: ALIAS) {
+               int value = vist::policy::API::Get(policyName);
+               row[schemaName] = std::to_string(value);
+       }
+
+       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_value_array") == 0)
+               throw std::runtime_error("Wrong request format. Not found json value.");
+
+       std::string str = request.at("json_value_array");
+       rapidjson::Document document;
+       document.Parse(str.c_str());
+       if (document.HasParseError() || !document.IsArray())
+               throw std::runtime_error("Cannot parse request.");
+
+       if (document.Size() != 4)
+               throw std::runtime_error("Wrong request format.");
+
+       /// TODO(Sangwan): Sync vtab schema with policy definition
+       setPolicy("bluetooth", document[0].GetInt());
+       setPolicy("bluetooth-desktop-connectivity", document[1].GetInt());
+       setPolicy("bluetooth-pairing", document[2].GetInt());
+       setPolicy("bluetooth-tethering", document[3].GetInt());
+
+       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/bluetooth.hpp b/src/vist/table/bluetooth.hpp
new file mode 100644 (file)
index 0000000..883468a
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ *  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 <osquery/tables.h>
+
+namespace vist {
+namespace table {
+
+using namespace osquery;
+
+class BluetoothTable final : public TablePlugin {
+public:
+       static 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-admin.cpp b/src/vist/table/policy-admin.cpp
new file mode 100644 (file)
index 0000000..5dc7786
--- /dev/null
@@ -0,0 +1,199 @@
+/*
+ *  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-admin.hpp"
+
+#include <vist/exception.hpp>
+#include <vist/logger.hpp>
+#include <vist/policy/api.hpp>
+
+#include <osquery/registry.h>
+#include <osquery/sql/dynamic_table_row.h>
+
+#include <memory>
+#include <stdexcept>
+#include <string>
+
+namespace vist {
+namespace table {
+
+namespace {
+
+std::string getValue(std::string&& alias, const std::string& key)
+{
+       auto pos = alias.find(";");
+       auto token = alias.substr(0, pos);
+
+       if (token == key)
+               return alias.erase(0, pos + 1);
+       else
+               return std::string();
+}
+
+std::string parseAdmin(const std::string& request, bool insert = true)
+{
+       rapidjson::Document document;
+       document.Parse(request.c_str());
+       if (document.HasParseError() || !document.IsArray())
+               throw std::runtime_error("Cannot parse request.");
+
+       if (insert)
+               return std::string(document[0].GetString());
+       else
+               return getValue(document[0].GetString(), "name");
+}
+
+} // anonymous namespace
+
+void PolicyAdminTable::Init()
+{
+       auto tables = RegistryFactory::get().registry("table");
+       tables->add("policy_admin", std::make_shared<PolicyAdminTable>());
+}
+
+TableColumns PolicyAdminTable::columns() const
+{
+       return {
+               std::make_tuple("name", TEXT_TYPE, ColumnOptions::DEFAULT),
+               std::make_tuple("activated", INTEGER_TYPE, ColumnOptions::DEFAULT),
+       };
+}
+
+TableRows PolicyAdminTable::generate(QueryContext& context) try
+{
+       INFO(VIST) << "Select query about policy-admin table.";
+
+       QueryData results;
+       auto admins = vist::policy::API::Admin::GetAll();
+
+       for (auto& admin : admins) {
+               if (context.constraints["name"].exists(EQUALS)) { /// where clause
+                       auto names = context.constraints["name"].getAll(EQUALS);
+                       for (const auto& name : names) {
+                               if (name == admin.first) {
+                                       Row row;
+                                       row["name"] = admin.first;
+                                       row["activated"] = std::to_string(admin.second);
+
+                                       DEBUG(VIST) << "Admin info [name]: " << row["name"]
+                                                               << ", [activated]:" << row["activated"];
+
+                                       results.emplace_back(std::move(row));
+                               }
+                       }
+               } else { /// select *;
+                       Row row;
+                       row["name"] = admin.first;
+                       row["activated"] = std::to_string(admin.second);
+
+                       DEBUG(VIST) << "Admin info [name]: " << row["name"]
+                                               << ", [activated]:" << row["activated"];
+                       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 PolicyAdminTable::insert(QueryContext&, const PluginRequest& request) try
+{
+       INFO(VIST) << "Insert query about policy-admin table.";
+       if (request.count("json_value_array") == 0)
+               throw std::runtime_error("Wrong request format. Not found json value.");
+
+       auto admin = parseAdmin(request.at("json_value_array"));
+       DEBUG(VIST) << "Admin info [name]: " << admin;
+       vist::policy::API::Admin::Enroll(admin);
+
+       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 };
+}
+
+QueryData PolicyAdminTable::delete_(QueryContext&, const PluginRequest& request) try
+{
+       INFO(VIST) << "Delete query about policy-admin table.";
+       if (request.count("json_value_array") == 0)
+               throw std::runtime_error("Wrong request format. Not found json value.");
+
+       auto admin = parseAdmin(request.at("json_value_array"), false);
+       DEBUG(VIST) << "Admin info [name]: " << admin;
+       vist::policy::API::Admin::Disenroll(admin);
+
+       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 };
+}
+
+QueryData PolicyAdminTable::update(QueryContext&, const PluginRequest& request) try
+{
+       INFO(VIST) << "Update query about policy-admin table.";
+       if (request.count("json_value_array") == 0)
+               throw std::runtime_error("Wrong request format. Not found json value.");
+
+       std::string str = request.at("json_value_array");
+       rapidjson::Document document;
+       document.Parse(str.c_str());
+       if (document.HasParseError() || !document.IsArray())
+               throw std::runtime_error("Cannot parse request.");
+
+       if (document.Size() != 2)
+               throw std::runtime_error("Wrong request format.");
+
+       std::string name = document[0].GetString();
+       int activated = document[1].GetInt();
+
+       vist::policy::API::Admin::Activate(name, activated);
+
+       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 tables
+} // namespace osquery
diff --git a/src/vist/table/policy-admin.hpp b/src/vist/table/policy-admin.hpp
new file mode 100644 (file)
index 0000000..d8a8a7e
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ *  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 <osquery/tables.h>
+
+namespace vist {
+namespace table {
+
+using namespace osquery;
+
+class PolicyAdminTable final : public TablePlugin {
+public:
+       static void Init();
+
+private:
+       TableColumns columns() const override;
+       TableRows generate(QueryContext&) override;
+       QueryData delete_(QueryContext&, const PluginRequest& request) override;
+       QueryData insert(QueryContext&, const PluginRequest& request) override;
+       QueryData update(QueryContext&, const PluginRequest& request) override;
+};
+
+} // namespace table
+} // namespace vist
diff --git a/src/vist/table/policy.cpp b/src/vist/table/policy.cpp
new file mode 100644 (file)
index 0000000..1d4fb2b
--- /dev/null
@@ -0,0 +1,127 @@
+/*
+ *  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/exception.hpp>
+#include <vist/logger.hpp>
+#include <vist/policy/api.hpp>
+
+#include <osquery/registry.h>
+#include <osquery/sql/dynamic_table_row.h>
+
+#include <memory>
+#include <stdexcept>
+#include <string>
+
+namespace vist {
+namespace table {
+
+namespace {
+
+Row convert(const std::string& name, const vist::policy::PolicyValue& value)
+{
+       Row r;
+       r["name"] = name;
+       r["value"] = value.dump();
+
+       return r;
+}
+
+} // anonymous namespace
+
+void PolicyTable::Init()
+{
+       auto tables = RegistryFactory::get().registry("table");
+       tables->add("policy", std::make_shared<PolicyTable>());
+}
+
+TableColumns PolicyTable::columns() const
+{
+       return {
+               std::make_tuple("name", TEXT_TYPE, ColumnOptions::DEFAULT),
+               std::make_tuple("value", TEXT_TYPE, ColumnOptions::DEFAULT),
+       };
+}
+
+TableRows PolicyTable::generate(QueryContext& context) try
+{
+       INFO(VIST) << "Select query about policy table.";
+
+       QueryData results;
+       if (context.constraints["name"].exists(EQUALS)) { /// where clause
+               auto names = context.constraints["name"].getAll(EQUALS);
+               for (const auto& name : names) {
+                       auto value = vist::policy::API::Get(name);
+                       auto row = convert(name, value);
+
+                       results.emplace_back(std::move(row));
+               }
+       } else { /// select *;
+               auto policies = vist::policy::API::GetAll();
+               for (auto& policy : policies) {
+                       auto row = convert(policy.first, policy.second);
+
+                       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 PolicyTable::update(QueryContext&, const PluginRequest& request) try
+{
+       INFO(VIST) << "Update query about policy table.";
+       if (request.count("json_value_array") == 0)
+               throw std::runtime_error("Wrong request format. Not found json value.");
+
+       std::string str = request.at("json_value_array");
+       rapidjson::Document document;
+       document.Parse(str.c_str());
+       if (document.HasParseError() || !document.IsArray())
+               throw std::runtime_error("Cannot parse request.");
+
+       if (document.Size() != 2)
+               throw std::runtime_error("Wrong request format.");
+
+       std::string name = document[0].GetString();
+       std::string dumpedValue = document[1].GetString();
+
+       vist::policy::API::Admin::Set(name, vist::policy::PolicyValue(dumpedValue, true));
+
+       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.hpp b/src/vist/table/policy.hpp
new file mode 100644 (file)
index 0000000..f96c473
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ *  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 <osquery/tables.h>
+
+namespace vist {
+namespace table {
+
+using namespace osquery;
+
+class PolicyTable final : public TablePlugin {
+public:
+       static void Init();
+
+private:
+       TableColumns columns() const override;
+       TableRows generate(QueryContext&) override;
+       QueryData update(QueryContext&, const PluginRequest& request) override;
+};
+
+} // namespace table
+} // namespace vist