Cleanup rapidjson
authorSangwan Kwon <sangwan.kwon@samsung.com>
Mon, 18 May 2020 07:49:49 +0000 (16:49 +0900)
committer권상완/Security 2Lab(SR)/Engineer/삼성전자 <sangwan.kwon@samsung.com>
Wed, 20 May 2020 01:51:37 +0000 (10:51 +0900)
Signed-off-by: Sangwan Kwon <sangwan.kwon@samsung.com>
13 files changed:
src/osquery/sql/dynamic_table_row.cpp
src/osquery/sql/dynamic_table_row.h
src/osquery/sql/tests/sql.cpp
src/osquery/sql/tests/sql_test_utils.cpp
src/osquery/sql/tests/sql_test_utils.h
src/osquery/sql/virtual_table.cpp
src/osquery/utils/CMakeLists.txt
src/osquery/utils/json/json.cpp [deleted file]
src/osquery/utils/json/json.h [deleted file]
src/osquery/utils/json/tests/json.cpp [deleted file]
src/vist/table/bluetooth.cpp
src/vist/table/policy-admin.cpp
src/vist/table/policy.cpp

index 4ee27e1..c5285c8 100644 (file)
@@ -12,8 +12,6 @@
 #include <vist/logger.hpp>
 #include <osquery/utils/conversions/tryto.h>
 
