diff --git a/src/storage/Serializer.h b/src/storage/Serializer.h index 8b5643bf1e..939b06b0be 100644 --- a/src/storage/Serializer.h +++ b/src/storage/Serializer.h @@ -36,8 +36,6 @@ public: protected: Serializer(std::string name) : name(std::move(name)) {} - -private: std::string name; }; diff --git a/src/storage/serializer/json/JSON.cc b/src/storage/serializer/json/JSON.cc index a639112524..ecc4296e37 100644 --- a/src/storage/serializer/json/JSON.cc +++ b/src/storage/serializer/json/JSON.cc @@ -6,24 +6,39 @@ namespace zeek::storage::serializer::json { +std::string JSON::versioned_name = "JSONv1"; + std::unique_ptr JSON::Instantiate() { return std::make_unique(); } JSON::JSON() : Serializer("JSON") {} std::optional JSON::Serialize(ValPtr val) { + static auto byte_converter = [](u_char c) { return std::byte(c); }; + byte_buffer buf; auto json = val->ToJSON(); - buf.reserve(json->Len()); + buf.reserve(json->Len() + versioned_name.size() + 1); - std::transform(json->Bytes(), json->Bytes() + json->Len(), std::back_inserter(buf), - [](u_char c) { return std::byte(c); }); + std::transform(versioned_name.begin(), versioned_name.end(), std::back_inserter(buf), byte_converter); + buf.push_back(static_cast(';')); + std::transform(json->Bytes(), json->Bytes() + json->Len(), std::back_inserter(buf), byte_converter); return buf; } zeek::expected JSON::Unserialize(byte_buffer_span buf, TypePtr type) { std::string_view text{reinterpret_cast(buf.data()), buf.size()}; - return zeek::detail::ValFromJSON(text, type, Func::nil); + + auto semicolon = text.find(';'); + if ( semicolon == std::string::npos ) + return zeek::unexpected("Version string missing"); + + std::string_view version = std::string_view(text).substr(0, semicolon); + if ( version != versioned_name ) + return zeek::unexpected( + util::fmt("Version doesn't match: %s vs %s", version.data(), versioned_name.c_str())); + + return zeek::detail::ValFromJSON(text.substr(semicolon + 1), type, Func::nil); } } // namespace zeek::storage::serializer::json diff --git a/src/storage/serializer/json/JSON.h b/src/storage/serializer/json/JSON.h index c9789d6b9f..d31d25acd5 100644 --- a/src/storage/serializer/json/JSON.h +++ b/src/storage/serializer/json/JSON.h @@ -15,6 +15,9 @@ public: std::optional Serialize(ValPtr val) override; zeek::expected Unserialize(byte_buffer_span buf, TypePtr type) override; + +private: + static std::string versioned_name; }; } // namespace zeek::storage::serializer::json