-namespace rj = rapidjson;
-
 namespace osquery {
 
 TableRows tableRowsFromQueryData(QueryData&& rows) {
index a0d48b5..7da1493 100644 (file)
@@ -10,7 +10,6 @@
 
 #include <osquery/core/sql/query_data.h>
 #include <osquery/core/sql/table_row.h>
-#include <osquery/utils/json/json.h>
 
 namespace osquery {
 
index 4e32a2a..3438580 100644 (file)
@@ -13,7 +13,6 @@
 #include <osquery/registry.h>
 #include <osquery/sql.h>
 #include <osquery/sql/dynamic_table_row.h>
-#include <osquery/sql/tests/sql_test_utils.h>
 #include <osquery/tables.h>
 
 namespace osquery {
index 35ad89a..e48adea 100644 (file)
@@ -80,108 +80,4 @@ ColumnNames getSerializedRowColumnNames(bool unordered_and_repeated) {
   return cn;
 }
 
-std::pair<JSON, RowTyped> getSerializedRow(bool unordered_and_repeated) {
-  auto cns = getSerializedRowColumnNames(unordered_and_repeated);
-
-  RowTyped r;
-  auto doc = JSON::newObject();
-  for (const auto& cn : cns) {
-    auto c_value = cn + "_value";
-    r[cn] = c_value;
-    doc.addCopy(cn, c_value);
-  }
-  return std::make_pair(std::move(doc), r);
-}
-
-std::pair<JSON, QueryDataTyped> getSerializedQueryData() {
-  auto r = getSerializedRow(false);
-  QueryDataTyped q = {r.second, r.second};
-
-  JSON doc = JSON::newArray();
-  auto arr1 = doc.getArray();
-  doc.copyFrom(r.first.doc(), arr1);
-  doc.push(arr1);
-
-  auto arr2 = doc.getArray();
-  doc.copyFrom(r.first.doc(), arr2);
-  doc.push(arr2);
-
-  return std::make_pair(std::move(doc), q);
-}
-
-std::pair<std::string, QueryDataTyped> getSerializedQueryDataJSON() {
-  auto results = getSerializedQueryData();
-  std::string output;
-  results.first.toString(output);
-  return std::make_pair(output, results.second);
-}
-
-std::pair<JSON, DiffResults> getSerializedDiffResults() {
-  auto qd = getSerializedQueryData();
-  DiffResults diff_results;
-  diff_results.added = qd.second;
-  diff_results.removed = qd.second;
-
-  JSON doc = JSON::newObject();
-  doc.add("removed", qd.first.doc());
-  doc.add("added", qd.first.doc());
-
-  return std::make_pair(std::move(doc), std::move(diff_results));
-}
-
-std::pair<JSON, QueryLogItem> getSerializedQueryLogItem() {
-  std::pair<JSON, QueryLogItem> p;
-  QueryLogItem i;
-  JSON doc = JSON::newObject();
-  auto dr = getSerializedDiffResults();
-  i.results = std::move(dr.second);
-  i.name = "foobar";
-  i.calendar_time = "Mon Aug 25 12:10:57 2014";
-  i.time = 1408993857;
-  i.identifier = "foobaz";
-  i.epoch = 0LL;
-  i.counter = 0LL;
-
-  auto diff_doc = doc.getObject();
-  diff_doc.Swap(dr.first.doc());
-  doc.add("diffResults", diff_doc);
-  doc.addRef("name", "foobar");
-  doc.addRef("hostIdentifier", "foobaz");
-  doc.addRef("calendarTime", "Mon Aug 25 12:10:57 2014");
-  doc.add("unixTime", 1408993857);
-  doc.add("epoch", std::size_t{0});
-  doc.add("counter", std::size_t{0});
-
-  return std::make_pair(std::move(doc), std::move(i));
-}
-
-std::pair<JSON, QueryDataTyped> getSerializedQueryDataWithColumnOrder() {
-  auto r = getSerializedRow(true);
-  QueryDataTyped q = {r.second, r.second};
-  JSON doc = JSON::newArray();
-  auto arr1 = doc.getArray();
-  doc.copyFrom(r.first.doc(), arr1);
-  doc.push(arr1);
-
-  auto arr2 = doc.getArray();
-  doc.copyFrom(r.first.doc(), arr2);
-  doc.push(arr2);
-
-  return std::make_pair(std::move(doc), q);
-}
-
-std::pair<std::string, DiffResults> getSerializedDiffResultsJSON() {
-  auto results = getSerializedDiffResults();
-  std::string output;
-  results.first.toString(output);
-  return std::make_pair(output, std::move(results.second));
-}
-
-std::pair<std::string, QueryLogItem> getSerializedQueryLogItemJSON() {
-  auto results = getSerializedQueryLogItem();
-  std::string output;
-  results.first.toString(output);
-  return std::make_pair(output, std::move(results.second));
-}
-
 } // namespace osquery
index 9a93f0a..638f5c1 100644 (file)
@@ -3,7 +3,6 @@
 #include <osquery/registry_interface.h>
 #include <osquery/sql.h>
 #include <osquery/sql/sqlite_util.h>
-#include <osquery/utils/json/json.h>
 
 namespace osquery {
 
@@ -23,30 +22,4 @@ QueryDataTyped getTestDBExpectedResults();
 // vector includes a repeated column name and is in non-alphabetical order
 ColumnNames getSerializedRowColumnNames(bool unordered_and_repeated);
 
-// getSerializedRow() return an std::pair where pair->first is a string which
-// should serialize to pair->second. pair->second should deserialize
-// to pair->first
-std::pair<JSON, RowTyped> getSerializedRow(bool unordered_and_repeated = false);
-
-// getSerializedQueryData() return an std::pair where pair->first is a string
-// which should serialize to pair->second. pair->second should
-// deserialize to pair->first. getSerializedQueryDataWithColumnOrder
-// returns a pair where pair->second is a tree that has a repeated column and
-// the child nodes are not in alphabetical order
-std::pair<JSON, QueryDataTyped> getSerializedQueryData();
-std::pair<JSON, QueryDataTyped> getSerializedQueryDataWithColumnOrder();
-std::pair<std::string, QueryDataTyped> getSerializedQueryDataJSON();
-
-// getSerializedDiffResults() return an std::pair where pair->first is a string
-// which should serialize to pair->second. pair->second should
-// deserialize to pair->first
-std::pair<JSON, DiffResults> getSerializedDiffResults();
-std::pair<std::string, DiffResults> getSerializedDiffResultsJSON();
-
-// getSerializedQueryLogItem() return an std::pair where pair->first
-// is a string which should serialize to pair->second. pair->second
-// should deserialize to pair->first
-std::pair<JSON, QueryLogItem> getSerializedQueryLogItem();
-std::pair<std::string, QueryLogItem> getSerializedQueryLogItemJSON();
-
 } // namespace osquery
index 6fc42bf..ecf0252 100644 (file)
@@ -9,14 +9,16 @@
 #include <atomic>
 #include <unordered_set>
 
-#include <osquery/core.h>
+#include <vist/json.hpp>
 #include <vist/logger.hpp>
+
+#include <osquery/core.h>
 #include <osquery/registry_factory.h>
 #include <osquery/sql/dynamic_table_row.h>
 #include <osquery/sql/virtual_table.h>
 #include <osquery/utils/conversions/tryto.h>
 
-#include <vist/logger.hpp>
+using namespace vist;
 
 namespace osquery {
 
@@ -114,18 +116,14 @@ bool getColumnValue(std::string& value,
 }
 
 /// PATCH START //////////////////////////////////////////////////////////////
-int serializeDeleteParameters(std::string& json_value_array,
-                                                         VirtualTable* pVtab) {
+int serializeDeleteParameters(std::string& serialized, VirtualTable* pVtab) {
        auto content = pVtab->content;
        if (content->constraints.size() <= 0) {
                ERROR(OSQUERY) << "Invalid constraints arguments";
                return SQLITE_ERROR;
        }
 
-       auto document = rapidjson::Document();
-       document.SetArray();
-       auto& allocator = document.GetAllocator();
-
+       json::Array values;
        for (std::size_t i = 0; i < content->constraints.size(); i++) {
                for (auto& constraint : content->constraints[i]) {
                        auto key = constraint.first;
@@ -133,127 +131,110 @@ int serializeDeleteParameters(std::string& json_value_array,
 
                        if (!value.empty()) {
                                /// Since concrete table is not able to know the key, make alias.
-                               rapidjson::Value jsonValue((key + ";" + value).c_str(), allocator);
-                               document.PushBack(jsonValue, allocator);
+                               values.push(key + ";" + value);
                        }
                }
        }
 
-       rapidjson::StringBuffer buffer;
-       buffer.Clear();
+       json::Json document;
+       document.push("values", values);
 
-       rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
-       document.Accept(writer);
-
-       json_value_array = buffer.GetString();
+       serialized = document.serialize();
+       DEBUG(VIST) << "Serialized sql parameters: " << serialized;
 
        return SQLITE_OK;
 }
-/// PATCH END /////////////////////////////////////////////////////////////////
 
 // Type-aware serializer to pass parameters between osquery and the extension
-int serializeUpdateParameters(std::string& json_value_array,
-                              size_t argc,
-                              sqlite3_value** argv,
-                              const TableColumns& columnDescriptors) {
-  if (columnDescriptors.size() != argc - 2U) {
-    DEBUG(OSQUERY) << "Wrong column count: " << argc - 2U
-            << ". Expected: " << columnDescriptors.size();
-    return SQLITE_RANGE;
-  }
-
-  auto document = rapidjson::Document();
-  document.SetArray();
+int serializeUpdateParameters(std::string& serialized,
+                                                         size_t argc,
+                                                         sqlite3_value** argv,
+                                                         const TableColumns& columnDescriptors) {
+       if (columnDescriptors.size() != argc - 2U) {
+               DEBUG(VIST) << "Wrong column count: " << argc - 2U
+                                       << ". Expected: " << columnDescriptors.size();
+               return SQLITE_RANGE;
+       }
 
-  auto& allocator = document.GetAllocator();
+       json::Array values;
 
-  for (size_t i = 2U; i < argc; i++) {
-    auto sqlite_value = argv[i];
+       for (size_t i = 2U; i < argc; i++) {
+               auto sqlite_value = argv[i];
 
-    const auto& columnDescriptor = columnDescriptors[i - 2U];
-    const auto& columnType = std::get<1>(columnDescriptor);
+               const auto& columnDescriptor = columnDescriptors[i - 2U];
+               const auto& columnType = std::get<1>(columnDescriptor);
 
-    const auto& columnOptions = std::get<2>(columnDescriptor);
-    bool requiredColumn = (columnOptions == ColumnOptions::INDEX ||
-                           columnOptions == ColumnOptions::REQUIRED);
+               const auto& columnOptions = std::get<2>(columnDescriptor);
+               bool requiredColumn = (columnOptions == ColumnOptions::INDEX ||
+                                                          columnOptions == ColumnOptions::REQUIRED);
 
-    auto receivedValueType = sqlite3_value_type(sqlite_value);
-    switch (receivedValueType) {
-    case SQLITE_INTEGER: {
-      if (columnType != INTEGER_TYPE && columnType != BIGINT_TYPE &&
-          columnType != UNSIGNED_BIGINT_TYPE) {
-        return SQLITE_MISMATCH;
-      }
-
-      auto integer =
-          static_cast<std::int64_t>(sqlite3_value_int64(sqlite_value));
+               auto receivedValueType = sqlite3_value_type(sqlite_value);
+               switch (receivedValueType) {
+               case SQLITE_INTEGER: {
+                       if (columnType != INTEGER_TYPE && columnType != BIGINT_TYPE &&
+                                       columnType != UNSIGNED_BIGINT_TYPE) {
+                               return SQLITE_MISMATCH;
+                       }
 
-      document.PushBack(integer, allocator);
-      break;
-    }
+                       auto integer = static_cast<int>(sqlite3_value_int64(sqlite_value));
+                       values.push(integer);
+                       break;
+               }
 
-    case SQLITE_FLOAT: {
-      if (columnType != DOUBLE_TYPE) {
-        return SQLITE_MISMATCH;
-      }
+               case SQLITE_FLOAT: {
+                       if (columnType != DOUBLE_TYPE)
+                               return SQLITE_MISMATCH;
 
-      document.PushBack(sqlite3_value_double(sqlite_value), allocator);
-      break;
-    }
+                       values.push(sqlite3_value_double(sqlite_value));
+                       break;
+               }
 
-    case SQLITE_BLOB:
-    case SQLITE3_TEXT: {
-      bool typeMismatch = false;
-      if (receivedValueType == SQLITE_BLOB) {
-        typeMismatch = columnType != BLOB_TYPE;
-      } else {
-        typeMismatch = columnType != TEXT_TYPE;
-      }
+               case SQLITE_BLOB:
+               case SQLITE3_TEXT: {
+                       bool typeMismatch = false;
+                       if (receivedValueType == SQLITE_BLOB)
+                               typeMismatch = columnType != BLOB_TYPE;
+                       else
+                               typeMismatch = columnType != TEXT_TYPE;
 
-      if (typeMismatch) {
-        return SQLITE_MISMATCH;
-      }
+                       if (typeMismatch) 
+                               return SQLITE_MISMATCH;
 
-      auto data_pointer = sqlite3_value_blob(sqlite_value);
-      auto buffer_size = sqlite3_value_bytes(sqlite_value);
+                       auto data_pointer = sqlite3_value_blob(sqlite_value);
+                       auto buffer_size = sqlite3_value_bytes(sqlite_value);
 
-      std::string string_data;
-      string_data.resize(buffer_size);
-      std::memcpy(&string_data[0], data_pointer, buffer_size);
+                       std::string string_data;
+                       string_data.resize(buffer_size);
+                       std::memcpy(&string_data[0], data_pointer, buffer_size);
 
-      rapidjson::Value value(string_data.c_str(), allocator);
-      document.PushBack(value, allocator);
+                       values.push(string_data);
 
-      break;
-    }
-
-    case SQLITE_NULL: {
-      if (requiredColumn) {
-        return SQLITE_MISMATCH;
-      }
+                       break;
+               }
 
-      rapidjson::Value value;
-      value.SetNull();
+               case SQLITE_NULL: {
+                       if (requiredColumn)
+                               return SQLITE_MISMATCH;
 
-      document.PushBack(value, allocator);
-      break;
-    }
+                       json::Null null;
+                       values.push(null);
+                       break;
+               }
 
-    default: {
-      ERROR(OSQUERY) << "Invalid column type returned by sqlite";
-      return SQLITE_MISMATCH;
-    }
-    }
-  }
+               default: {
+                       ERROR(OSQUERY) << "Invalid column type returned by sqlite";
+                       return SQLITE_MISMATCH;
+               }
+               }
+       }
 
-  rapidjson::StringBuffer buffer;
-  buffer.Clear();
+       json::Json document;
+       document.push("values", values);
 
-  rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
-  document.Accept(writer);
+       serialized = document.serialize();
+       DEBUG(VIST) << "Serialized sql parameters: " << serialized;
 
-  json_value_array = buffer.GetString();
-  return SQLITE_OK;
+       return SQLITE_OK;
 }
 
 void setTableErrorMessage(sqlite3_vtab* vtable,
@@ -365,10 +346,9 @@ int xUpdate(sqlite3_vtab* p,
     plugin_request.insert({"id", std::to_string(row_to_delete)});
 
 /// PATCH START //////////////////////////////////////////////////////////////
-       std::string json_value_array;
-       /// serialize constraints
-       serializeDeleteParameters(json_value_array, reinterpret_cast<VirtualTable*>(p));
-       plugin_request.insert({"json_value_array", json_value_array});
+       std::string json_values;
+       serializeDeleteParameters(json_values, reinterpret_cast<VirtualTable*>(p));
+       plugin_request.insert({"json_values", json_values});
 /// PATCH END ////////////////////////////////////////////////////////////////
   } else if (sqlite3_value_type(argv[0]) == SQLITE_NULL) {
     // This is an INSERT query; if the rowid has been generated for us, we'll
@@ -378,15 +358,15 @@ int xUpdate(sqlite3_vtab* p,
     // Add the values to insert; we should have a value for each column present
     // in the table, even if the user did not specify a value (in which case
     // we will find a nullptr)
-    std::string json_value_array;
-    auto serializerError = serializeUpdateParameters(
-        json_value_array, argument_count, argv, columnDescriptors);
-    if (serializerError != SQLITE_OK) {
-      DEBUG(OSQUERY) << "Failed to serialize the INSERT request";
-      return serializerError;
-    }
+       std::string json_values;
+       auto serializerError = serializeUpdateParameters(
+               json_values, argument_count, argv, columnDescriptors);
+       if (serializerError != SQLITE_OK) {
+               DEBUG(OSQUERY) << "Failed to serialize the UPDATE request";
+               return serializerError;
+       }
 
-    plugin_request.insert({"json_value_array", json_value_array});
+       plugin_request.insert({"json_values", json_values});
 
     if (sqlite3_value_type(argv[1]) != SQLITE_NULL) {
       plugin_request.insert({"auto_rowid", "true"});
@@ -430,15 +410,15 @@ int xUpdate(sqlite3_vtab* p,
     }
 
     // Get the values to update
-    std::string json_value_array;
-    auto serializerError = serializeUpdateParameters(
-        json_value_array, argument_count, argv, columnDescriptors);
-    if (serializerError != SQLITE_OK) {
-      DEBUG(OSQUERY) << "Failed to serialize the UPDATE request";
-      return serializerError;
-    }
+       std::string json_values;
+       auto serializerError = serializeUpdateParameters(
+               json_values, argument_count, argv, columnDescriptors);
+       if (serializerError != SQLITE_OK) {
+               DEBUG(OSQUERY) << "Failed to serialize the UPDATE request";
+               return serializerError;
+       }
 
-    plugin_request.insert({"json_value_array", json_value_array});
+       plugin_request.insert({"json_values", json_values});
 
   } else {
     DEBUG(OSQUERY) << "Invalid xUpdate call";
index 74a17dd..29c2a69 100644 (file)
@@ -22,8 +22,7 @@ ADD_OSQUERY_LIBRARY(osquery_utils base64.cpp
                                                                  system/posix/filepath.cpp
                                                                  system/posix/time.cpp
                                                                  conversions/tryto.cpp
-                                                                 conversions/split.cpp
-                                                                 json/json.cpp)
+                                                                 conversions/split.cpp)
 
 FILE(GLOB OSQUERY_UTILS_ERROR_TESTS "error/tests/*.cpp")
 ADD_OSQUERY_TEST(${OSQUERY_UTILS_ERROR_TESTS})
@@ -40,9 +39,6 @@ ADD_OSQUERY_TEST(${OSQUERY_UTILS_STATUS_TESTS})
 FILE(GLOB OSQUERY_UTILS_CONVERSION_TESTS "conversions/tests/*.cpp")
 ADD_OSQUERY_TEST(${OSQUERY_UTILS_CONVERSION_TESTS})
 
-FILE(GLOB OSQUERY_UTILS_JSON_TESTS "json/tests/*.cpp")
-ADD_OSQUERY_TEST(${OSQUERY_UTILS_JSON_TESTS})
-
 FILE(GLOB OSQUERY_UTILS_SYSTEM_TESTS "system/tests/*.cpp")
 FILE(GLOB OSQUERY_UTILS_SYSTEM_POSIXE_TESTS "system/posix/tests/*.cpp")
 ADD_OSQUERY_TEST(${OSQUERY_UTILS_SYSTEM_TESTS}
diff --git a/src/osquery/utils/json/json.cpp b/src/osquery/utils/json/json.cpp
deleted file mode 100644 (file)
index 74b50e6..0000000
+++ /dev/null
@@ -1,380 +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.
- */
-/**
- *  Copyright (c) 2019 Samsung Electronics Co., Ltd All Rights Reserved
- *  
- *  @author Sangwan Kwon (sangwan.kwon@samsung.com)
- *  @diff #1 rj::StringRef(std::string) => rj::StringRef(std::string.c_str())
- *        #2 rj::Value::FindMember(std::string) =>
- *           rj::Value::FindMember(std::string.c_str())
- *        #3 rj::ParseResult => rj::ParseErrorCode (line 295)
- */
-
-#include "json.h"
-
-#include <osquery/utils/conversions/tryto.h>
-
-namespace rj = rapidjson;
-
-namespace osquery {
-
-JSON::JSON(rj::Type type) : type_(type) {
-  if (type_ == rj::kObjectType) {
-    doc_.SetObject();
-  } else {
-    doc_.SetArray();
-  }
-}
-
-JSON::JSON() {
-  type_ = rj::kObjectType;
-  doc_.SetObject();
-}
-
-JSON JSON::newObject() {
-  return JSON(rj::kObjectType);
-}
-
-JSON JSON::newArray() {
-  return JSON(rj::kArrayType);
-}
-
-rj::Document JSON::getObject() const {
-  rj::Document line;
-  line.SetObject();
-  return line;
-}
-
-rj::Document JSON::getArray() const {
-  rj::Document line;
-  line.SetArray();
-  return line;
-}
-
-void JSON::push(rj::Value& value) {
-  assert(type_ == rj::kArrayType);
-  push(value, doc());
-}
-
-void JSON::push(rj::Value& value, rj::Value& arr) {
-  arr.PushBack(rj::Value(value, doc_.GetAllocator()).Move(),
-               doc_.GetAllocator());
-}
-
-void JSON::push(size_t value) {
-  push(value, doc());
-}
-
-void JSON::push(size_t value, rj::Value& arr) {
-  arr.PushBack(rj::Value(static_cast<uint64_t>(value)).Move(),
-               doc_.GetAllocator());
-}
-
-void JSON::pushCopy(const std::string& value) {
-  pushCopy(value, doc());
-}
-
-void JSON::pushCopy(const std::string& value, rj::Value& arr) {
-  rj::Value sc;
-  sc.SetString(value.c_str(), value.size(), doc_.GetAllocator());
-  arr.PushBack(sc.Move(), doc_.GetAllocator());
-}
-
-void JSON::add(const std::string& key, const rj::Value& value) {
-  add(key, value, doc());
-}
-
-void JSON::add(const std::string& key, const rj::Value& value, rj::Value& obj) {
-  assert(obj.IsObject());
-  auto itr = obj.FindMember(key.c_str());
-  if (itr != obj.MemberEnd()) {
-    obj.RemoveMember(itr);
-  }
-
-  obj.AddMember(rj::Value(rj::StringRef(key.c_str()), doc_.GetAllocator()).Move(),
-                rj::Value(value, doc_.GetAllocator()).Move(),
-                doc_.GetAllocator());
-}
-
-void JSON::addCopy(const std::string& key,
-                   const std::string& value,
-                   rj::Value& obj) {
-  assert(obj.IsObject());
-  auto itr = obj.FindMember(key.c_str());
-  if (itr != obj.MemberEnd()) {
-    obj.RemoveMember(itr);
-  }
-
-  rj::Value sc;
-  sc.SetString(value.c_str(), value.size(), doc_.GetAllocator());
-  obj.AddMember(rj::Value(rj::StringRef(key.c_str()), doc_.GetAllocator()).Move(),
-                sc.Move(),
-                doc_.GetAllocator());
-}
-
-void JSON::addCopy(const std::string& key, const std::string& value) {
-  addCopy(key, value, doc());
-}
-
-void JSON::addRef(const std::string& key,
-                  const std::string& value,
-                  rj::Value& obj) {
-  assert(obj.IsObject());
-  auto itr = obj.FindMember(key.c_str());
-  if (itr != obj.MemberEnd()) {
-    obj.RemoveMember(itr);
-  }
-
-  obj.AddMember(rj::Value(rj::StringRef(key.c_str()), doc_.GetAllocator()).Move(),
-                rj::Value(rj::StringRef(value.c_str()), doc_.GetAllocator()).Move(),
-                doc_.GetAllocator());
-}
-
-void JSON::addRef(const std::string& key, const std::string& value) {
-  addRef(key, value, doc());
-}
-
-void JSON::add(const std::string& key, const std::string& value) {
-  addCopy(key, value);
-}
-
-void JSON::add(const std::string& key,
-               const std::string& value,
-               rj::Value& obj) {
-  addCopy(key, value, obj);
-}
-
-void JSON::add(const std::string& key, const char* value, rj::Value& obj) {
-  assert(obj.IsObject());
-  auto itr = obj.FindMember(key.c_str());
-  if (itr != obj.MemberEnd()) {
-    obj.RemoveMember(itr);
-  }
-
-  obj.AddMember(rj::Value(rj::StringRef(key.c_str()), doc_.GetAllocator()).Move(),
-                rj::Value(value, strlen(value)).Move(),
-                doc_.GetAllocator());
-}
-void JSON::add(const std::string& key, const char* value) {
-  add(key, value, doc());
-}
-
-void JSON::add(const std::string& key, int value, rj::Value& obj) {
-  assert(obj.IsObject());
-  auto itr = obj.FindMember(key.c_str());
-  if (itr != obj.MemberEnd()) {
-    obj.RemoveMember(itr);
-  }
-
-  obj.AddMember(rj::Value(rj::StringRef(key.c_str()), doc_.GetAllocator()).Move(),
-                rj::Value(static_cast<int64_t>(value)).Move(),
-                doc_.GetAllocator());
-}
-
-void JSON::add(const std::string& key, int value) {
-  add(key, value, doc());
-}
-
-void JSON::add(const std::string& key, long value, rj::Value& obj) {
-  assert(obj.IsObject());
-  auto itr = obj.FindMember(key.c_str());
-  if (itr != obj.MemberEnd()) {
-    obj.RemoveMember(itr);
-  }
-
-  obj.AddMember(rj::Value(rj::StringRef(key.c_str()), doc_.GetAllocator()).Move(),
-                rj::Value(static_cast<int64_t>(value)).Move(),
-                doc_.GetAllocator());
-}
-
-void JSON::add(const std::string& key, long value) {
-  add(key, value, doc());
-}
-
-void JSON::add(const std::string& key, long long value, rj::Value& obj) {
-  assert(obj.IsObject());
-  auto itr = obj.FindMember(key.c_str());
-  if (itr != obj.MemberEnd()) {
-    obj.RemoveMember(itr);
-  }
-  obj.AddMember(rj::Value(rj::StringRef(key.c_str()), doc_.GetAllocator()).Move(),
-                rj::Value(static_cast<int64_t>(value)).Move(),
-                doc_.GetAllocator());
-}
-void JSON::add(const std::string& key, long long value) {
-  add(key, value, doc());
-}
-
-void JSON::add(const std::string& key, unsigned int value, rj::Value& obj) {
-  assert(obj.IsObject());
-  auto itr = obj.FindMember(key.c_str());
-  if (itr != obj.MemberEnd()) {
-    obj.RemoveMember(itr);
-  }
-
-  obj.AddMember(rj::Value(rj::StringRef(key.c_str()), doc_.GetAllocator()).Move(),
-                rj::Value(static_cast<uint64_t>(value)).Move(),
-                doc_.GetAllocator());
-}
-
-void JSON::add(const std::string& key, unsigned int value) {
-  add(key, value, doc());
-}
-
-void JSON::add(const std::string& key, unsigned long value, rj::Value& obj) {
-  assert(obj.IsObject());
-  auto itr = obj.FindMember(key.c_str());
-  if (itr != obj.MemberEnd()) {
-    obj.RemoveMember(itr);
-  }
-
-  obj.AddMember(rj::Value(rj::StringRef(key.c_str()), doc_.GetAllocator()).Move(),
-                rj::Value(static_cast<uint64_t>(value)).Move(),
-                doc_.GetAllocator());
-}
-
-void JSON::add(const std::string& key, unsigned long value) {
-  add(key, value, doc());
-}
-
-void JSON::add(const std::string& key,
-               unsigned long long value,
-               rj::Value& obj) {
-  assert(obj.IsObject());
-  auto itr = obj.FindMember(key.c_str());
-  if (itr != obj.MemberEnd()) {
-    obj.RemoveMember(itr);
-  }
-  obj.AddMember(rj::Value(rj::StringRef(key.c_str()), doc_.GetAllocator()).Move(),
-                rj::Value(static_cast<uint64_t>(value)).Move(),
-                doc_.GetAllocator());
-}
-void JSON::add(const std::string& key, unsigned long long value) {
-  add(key, value, doc());
-}
-void JSON::add(const std::string& key, double value, rj::Value& obj) {
-  assert(obj.IsObject());
-  auto itr = obj.FindMember(key.c_str());
-  if (itr != obj.MemberEnd()) {
-    obj.RemoveMember(itr);
-  }
-  obj.AddMember(rj::Value(rj::StringRef(key.c_str()), doc_.GetAllocator()).Move(),
-                rj::Value(value).Move(),
-                doc_.GetAllocator());
-}
-void JSON::add(const std::string& key, double value) {
-  add(key, value, doc());
-}
-
-void JSON::add(const std::string& key, bool value, rj::Value& obj) {
-  assert(obj.IsObject());
-  auto itr = obj.FindMember(key.c_str());
-  if (itr != obj.MemberEnd()) {
-    obj.RemoveMember(itr);
-  }
-
-  obj.AddMember(rj::Value(rj::StringRef(key.c_str()), doc_.GetAllocator()).Move(),
-                rj::Value(value).Move(),
-                doc_.GetAllocator());
-}
-
-void JSON::add(const std::string& key, bool value) {
-  add(key, value, doc());
-}
-
-Status JSON::toString(std::string& str) const {
-  rj::StringBuffer sb;
-  rj::Writer<rj::StringBuffer> writer(sb);
-  doc_.Accept(writer);
-  str = sb.GetString();
-  return Status::success();
-}
-
-Status JSON::fromString(const std::string& str) {
-  rj::ParseErrorCode ok = doc_.Parse(str.c_str()).GetParseError();
-  if (ok != rj::kParseErrorNone) {
-    std::string message{"Cannot parse JSON: "};
-    message += GetParseError_En(ok);
-    message += " Offset: ";
-    message += std::to_string(doc_.GetErrorOffset());
-    return Status(1, message);
-  }
-  return Status::success();
-}
-
-void JSON::mergeObject(rj::Value& target_obj, rj::Value& source_obj) {
-  assert(target_obj.IsObject());
-  assert(source_obj.IsObject());
-  for (auto itr = source_obj.MemberBegin(); itr != source_obj.MemberEnd();
-       ++itr) {
-    auto titr = target_obj.FindMember(itr->name);
-    if (titr != target_obj.MemberEnd()) {
-      target_obj.RemoveMember(titr);
-    }
-
-    target_obj.AddMember(itr->name, itr->value, doc_.GetAllocator());
-  }
-}
-
-void JSON::mergeArray(rj::Value& target_arr, rj::Value& source_arr) {
-  assert(target_arr.IsArray());
-  assert(source_arr.IsArray());
-  for (auto itr = source_arr.Begin(); itr != source_arr.End(); ++itr) {
-    target_arr.PushBack(*itr, doc_.GetAllocator());
-  }
-}
-
-JSON JSON::newFromValue(const rj::Value& value) {
-  assert(value.IsObject() || value.IsArray());
-
-  JSON doc;
-  doc.type_ = (value.IsArray()) ? rj::kArrayType : rj::kObjectType;
-  doc.copyFrom(value, doc.doc());
-  return doc;
-}
-
-void JSON::copyFrom(const rapidjson::Value& value, rj::Value& target) {
-  target.CopyFrom(value, doc().GetAllocator());
-}
-
-void JSON::copyFrom(const rj::Value& value) {
-  copyFrom(value, doc());
-}
-
-rj::Document& JSON::doc() {
-  return doc_;
-}
-
-const rj::Document& JSON::doc() const {
-  return doc_;
-}
-
-size_t JSON::valueToSize(const rj::Value& value) {
-  if (value.IsString()) {
-    return tryTo<std::size_t>(std::string{value.GetString()}).takeOr(0_sz);
-  } else if (value.IsNumber()) {
-    return static_cast<size_t>(value.GetUint64());
-  }
-  return 0_sz;
-}
-
-bool JSON::valueToBool(const rj::Value& value) {
-  if (value.IsBool()) {
-    return value.GetBool();
-  } else if (value.IsString()) {
-    auto b = std::string(value.GetString());
-    std::transform(b.begin(), b.end(), b.begin(), ::tolower);
-
-    return (b == "true" || b == "t");
-  } else if (value.IsNumber()) {
-    return (value.GetInt() != 0);
-  }
-  return false;
-}
-
-}
diff --git a/src/osquery/utils/json/json.h b/src/osquery/utils/json/json.h
deleted file mode 100644 (file)
index 38847da..0000000
+++ /dev/null
@@ -1,364 +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.
- */
-
-#pragma once
-
-#include <cstddef>
-
-#include <osquery/utils/only_movable.h>
-#include <osquery/utils/status/status.h>
-
-#ifdef WIN32
-#pragma warning(push, 3)
-#pragma warning(disable : 4715)
-#endif
-
-#include <rapidjson/document.h>
-#include <rapidjson/error/en.h>
-#include <rapidjson/stringbuffer.h>
-#include <rapidjson/writer.h>
-
-#ifdef WIN32
-#pragma warning(pop)
-#endif
-
-namespace osquery {
-/**
- * @brief This provides a small wrapper around constructing JSON objects.
- *
- * Constructing RapidJSON objects can be slightly tricky. In our original
- * refactoring we found several opportunities to leak memory and cause faults.
- * This was mostly causes by setting allocators incorrectly.
- */
-class JSON : private only_movable {
- private:
-  explicit JSON(rapidjson::Type type);
-
- public:
-  JSON();
-  JSON(JSON&&) = default;
-  JSON& operator=(JSON&&) = default;
-
-  /// Create a JSON wrapper for an Object (map).
-  static JSON newObject();
-
-  /// Create a JSON wrapper for an Array (list).
-  static JSON newArray();
-
-  /// Create a JSON wrapper from an existing value.
-  static JSON newFromValue(const rapidjson::Value& value);
-
- public:
-  /// Make a JSON object (map).
-  rapidjson::Document getObject() const;
-
-  /// Make a JSON array (list).
-  rapidjson::Document getArray() const;
-
-  /// Add a JSON object or array to a list.
-  void push(rapidjson::Value& value);
-
-  /// Add a JSON object or array to a list.
-  void push(rapidjson::Value& value, rapidjson::Value& arr);
-
-  /// Add a size_t to a JSON array.
-  void push(size_t value);
-
-  /// Add a size_t to a JSON array.
-  void push(size_t value, rapidjson::Value& arr);
-
-  /// Add a copy of a string to a JSON array.
-  void pushCopy(const std::string& value);
-
-  /// Add a reference to a string to a JSON array.
-  void pushCopy(const std::string& value, rapidjson::Value& arr);
-
-  /**
-   * @brief Add a string value to a JSON object by copying the contents.
-   *
-   * This will add the key and value to an input document. If the key exists
-   * the value will be replaced.
-   * The input document must be an object type.
-   */
-  void addCopy(const std::string& key,
-               const std::string& value,
-               rapidjson::Value& obj);
-
-  /**
-   * @brief Add a string value to a JSON object by copying the contents.
-   *
-   * This will add the key and value to the JSON document. If the key exists
-   * the value will be replaced.
-   * The document must be an object type.
-   */
-  void addCopy(const std::string& key, const std::string& value);
-
-  /**
-   * @brief Add a string value to a JSON object by referencing the contents.
-   *
-   * The string value must live longer than the document's use.
-   *
-   * This will add the key and value to an input document. If the key exists
-   * the value will be replaced.
-   * The input document must be an object type.
-   */
-  void addRef(const std::string& key,
-              const std::string& value,
-              rapidjson::Value& obj);
-
-  /**
-   * @brief Add a string value to a JSON object by referencing the contents.
-   *
-   * The string value must live longer than the document's use.
-   *
-   * This will add the key and value to the JSON document. If the key exists
-   * the value will be replaced.
-   * The input document must be an object type.
-   */
-  void addRef(const std::string& key, const std::string& value);
-
-  /**
-   * @brief Add a string value to a JSON object by copying the contents.
-   *
-   * This is basically and alias for addCopy()
-   *
-   * This will add the key and value to an input document. If the key exists
-   * the value will be replaced.
-   * The input document must be an object type.
-   */
-  void add(const std::string& key,
-           const std::string& value,
-           rapidjson::Value& obj);
-
-  /**
-   * @brief Add a string value to a JSON object by copying the contents.
-   *
-   * This is basically and alias for addCopy().
-   *
-   * This will add the key and value to the JSON document. If the key exists
-   * the value will be replaced.
-   * The document must be an object type.
-   */
-  void add(const std::string& key, const std::string& value);
-
-  /**
-   * @brief Add a char* value to a JSON object by copying the contents.
-   *
-   * This will add the key and value to an input document. If the key exists
-   * the value will be replaced.
-   * The input document must be an object type.
-   */
-  void add(const std::string& key, const char* value, rapidjson::Value& obj);
-
-  /**
-   * @brief Add a char* value to a JSON object by copying the contents.
-   *
-   * This will add the key and value to the JSON document. If the key exists
-   * the value will be replaced.
-   * The document must be an object type.
-   */
-  void add(const std::string& key, const char* value);
-
-  /**
-   * @brief Add a int value to a JSON object by copying the contents.
-   *
-   * This will add the key and value to an input document. If the key exists
-   * the value will be replaced.
-   * The input document must be an object type.
-   */
-  void add(const std::string& key, int value, rapidjson::Value& obj);
-
-  /**
-   * @brief Add a int value to a JSON object by copying the contents.
-   *
-   * This will add the key and value to the JSON document. If the key exists
-   * the value will be replaced.
-   * The document must be an object type.
-   */
-  void add(const std::string& key, int value);
-
-  /**
-   * @brief Add a long value to a JSON object by copying the contents.
-   *
-   * This will add the key and value to an input document. If the key exists
-   * the value will be replaced.
-   * The input document must be an object type.
-   */
-  void add(const std::string& key, long value, rapidjson::Value& obj);
-
-  /**
-   * @brief Add a long value to a JSON object by copying the contents.
-   *
-   * This will add the key and value to the JSON document. If the key exists
-   * the value will be replaced.
-   * The document must be an object type.
-   */
-  void add(const std::string& key, long value);
-
-  /**
-   * @brief Add a long long to a JSON object by copying the
-   * contents.
-   *
-   * This will add the key and value to an input document. If the key exists
-   * the value will be replaced.
-   * The input document must be an object type.
-   */
-  void add(const std::string& key, long long value, rapidjson::Value& obj);
-  /**
-   * @brief Add a long long to a JSON object by copying the
-   * contents.
-   *
-   * This will add the key and value to the JSON document. If the key exists
-   * the value will be replaced.
-   * The document must be an object type.
-   */
-  void add(const std::string& key, long long value);
-
-  /**
-   * @brief Add an unsigned int value to a JSON object by copying the contents.
-   *
-   * This will add the key and value to an input document. If the key exists
-   * the value will be replaced.
-   * The input document must be an object type.
-   */
-  void add(const std::string& key, unsigned int value, rapidjson::Value& obj);
-
-  /**
-   * @brief Add an unsigned int value to a JSON object by copying the contents.
-   *
-   * This will add the key and value to the JSON document. If the key exists
-   * the value will be replaced.
-   * The document must be an object type.
-   */
-  void add(const std::string& key, unsigned int value);
-
-  /**
-   * @brief Add an unsigned long value to a JSON object by copying the contents.
-   *
-   * This will add the key and value to an input document. If the key exists
-   * the value will be replaced.
-   * The input document must be an object type.
-   */
-  void add(const std::string& key, unsigned long value, rapidjson::Value& obj);
-
-  /**
-   * @brief Add an unsigned long value to a JSON object by copying the contents.
-   *
-   * This will add the key and value to the JSON document. If the key exists
-   * the value will be replaced.
-   * The document must be an object type.
-   */
-  void add(const std::string& key, unsigned long value);
-
-  /**
-   * @brief Add an unsigned long long to a JSON object by copying the
-   * contents.
-   *
-   * This will add the key and value to an input document. If the key exists
-   * the value will be replaced.
-   * The input document must be an object type.
-   */
-  void add(const std::string& key,
-           unsigned long long value,
-           rapidjson::Value& obj);
-  /**
-   * @brief Add an unsigned long long to a JSON object by copying the
-   * contents.
-   *
-   * This will add the key and value to the JSON document. If the key exists
-   * the value will be replaced.
-   * The document must be an object type.
-   */
-  void add(const std::string& key, unsigned long long value);
-
-  /**
-   * @brief Add a double value to a JSON object by copying the contents.
-   *
-   * This will add the key and value to an input document. If the key exists
-   * the value will be replaced.
-   * The input document must be an object type.
-   */
-  void add(const std::string& key, double value, rapidjson::Value& obj);
-  /**
-   * @brief Add an double value to a JSON object by copying the contents.
-   *
-   * This will add the key and value to the JSON document. If the key exists
-   * the value will be replaced.
-   * The document must be an object type.
-   */
-  void add(const std::string& key, double value);
-
-  /**
-   * @brief Add a bool value to a JSON object by copying the contents.
-   *
-   * This will add the key and value to an input document. If the key exists
-   * the value will be replaced.
-   * The input document must be an object type.
-   */
-  void add(const std::string& key, bool value, rapidjson::Value& obj);
-
-  /**
-   * @brief Add a bool value to a JSON object by copying the contents.
-   *
-   * This will add the key and value to the JSON document. If the key exists
-   * the value will be replaced.
-   * The document must be an object type.
-   */
-  void add(const std::string& key, bool value);
-
-  /// Add a JSON document as a member.
-  void add(const std::string& key, const rapidjson::Value& value);
-
-  /// Add a JSON document as a member of another document.
-  void add(const std::string& key,
-           const rapidjson::Value& value,
-           rapidjson::Value& obj);
-
-  /**
-   * @brief Copy a JSON object/array into the document.
-   *
-   * The type of the base document may change, be careful.
-   */
-  void copyFrom(const rapidjson::Value& value, rapidjson::Value& target);
-
-  /**
-   * @brief Copy a JSON object/array into the document.
-   *
-   * The type of the base document may change, be careful.
-   */
-  void copyFrom(const rapidjson::Value& value);
-
-  /// Convert this document to a JSON string.
-  Status toString(std::string& str) const;
-
-  /// Helper to convert a string into JSON.
-  Status fromString(const std::string& str);
-
-  /// Merge members of source into target, must both be objects.
-  void mergeObject(rapidjson::Value& target_obj, rapidjson::Value& source_obj);
-
-  void mergeArray(rapidjson::Value& target_arr, rapidjson::Value& source_arr);
-
-  /// Access the internal document containing the allocator.
-  rapidjson::Document& doc();
-
-  /// Access the internal document containing the allocator.
-  const rapidjson::Document& doc() const;
-
- public:
-  /// Get the value as a 'size' or 0.
-  static size_t valueToSize(const rapidjson::Value& value);
-
-  /// Get the value as a 'bool' or false.
-  static bool valueToBool(const rapidjson::Value& value);
-
- private:
-  rapidjson::Document doc_;
-  decltype(rapidjson::kObjectType) type_;
-};
-} // namespace osquery
diff --git a/src/osquery/utils/json/tests/json.cpp b/src/osquery/utils/json/tests/json.cpp
deleted file mode 100644 (file)
index 650ebd2..0000000
+++ /dev/null
@@ -1,231 +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 <string>
-#include <unordered_map>
-
-#include <gtest/gtest.h>
-
-#include <osquery/utils/json/json.h>
-
-namespace osquery {
-
-class ConversionsTests : public testing::Test {};
-
-TEST_F(ConversionsTests, test_json_array) {
-  auto doc = JSON::newArray();
-
-  {
-    auto obj = doc.getObject();
-    size_t value = 10;
-    doc.add("key", value, obj);
-    int value2 = -10;
-    doc.add("key2", value2, obj);
-    int64_t value3 = (uint64_t(1)) << 48;
-    doc.add("key3", value3, obj);
-    double value4 = 3.14159265359;
-    doc.add("key4", value4, obj);
-    doc.push(obj);
-  }
-
-  size_t value = 11;
-  doc.push(value);
-
-  std::string result;
-  EXPECT_TRUE(doc.toString(result));
-
-  std::string expected =
-      "[{\"key\":10,\"key2\":-10,\"key3\":281474976710656,\"key4\":3."
-      "14159265359},11]";
-  EXPECT_EQ(expected, result);
-}
-
-TEST_F(ConversionsTests, test_json_object) {
-  auto doc = JSON::newObject();
-
-  {
-    size_t value = 10;
-    doc.add("key", value);
-  }
-
-  std::string result;
-  EXPECT_TRUE(doc.toString(result));
-
-  std::string expected = "{\"key\":10}";
-  EXPECT_EQ(expected, result);
-}
-
-TEST_F(ConversionsTests, test_json_from_string) {
-  std::string json = "{\"key\":\"value\",\"key2\":{\"key3\":3}}";
-  auto doc = JSON::newObject();
-
-  EXPECT_TRUE(doc.fromString(json).ok());
-
-  std::string result;
-  EXPECT_TRUE(doc.toString(result));
-  EXPECT_EQ(json, result);
-
-  json += ';';
-  EXPECT_FALSE(doc.fromString(json).ok());
-}
-
-TEST_F(ConversionsTests, test_json_from_string_error) {
-  std::string json = "{\"key\":\"value\",\"key2\":{\"key3\":'error'}}";
-  auto doc = JSON::newObject();
-  auto s = doc.fromString(json);
-  EXPECT_FALSE(s.ok());
-  EXPECT_EQ(s.getMessage(), "Cannot parse JSON: Invalid value. Offset: 30");
-}
-
-TEST_F(ConversionsTests, test_json_add_object) {
-  std::string json = "{\"key\":\"value\", \"key2\":{\"key3\":[3,2,1]}}";
-  auto doc = JSON::newObject();
-
-  ASSERT_TRUE(doc.fromString(json));
-  auto doc2 = JSON::newObject();
-  doc2.add("key2", doc.doc()["key2"]);
-  EXPECT_TRUE(doc2.doc().HasMember("key2"));
-  EXPECT_TRUE(doc2.doc()["key2"].IsObject());
-  EXPECT_TRUE(doc2.doc()["key2"].HasMember("key3"));
-
-  auto doc3 = JSON::newFromValue(doc.doc()["key2"]);
-  ASSERT_TRUE(doc3.doc().IsObject());
-  EXPECT_TRUE(doc3.doc().HasMember("key3"));
-
-  auto doc4 = JSON::newArray();
-  auto arr = doc4.getArray();
-  doc4.copyFrom(doc.doc()["key2"]["key3"], arr);
-  doc4.push(arr);
-
-  std::string expected = "[[3,2,1]]";
-  std::string output;
-  ASSERT_TRUE(doc4.toString(output).ok());
-  EXPECT_EQ(expected, output);
-}
-
-TEST_F(ConversionsTests, test_json_strings) {
-  auto doc = JSON::newObject();
-
-  {
-    std::string value("value");
-    doc.addCopy("key", value);
-  }
-
-  std::string value2("value2");
-  doc.addRef("key2", value2);
-
-  std::string result;
-  EXPECT_TRUE(doc.toString(result));
-
-  std::string expected = "{\"key\":\"value\",\"key2\":\"value2\"}";
-  EXPECT_EQ(expected, result);
-}
-
-TEST_F(ConversionsTests, test_json_strings_array) {
-  auto doc = JSON::newObject();
-
-  {
-    auto arr = doc.getArray();
-    std::string value("value");
-    doc.pushCopy(value, arr);
-    doc.add("array", arr);
-  }
-
-  std::string result;
-  EXPECT_TRUE(doc.toString(result));
-  std::string expected = "{\"array\":[\"value\"]}";
-  EXPECT_EQ(expected, result);
-}
-
-TEST_F(ConversionsTests, test_json_duplicate_keys) {
-  auto doc = JSON::newObject();
-
-  size_t value = 10;
-  doc.add("key", value);
-  value = 11;
-  doc.add("key", value);
-
-  std::string result;
-  EXPECT_TRUE(doc.toString(result));
-
-  std::string expected = "{\"key\":11}";
-  EXPECT_EQ(expected, result);
-}
-
-TEST_F(ConversionsTests, test_json_merge_object) {
-  auto doc1 = JSON::newObject();
-
-  size_t value = 10;
-  doc1.add("key", value);
-  std::string value2 = "value";
-  doc1.addRef("key2", value2);
-
-  {
-    std::string temp_value = "temp_value";
-    doc1.addCopy("temp_key", temp_value);
-
-    auto arr = doc1.getArray();
-    doc1.add("array", arr);
-  }
-
-  auto doc2 = JSON::newObject();
-  doc2.add("new_key", size_t{10});
-  doc2.addCopy("new_key1", "new_value");
-
-  doc2.mergeObject(doc2.doc(), doc1.doc());
-
-  std::string result;
-  EXPECT_TRUE(doc2.toString(result));
-
-  std::string expected =
-      "{\"new_key\":10,\"new_key1\":\"new_value\",\"key\":10,\"key2\":"
-      "\"value\",\"temp_key\":\"temp_value\",\"array\":[]}";
-  EXPECT_EQ(expected, result);
-}
-
-TEST_F(ConversionsTests, test_json_size_like) {
-  auto doc = JSON::newObject();
-  doc.addRef("key", "10");
-
-  int value = 10;
-  doc.add("key2", value);
-
-  EXPECT_EQ(JSON::valueToSize(doc.doc()["key"]), size_t{10});
-  EXPECT_EQ(JSON::valueToSize(doc.doc()["key2"]), size_t{10});
-}
-
-TEST_F(ConversionsTests, test_json_bool_like) {
-  auto doc = JSON::newObject();
-  doc.addRef("true1", "true");
-  doc.addRef("true2", "T");
-  doc.addRef("true3", "t");
-  doc.addRef("true4", "TRUE");
-  doc.add("true5", 1);
-
-  EXPECT_TRUE(JSON::valueToBool(doc.doc()["true1"]));
-  EXPECT_TRUE(JSON::valueToBool(doc.doc()["true2"]));
-  EXPECT_TRUE(JSON::valueToBool(doc.doc()["true3"]));
-  EXPECT_TRUE(JSON::valueToBool(doc.doc()["true4"]));
-  EXPECT_TRUE(JSON::valueToBool(doc.doc()["true5"]));
-
-  doc.addRef("false1", "awesome");
-  doc.addRef("false2", "false");
-  doc.addRef("false3", "F");
-  doc.addRef("false4", "FALSE");
-  doc.addRef("false5", "f");
-  doc.add("false6", 0);
-
-  EXPECT_FALSE(JSON::valueToBool(doc.doc()["false1"]));
-  EXPECT_FALSE(JSON::valueToBool(doc.doc()["false2"]));
-  EXPECT_FALSE(JSON::valueToBool(doc.doc()["false3"]));
-  EXPECT_FALSE(JSON::valueToBool(doc.doc()["false4"]));
-  EXPECT_FALSE(JSON::valueToBool(doc.doc()["false5"]));
-  EXPECT_FALSE(JSON::valueToBool(doc.doc()["false6"]));
-}
-
-} // namespace osquery
index 5cfcf3a..d180afb 100644 (file)
@@ -17,6 +17,7 @@
 #include "bluetooth.hpp"
 
 #include <vist/exception.hpp>
+#include <vist/json.hpp>
 #include <vist/logger.hpp>
 #include <vist/policy/api.hpp>
 
@@ -88,23 +89,20 @@ TableRows BluetoothTable::generate(QueryContext&) try {
 
 QueryData BluetoothTable::update(QueryContext&, const PluginRequest& request) try {
        INFO(VIST) << "Update query about bluetooth table.";
-       if (request.count("json_value_array") == 0)
+       if (request.count("json_values") == 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)
+       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", document[0].GetInt());
-       setPolicy("bluetooth-desktop-connectivity", document[1].GetInt());
-       setPolicy("bluetooth-pairing", document[2].GetInt());
-       setPolicy("bluetooth-tethering", document[3].GetInt());
+       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";
index 5dc7786..a56fb99 100644 (file)
@@ -17,6 +17,7 @@
 #include "policy-admin.hpp"
 
 #include <vist/exception.hpp>
+#include <vist/json.hpp>
 #include <vist/logger.hpp>
 #include <vist/policy/api.hpp>
 
@@ -45,15 +46,13 @@ std::string getValue(std::string&& alias, const std::string& key)
 
 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.");
+       json::Json document = json::Json::Parse(request);
+       json::Array values = document.get<json::Array>("values");
 
        if (insert)
-               return std::string(document[0].GetString());
+               return values.at(0);
        else
-               return getValue(document[0].GetString(), "name");
+               return getValue(values.at(0), "name");
 }
 
 } // anonymous namespace
@@ -119,10 +118,11 @@ TableRows PolicyAdminTable::generate(QueryContext& context) try
 QueryData PolicyAdminTable::insert(QueryContext&, const PluginRequest& request) try
 {
        INFO(VIST) << "Insert query about policy-admin table.";
-       if (request.count("json_value_array") == 0)
+       if (request.count("json_values") == 0)
                throw std::runtime_error("Wrong request format. Not found json value.");
 
-       auto admin = parseAdmin(request.at("json_value_array"));
+       DEBUG(VIST) << "Request values: " << request.at("json_values");
+       auto admin = parseAdmin(request.at("json_values"));
        DEBUG(VIST) << "Admin info [name]: " << admin;
        vist::policy::API::Admin::Enroll(admin);
 
@@ -142,10 +142,11 @@ QueryData PolicyAdminTable::insert(QueryContext&, const PluginRequest& request)
 QueryData PolicyAdminTable::delete_(QueryContext&, const PluginRequest& request) try
 {
        INFO(VIST) << "Delete query about policy-admin table.";
-       if (request.count("json_value_array") == 0)
+       if (request.count("json_values") == 0)
                throw std::runtime_error("Wrong request format. Not found json value.");
 
-       auto admin = parseAdmin(request.at("json_value_array"), false);
+       DEBUG(VIST) << "Request values: " << request.at("json_values");
+       auto admin = parseAdmin(request.at("json_values"), false);
        DEBUG(VIST) << "Admin info [name]: " << admin;
        vist::policy::API::Admin::Disenroll(admin);
 
@@ -165,20 +166,17 @@ QueryData PolicyAdminTable::delete_(QueryContext&, const PluginRequest& request)
 QueryData PolicyAdminTable::update(QueryContext&, const PluginRequest& request) try
 {
        INFO(VIST) << "Update query about policy-admin table.";
-       if (request.count("json_value_array") == 0)
+       if (request.count("json_values") == 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)
+       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.");
 
-       std::string name = document[0].GetString();
-       int activated = document[1].GetInt();
+       std::string name = static_cast<std::string>(values.at(0));
+       int activated = static_cast<int>(values.at(1));
 
        vist::policy::API::Admin::Activate(name, activated);
 
index 1d4fb2b..6970d52 100644 (file)
@@ -17,6 +17,7 @@
 #include "policy.hpp"
 
 #include <vist/exception.hpp>
+#include <vist/json.hpp>
 #include <vist/logger.hpp>
 #include <vist/policy/api.hpp>
 
@@ -93,20 +94,17 @@ TableRows PolicyTable::generate(QueryContext& context) try
 QueryData PolicyTable::update(QueryContext&, const PluginRequest& request) try
 {
        INFO(VIST) << "Update query about policy table.";
-       if (request.count("json_value_array") == 0)
+       if (request.count("json_values") == 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)
+       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.");
 
-       std::string name = document[0].GetString();
-       std::string dumpedValue = document[1].GetString();
+       std::string name = static_cast<std::string>(values.at(0));
+       std::string dumpedValue = static_cast<std::string>(values.at(1));
 
        vist::policy::API::Admin::Set(name, vist::policy::PolicyValue(dumpedValue, true));