1 parent
8583a479dd
commit
3851aeb703
42 files changed
+6948
-759
No files matched your search
+11
-6
@@ -1,5 +1,12 @@
|
|||||||
cmake_minimum_required(VERSION 4.0.0)
|
cmake_minimum_required(VERSION 4.0.0)
|
||||||
project(Void VERSION 1.0.0 LANGUAGES CXX)
|
project(Void VERSION 1.0.0 LANGUAGES CXX)
|
||||||
|
if(PROJECT_IS_TOP_LEVEL)
|
||||||
|
option(BUILD_SHARED_LIBS "Build Void modules as shared libraries" ON)
|
||||||
|
elseif(NOT DEFINED BUILD_SHARED_LIBS)
|
||||||
|
# Keep Void's shared default local when embedded so a dependency does not
|
||||||
|
# silently change the linkage policy of its parent project.
|
||||||
|
set(BUILD_SHARED_LIBS ON)
|
||||||
|
endif()
|
||||||
option(VOID_ENABLE_TESTING "Build the test suite" ON)
|
option(VOID_ENABLE_TESTING "Build the test suite" ON)
|
||||||
option(VOID_WARNINGS_AS_ERRORS "Treat compiler warnings as errors" OFF)
|
option(VOID_WARNINGS_AS_ERRORS "Treat compiler warnings as errors" OFF)
|
||||||
option(VOID_ENABLE_ASAN "Enable AddressSanitizer (Clang/GCC)" OFF)
|
option(VOID_ENABLE_ASAN "Enable AddressSanitizer (Clang/GCC)" OFF)
|
||||||
@@ -41,13 +48,11 @@ if(VOID_ENABLE_TESTING)
|
|||||||
|
|
||||||
endif()
|
endif()
|
||||||
get_property(ALL_DISCOVERED_MODULES GLOBAL PROPERTY VOID_MODULES)
|
get_property(ALL_DISCOVERED_MODULES GLOBAL PROPERTY VOID_MODULES)
|
||||||
get_property(ALL_EXTERNAL_DEPS GLOBAL PROPERTY VOID_EXT_DEPS)
|
get_property(ALL_MODULE_DEPENDENCY_RECORDS GLOBAL PROPERTY
|
||||||
|
VOID_MODULE_DEPENDENCY_RECORDS)
|
||||||
|
|
||||||
if(ALL_EXTERNAL_DEPS)
|
set(VOID_MODULES_LIST "${ALL_DISCOVERED_MODULES}")
|
||||||
list(REMOVE_DUPLICATES ALL_EXTERNAL_DEPS)
|
set(VOID_MODULE_DEPENDENCY_RECORDS "${ALL_MODULE_DEPENDENCY_RECORDS}")
|
||||||
endif()
|
|
||||||
|
|
||||||
set(VOID_EXTERNAL_DEPS_LIST "${ALL_EXTERNAL_DEPS}")
|
|
||||||
|
|
||||||
write_basic_package_version_file(
|
write_basic_package_version_file(
|
||||||
"${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake"
|
"${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake"
|
||||||
|
|||||||
@@ -64,6 +64,13 @@ function(void_fetch_dependency DEP_NAME)
|
|||||||
INTERFACE_LINK_LIBRARIES PkgConfig::SODIUM)
|
INTERFACE_LINK_LIBRARIES PkgConfig::SODIUM)
|
||||||
return()
|
return()
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
|
if(DEP_NAME STREQUAL "LibArchive")
|
||||||
|
if(NOT TARGET LibArchive::LibArchive)
|
||||||
|
find_package(LibArchive REQUIRED)
|
||||||
|
endif()
|
||||||
|
return()
|
||||||
|
endif()
|
||||||
# FIXME: Add if needed external
|
# FIXME: Add if needed external
|
||||||
# if(DEP_NAME STREQUAL "glaze")
|
# if(DEP_NAME STREQUAL "glaze")
|
||||||
# if(NOT glaze_POPULATED)
|
# if(NOT glaze_POPULATED)
|
||||||
|
|||||||
+21
-2
@@ -1,5 +1,5 @@
|
|||||||
set_property(GLOBAL PROPERTY VOID_MODULES "")
|
set_property(GLOBAL PROPERTY VOID_MODULES "")
|
||||||
set_property(GLOBAL PROPERTY VOID_EXT_DEPS "")
|
set_property(GLOBAL PROPERTY VOID_MODULE_DEPENDENCY_RECORDS "")
|
||||||
set_property(GLOBAL PROPERTY VOID_PENDING_OPTIONAL_DEPS "")
|
set_property(GLOBAL PROPERTY VOID_PENDING_OPTIONAL_DEPS "")
|
||||||
|
|
||||||
function(void_add_module MODULE_NAME)
|
function(void_add_module MODULE_NAME)
|
||||||
@@ -38,13 +38,32 @@ function(void_add_module MODULE_NAME)
|
|||||||
add_library(${ALIAS} ALIAS ${TGT})
|
add_library(${ALIAS} ALIAS ${TGT})
|
||||||
|
|
||||||
set_property(GLOBAL APPEND PROPERTY VOID_MODULES ${MODULE_NAME})
|
set_property(GLOBAL APPEND PROPERTY VOID_MODULES ${MODULE_NAME})
|
||||||
|
set(_module_external_deps "")
|
||||||
foreach(ext_dep IN LISTS ARG_EXTERNAL_DEPS)
|
foreach(ext_dep IN LISTS ARG_EXTERNAL_DEPS)
|
||||||
string(REGEX REPLACE "::.*" "" BASE_DEP ${ext_dep})
|
string(REGEX REPLACE "::.*" "" BASE_DEP ${ext_dep})
|
||||||
set_property(GLOBAL APPEND PROPERTY VOID_EXT_DEPS ${BASE_DEP})
|
list(APPEND _module_external_deps ${BASE_DEP})
|
||||||
include(cmake/Dependencies.cmake)
|
include(cmake/Dependencies.cmake)
|
||||||
void_fetch_dependency(${BASE_DEP})
|
void_fetch_dependency(${BASE_DEP})
|
||||||
endforeach()
|
endforeach()
|
||||||
|
|
||||||
|
set(_module_internal_deps ${ARG_INTERNAL_DEPS} ${ARG_OPTIONAL_DEPS})
|
||||||
|
if(_module_internal_deps)
|
||||||
|
list(REMOVE_DUPLICATES _module_internal_deps)
|
||||||
|
string(REPLACE ";" "," _module_internal_record
|
||||||
|
"${_module_internal_deps}")
|
||||||
|
else()
|
||||||
|
set(_module_internal_record "-")
|
||||||
|
endif()
|
||||||
|
if(_module_external_deps)
|
||||||
|
list(REMOVE_DUPLICATES _module_external_deps)
|
||||||
|
string(REPLACE ";" "," _module_external_record
|
||||||
|
"${_module_external_deps}")
|
||||||
|
else()
|
||||||
|
set(_module_external_record "-")
|
||||||
|
endif()
|
||||||
|
set_property(GLOBAL APPEND PROPERTY VOID_MODULE_DEPENDENCY_RECORDS
|
||||||
|
"${MODULE_NAME}|${_module_internal_record}|${_module_external_record}")
|
||||||
|
|
||||||
foreach(int_dep IN LISTS ARG_INTERNAL_DEPS)
|
foreach(int_dep IN LISTS ARG_INTERNAL_DEPS)
|
||||||
target_link_libraries(${TGT} ${SCOPE} ${PROJECT_NAME}::${int_dep})
|
target_link_libraries(${TGT} ${SCOPE} ${PROJECT_NAME}::${int_dep})
|
||||||
endforeach()
|
endforeach()
|
||||||
|
|||||||
@@ -2,7 +2,66 @@
|
|||||||
|
|
||||||
include(CMakeFindDependencyMacro)
|
include(CMakeFindDependencyMacro)
|
||||||
|
|
||||||
set(_void_external_deps "@VOID_EXTERNAL_DEPS_LIST@")
|
set(_void_known_modules "@VOID_MODULES_LIST@")
|
||||||
|
set(_void_module_dependency_records "@VOID_MODULE_DEPENDENCY_RECORDS@")
|
||||||
|
|
||||||
|
function(_void_module_dependencies module out_internal out_external)
|
||||||
|
foreach(record IN LISTS _void_module_dependency_records)
|
||||||
|
string(REPLACE "|" ";" fields "${record}")
|
||||||
|
list(GET fields 0 record_module)
|
||||||
|
if(NOT record_module STREQUAL module)
|
||||||
|
continue()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
list(GET fields 1 internal_csv)
|
||||||
|
list(GET fields 2 external_csv)
|
||||||
|
if(internal_csv STREQUAL "-")
|
||||||
|
set(internal "")
|
||||||
|
else()
|
||||||
|
string(REPLACE "," ";" internal "${internal_csv}")
|
||||||
|
endif()
|
||||||
|
if(external_csv STREQUAL "-")
|
||||||
|
set(external "")
|
||||||
|
else()
|
||||||
|
string(REPLACE "," ";" external "${external_csv}")
|
||||||
|
endif()
|
||||||
|
set(${out_internal} "${internal}" PARENT_SCOPE)
|
||||||
|
set(${out_external} "${external}" PARENT_SCOPE)
|
||||||
|
return()
|
||||||
|
endforeach()
|
||||||
|
set(${out_internal} "" PARENT_SCOPE)
|
||||||
|
set(${out_external} "" PARENT_SCOPE)
|
||||||
|
endfunction()
|
||||||
|
|
||||||
|
# With no requested components, preserve the historical all-modules package
|
||||||
|
# behavior. Component-aware consumers resolve only the transitive dependencies
|
||||||
|
# of the modules they explicitly request.
|
||||||
|
if(Void_FIND_COMPONENTS)
|
||||||
|
set(_void_pending_modules ${Void_FIND_COMPONENTS})
|
||||||
|
else()
|
||||||
|
set(_void_pending_modules ${_void_known_modules})
|
||||||
|
endif()
|
||||||
|
|
||||||
|
set(_void_required_modules "")
|
||||||
|
while(_void_pending_modules)
|
||||||
|
list(POP_FRONT _void_pending_modules module)
|
||||||
|
if(NOT module IN_LIST _void_known_modules OR
|
||||||
|
module IN_LIST _void_required_modules)
|
||||||
|
continue()
|
||||||
|
endif()
|
||||||
|
list(APPEND _void_required_modules "${module}")
|
||||||
|
_void_module_dependencies("${module}" internal_deps external_deps)
|
||||||
|
list(APPEND _void_pending_modules ${internal_deps})
|
||||||
|
endwhile()
|
||||||
|
|
||||||
|
set(_void_external_deps "")
|
||||||
|
foreach(module IN LISTS _void_required_modules)
|
||||||
|
_void_module_dependencies("${module}" internal_deps external_deps)
|
||||||
|
list(APPEND _void_external_deps ${external_deps})
|
||||||
|
endforeach()
|
||||||
|
if(_void_external_deps)
|
||||||
|
list(REMOVE_DUPLICATES _void_external_deps)
|
||||||
|
endif()
|
||||||
foreach(dep IN LISTS _void_external_deps)
|
foreach(dep IN LISTS _void_external_deps)
|
||||||
if(dep STREQUAL "Boost")
|
if(dep STREQUAL "Boost")
|
||||||
find_dependency(Boost REQUIRED COMPONENTS stacktrace_backtrace url)
|
find_dependency(Boost REQUIRED COMPONENTS stacktrace_backtrace url)
|
||||||
@@ -14,6 +73,8 @@ foreach(dep IN LISTS _void_external_deps)
|
|||||||
set_property(TARGET Sodium::Sodium PROPERTY
|
set_property(TARGET Sodium::Sodium PROPERTY
|
||||||
INTERFACE_LINK_LIBRARIES PkgConfig::SODIUM)
|
INTERFACE_LINK_LIBRARIES PkgConfig::SODIUM)
|
||||||
endif()
|
endif()
|
||||||
|
elseif(dep STREQUAL "LibArchive")
|
||||||
|
find_dependency(LibArchive REQUIRED)
|
||||||
elseif(NOT TARGET ${dep})
|
elseif(NOT TARGET ${dep})
|
||||||
find_dependency(${dep})
|
find_dependency(${dep})
|
||||||
endif()
|
endif()
|
||||||
@@ -21,6 +82,14 @@ endforeach()
|
|||||||
|
|
||||||
include("${CMAKE_CURRENT_LIST_DIR}/@EXPORT_SET_NAME@.cmake")
|
include("${CMAKE_CURRENT_LIST_DIR}/@EXPORT_SET_NAME@.cmake")
|
||||||
|
|
||||||
|
foreach(component IN LISTS Void_FIND_COMPONENTS)
|
||||||
|
if(TARGET Void::${component})
|
||||||
|
set(Void_${component}_FOUND TRUE)
|
||||||
|
else()
|
||||||
|
set(Void_${component}_FOUND FALSE)
|
||||||
|
endif()
|
||||||
|
endforeach()
|
||||||
|
|
||||||
# Auto-load the testing helper so consumers get void_add_tests + the
|
# Auto-load the testing helper so consumers get void_add_tests + the
|
||||||
# auto-scan sweep just by find_package(Void).
|
# auto-scan sweep just by find_package(Void).
|
||||||
if(EXISTS "${CMAKE_CURRENT_LIST_DIR}/VoidTesting.cmake")
|
if(EXISTS "${CMAKE_CURRENT_LIST_DIR}/VoidTesting.cmake")
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <filesystem>
|
||||||
|
|
||||||
|
namespace Void::Archive
|
||||||
|
{
|
||||||
|
struct ExtractionOptions {
|
||||||
|
std::size_t maxEntries{10'000};
|
||||||
|
std::uint64_t maxFileBytes{512ULL * 1024 * 1024};
|
||||||
|
std::uint64_t maxTotalBytes{2ULL * 1024 * 1024 * 1024};
|
||||||
|
bool overwriteExisting{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ExtractionResult {
|
||||||
|
std::size_t entries{0};
|
||||||
|
std::uint64_t bytes{0};
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Extract a tar/tar.zst archive without invoking an external process.
|
||||||
|
/// Only regular files and directories are accepted. Absolute/traversal
|
||||||
|
/// paths, links, special files, duplicates and configured size/count
|
||||||
|
/// overages fail the whole operation.
|
||||||
|
[[nodiscard]] Void::Result::Result<ExtractionResult>
|
||||||
|
extract(const std::filesystem::path& archivePath,
|
||||||
|
const std::filesystem::path& destination,
|
||||||
|
const ExtractionOptions& options = {});
|
||||||
|
} // namespace Void::Archive
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <array>
|
||||||
|
#include <bit>
|
||||||
|
#include <concepts>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <cstring>
|
||||||
|
#include <format>
|
||||||
|
#include <span>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
namespace Void::Binary
|
||||||
|
{
|
||||||
|
/// Bounds-checked, non-owning reader for binary formats.
|
||||||
|
class Reader
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
explicit constexpr Reader(std::span<const std::byte> bytes) noexcept
|
||||||
|
: m_bytes(bytes)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] constexpr std::size_t position() const noexcept
|
||||||
|
{
|
||||||
|
return m_position;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] constexpr std::size_t size() const noexcept
|
||||||
|
{
|
||||||
|
return m_bytes.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] constexpr std::size_t remaining() const noexcept
|
||||||
|
{
|
||||||
|
return m_bytes.size() - m_position;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] constexpr bool empty() const noexcept
|
||||||
|
{
|
||||||
|
return remaining() == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void> seek(std::size_t position)
|
||||||
|
{
|
||||||
|
if (position > m_bytes.size()) {
|
||||||
|
return Void::Result::fail(std::format(
|
||||||
|
"Binary::Reader::seek: offset {} exceeds size {}",
|
||||||
|
position, m_bytes.size()));
|
||||||
|
}
|
||||||
|
m_position = position;
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void> skip(std::size_t count)
|
||||||
|
{
|
||||||
|
if (count > remaining()) {
|
||||||
|
return truncated("skip", count);
|
||||||
|
}
|
||||||
|
m_position += count;
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<std::span<const std::byte>>
|
||||||
|
readBytes(std::size_t count)
|
||||||
|
{
|
||||||
|
if (count > remaining()) {
|
||||||
|
return std::unexpected{truncatedError("readBytes", count)};
|
||||||
|
}
|
||||||
|
const auto result = m_bytes.subspan(m_position, count);
|
||||||
|
m_position += count;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<std::span<const std::byte>>
|
||||||
|
peekBytes(std::size_t count) const
|
||||||
|
{
|
||||||
|
if (count > remaining()) {
|
||||||
|
return std::unexpected{truncatedError("peekBytes", count)};
|
||||||
|
}
|
||||||
|
return m_bytes.subspan(m_position, count);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <std::integral T>
|
||||||
|
requires(!std::same_as<T, bool>)
|
||||||
|
[[nodiscard]] Void::Result::Result<T>
|
||||||
|
read(std::endian byteOrder = std::endian::native)
|
||||||
|
{
|
||||||
|
auto bytes = readBytes(sizeof(T));
|
||||||
|
if (!bytes) {
|
||||||
|
return std::unexpected{bytes.error()};
|
||||||
|
}
|
||||||
|
std::array<std::byte, sizeof(T)> storage{};
|
||||||
|
std::ranges::copy(*bytes, storage.begin());
|
||||||
|
T value = std::bit_cast<T>(storage);
|
||||||
|
if constexpr (std::endian::native != std::endian::little &&
|
||||||
|
std::endian::native != std::endian::big) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Binary::Reader::read: mixed-endian targets are "
|
||||||
|
"unsupported");
|
||||||
|
} else if (byteOrder != std::endian::native) {
|
||||||
|
value = std::byteswap(value);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<std::string>
|
||||||
|
readString(std::size_t count)
|
||||||
|
{
|
||||||
|
auto bytes = readBytes(count);
|
||||||
|
if (!bytes) {
|
||||||
|
return std::unexpected{bytes.error()};
|
||||||
|
}
|
||||||
|
return std::string{reinterpret_cast<const char*>(bytes->data()),
|
||||||
|
bytes->size()};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<Reader>
|
||||||
|
subreader(std::size_t count)
|
||||||
|
{
|
||||||
|
auto bytes = readBytes(count);
|
||||||
|
if (!bytes) {
|
||||||
|
return std::unexpected{bytes.error()};
|
||||||
|
}
|
||||||
|
return Reader{*bytes};
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
std::span<const std::byte> m_bytes;
|
||||||
|
std::size_t m_position{0};
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Error
|
||||||
|
truncatedError(std::string_view operation,
|
||||||
|
std::size_t requested) const
|
||||||
|
{
|
||||||
|
return Void::Result::Error{
|
||||||
|
std::format("Binary::Reader::{}: requested {} bytes at "
|
||||||
|
"offset {}, only {} "
|
||||||
|
"remain",
|
||||||
|
operation, requested, m_position, remaining())};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
truncated(std::string_view operation,
|
||||||
|
std::size_t requested) const
|
||||||
|
{
|
||||||
|
return std::unexpected{truncatedError(operation, requested)};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
} // namespace Void::Binary
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <memory>
|
||||||
|
#include <span>
|
||||||
|
#include <string_view>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Crypto
|
||||||
|
{
|
||||||
|
enum class HashAlgorithm { Sha1, Sha256, Sha512 };
|
||||||
|
using Digest = std::vector<std::byte>;
|
||||||
|
|
||||||
|
class Hasher
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
[[nodiscard]] static Void::Result::Result<Hasher>
|
||||||
|
create(HashAlgorithm algorithm);
|
||||||
|
~Hasher();
|
||||||
|
Hasher(Hasher&&) noexcept;
|
||||||
|
Hasher& operator=(Hasher&&) noexcept;
|
||||||
|
Hasher(const Hasher&) = delete;
|
||||||
|
Hasher& operator=(const Hasher&) = delete;
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
update(std::span<const std::byte> data);
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
update(std::string_view data);
|
||||||
|
/// Finalize this hash. Calling finalize or update again is an
|
||||||
|
/// error.
|
||||||
|
[[nodiscard]] Void::Result::Result<Digest> finalize();
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
struct Impl;
|
||||||
|
std::unique_ptr<Impl> m_impl;
|
||||||
|
explicit Hasher(std::unique_ptr<Impl> impl) noexcept;
|
||||||
|
};
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<Digest>
|
||||||
|
hash(HashAlgorithm algorithm, std::span<const std::byte> data);
|
||||||
|
[[nodiscard]] Void::Result::Result<Digest> hash(HashAlgorithm algorithm,
|
||||||
|
std::string_view data);
|
||||||
|
[[nodiscard]] Void::Result::Result<Digest>
|
||||||
|
hashFile(HashAlgorithm algorithm, const std::filesystem::path& path);
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<Digest>
|
||||||
|
sha1(std::span<const std::byte> data);
|
||||||
|
[[nodiscard]] Void::Result::Result<Digest> sha1(std::string_view data);
|
||||||
|
[[nodiscard]] Void::Result::Result<Digest>
|
||||||
|
sha256(std::span<const std::byte> data);
|
||||||
|
[[nodiscard]] Void::Result::Result<Digest> sha256(std::string_view data);
|
||||||
|
[[nodiscard]] Void::Result::Result<Digest>
|
||||||
|
sha512(std::span<const std::byte> data);
|
||||||
|
[[nodiscard]] Void::Result::Result<Digest> sha512(std::string_view data);
|
||||||
|
[[nodiscard]] Void::Result::Result<Digest>
|
||||||
|
sha1File(const std::filesystem::path& path);
|
||||||
|
[[nodiscard]] Void::Result::Result<Digest>
|
||||||
|
sha256File(const std::filesystem::path& path);
|
||||||
|
[[nodiscard]] Void::Result::Result<Digest>
|
||||||
|
sha512File(const std::filesystem::path& path);
|
||||||
|
|
||||||
|
inline constexpr std::size_t Ed25519PublicKeySize = 32;
|
||||||
|
inline constexpr std::size_t Ed25519SignatureSize = 64;
|
||||||
|
|
||||||
|
/// Verify an Ed25519 detached signature over the exact message bytes.
|
||||||
|
/// Invalid key/signature sizes are errors; a well-formed but invalid
|
||||||
|
/// signature returns false.
|
||||||
|
[[nodiscard]] Void::Result::Result<bool>
|
||||||
|
verifyEd25519(std::span<const std::byte> message,
|
||||||
|
std::span<const std::byte> signature,
|
||||||
|
std::span<const std::byte> publicKey);
|
||||||
|
} // namespace Void::Crypto
|
||||||
@@ -9,82 +9,97 @@
|
|||||||
namespace Void::Plugin
|
namespace Void::Plugin
|
||||||
{
|
{
|
||||||
|
|
||||||
enum class LoadError {
|
enum class LoadError {
|
||||||
FileNotFound,
|
FileNotFound,
|
||||||
DlopenFailed,
|
DlopenFailed,
|
||||||
SymbolMissing,
|
SymbolMissing,
|
||||||
AbiMismatch,
|
AbiMismatch,
|
||||||
CreateFailed,
|
CreateFailed,
|
||||||
NotSupported, // platform does not support dlopen
|
NotSupported, // platform does not support dlopen
|
||||||
StateRejected, // new instance refused the serialized state
|
StateRejected, // new instance refused the serialized state
|
||||||
ActivationFailed, // on_load threw or readiness validation failed
|
ActivationFailed, // on_load threw or readiness validation failed
|
||||||
UnknownPlugin, // PluginManager: no plugin registered under that name
|
UnknownPlugin, // PluginManager: no plugin registered under that name
|
||||||
};
|
NameMismatch, // replacement reports a different registry name
|
||||||
|
};
|
||||||
|
|
||||||
[[nodiscard]] std::string_view to_string(LoadError e) noexcept;
|
[[nodiscard]] std::string_view to_string(LoadError e) noexcept;
|
||||||
|
|
||||||
// ── PluginLoader ──────────────────────────────────────────────────────────────
|
// ── PluginLoader
|
||||||
// Owns one plugin instance loaded from a shared library.
|
// ────────────────────────────────────────────────────────────── Owns one
|
||||||
//
|
// plugin instance loaded from a shared library.
|
||||||
// Hot-reload protocol:
|
//
|
||||||
// 1. The new .so (at the same canonical path) is copied to a temp file so
|
// Hot-reload protocol:
|
||||||
// dlopen gets a fresh inode even if the path was already cached.
|
// 1. The new .so (at the same canonical path) is copied to a temp file so
|
||||||
// 2. New instance is created and optional transfer_state() called (both
|
// dlopen gets a fresh inode even if the path was already cached.
|
||||||
// old and new instances are alive simultaneously at this point).
|
// 2. New instance is created and optional transfer_state() called (both
|
||||||
// 3. Old instance is destroyed and old handle is closed.
|
// old and new instances are alive simultaneously at this point).
|
||||||
//
|
// 3. Old instance is destroyed and old handle is closed.
|
||||||
// Thread safety: not thread-safe. Protect with external locking if needed.
|
//
|
||||||
|
// Thread safety: not thread-safe. Protect with external locking if needed.
|
||||||
|
|
||||||
class PluginLoader {
|
class PluginLoader
|
||||||
public:
|
{
|
||||||
[[nodiscard]] static std::expected<PluginLoader, LoadError>
|
public:
|
||||||
load(std::filesystem::path path);
|
|
||||||
|
|
||||||
~PluginLoader();
|
[[nodiscard]] static std::expected<PluginLoader, LoadError>
|
||||||
PluginLoader(PluginLoader&&) noexcept;
|
load(std::filesystem::path path);
|
||||||
PluginLoader& operator=(PluginLoader&&) noexcept;
|
|
||||||
PluginLoader(const PluginLoader&) = delete;
|
|
||||||
PluginLoader& operator=(const PluginLoader&) = delete;
|
|
||||||
|
|
||||||
[[nodiscard]] IPlugin* plugin() noexcept { return plugin_; }
|
~PluginLoader();
|
||||||
[[nodiscard]] const IPlugin* plugin() const noexcept { return plugin_; }
|
PluginLoader(PluginLoader&&) noexcept;
|
||||||
[[nodiscard]] const PluginInfo& info() const noexcept { return info_; }
|
PluginLoader& operator=(PluginLoader&&) noexcept;
|
||||||
[[nodiscard]] bool loaded() const noexcept { return handle_ != nullptr; }
|
PluginLoader(const PluginLoader&) = delete;
|
||||||
|
PluginLoader& operator=(const PluginLoader&) = delete;
|
||||||
|
|
||||||
IPlugin* operator->() noexcept { return plugin_; }
|
[[nodiscard]] IPlugin* plugin() noexcept { return plugin_; }
|
||||||
|
[[nodiscard]] const IPlugin* plugin() const noexcept
|
||||||
|
{
|
||||||
|
return plugin_;
|
||||||
|
}
|
||||||
|
[[nodiscard]] const PluginInfo& info() const noexcept
|
||||||
|
{
|
||||||
|
return info_;
|
||||||
|
}
|
||||||
|
[[nodiscard]] bool loaded() const noexcept
|
||||||
|
{
|
||||||
|
return handle_ != nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
// Hot-reload: copies current .so to a temp file (fresh inode), loads
|
IPlugin* operator->() noexcept { return plugin_; }
|
||||||
// it, transfers state, then destroys old instance and swaps handles.
|
|
||||||
// State transfer prefers the v2 serialize/deserialize protocol (old
|
|
||||||
// serializes, new deserializes with the old schema version); falls
|
|
||||||
// back to void_plugin_transfer_state; else no transfer.
|
|
||||||
[[nodiscard]] std::expected<void, LoadError> reload();
|
|
||||||
|
|
||||||
private:
|
// Hot-reload: copies current .so to a temp file (fresh inode),
|
||||||
PluginLoader() = default;
|
// loads it, transfers state, then destroys old instance and swaps
|
||||||
|
// handles. State transfer prefers the v2 serialize/deserialize
|
||||||
|
// protocol (old serializes, new deserializes with the old schema
|
||||||
|
// version); falls back to void_plugin_transfer_state; else no
|
||||||
|
// transfer.
|
||||||
|
[[nodiscard]] std::expected<void, LoadError> reload();
|
||||||
|
|
||||||
// Moves plugin state old -> new during a reload (v2 serialize/
|
private:
|
||||||
// deserialize, else transfer_state). Returns false only if the new
|
|
||||||
// instance rejects the state.
|
|
||||||
friend bool transfer_plugin_state(const PluginLoader& from,
|
|
||||||
PluginLoader& to);
|
|
||||||
|
|
||||||
void* handle_ {};
|
PluginLoader() = default;
|
||||||
IPlugin* plugin_ {};
|
|
||||||
destroy_fn destroy_ {};
|
|
||||||
transfer_fn transfer_ {};
|
|
||||||
ready_fn ready_ {};
|
|
||||||
state_version_fn state_version_{};
|
|
||||||
serialize_fn serialize_ {};
|
|
||||||
free_string_fn free_string_ {};
|
|
||||||
deserialize_fn deserialize_ {};
|
|
||||||
PluginInfo info_ {};
|
|
||||||
std::filesystem::path path_;
|
|
||||||
|
|
||||||
[[nodiscard]] std::expected<void, LoadError>
|
// Moves plugin state old -> new during a reload (v2 serialize/
|
||||||
load_from(const std::filesystem::path& path);
|
// deserialize, else transfer_state). Returns false only if the new
|
||||||
|
// instance rejects the state.
|
||||||
|
friend bool transfer_plugin_state(const PluginLoader& from,
|
||||||
|
PluginLoader& to);
|
||||||
|
|
||||||
void destroy_current() noexcept;
|
void* handle_{};
|
||||||
};
|
IPlugin* plugin_{};
|
||||||
|
destroy_fn destroy_{};
|
||||||
|
transfer_fn transfer_{};
|
||||||
|
ready_fn ready_{};
|
||||||
|
state_version_fn state_version_{};
|
||||||
|
serialize_fn serialize_{};
|
||||||
|
free_string_fn free_string_{};
|
||||||
|
deserialize_fn deserialize_{};
|
||||||
|
PluginInfo info_{};
|
||||||
|
std::filesystem::path path_;
|
||||||
|
|
||||||
|
[[nodiscard]] std::expected<void, LoadError>
|
||||||
|
load_from(const std::filesystem::path& path);
|
||||||
|
|
||||||
|
void destroy_current() noexcept;
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Void::Plugin
|
} // namespace Void::Plugin
|
||||||
@@ -87,7 +87,8 @@ namespace Void::Plugin
|
|||||||
std::function<std::string(std::string_view plugin_name)>
|
std::function<std::string(std::string_view plugin_name)>
|
||||||
config_provider;
|
config_provider;
|
||||||
// Host-specific contract checked after plugin activation and before
|
// Host-specific contract checked after plugin activation and before
|
||||||
// publication. A failed validation aborts load/reload transactionally.
|
// publication. A failed validation aborts load/reload
|
||||||
|
// transactionally.
|
||||||
std::function<bool(IPlugin&, const PluginInfo&)> instance_validator;
|
std::function<bool(IPlugin&, const PluginInfo&)> instance_validator;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -140,6 +141,16 @@ namespace Void::Plugin
|
|||||||
/// it alive until they drop.
|
/// it alive until they drop.
|
||||||
std::expected<void, LoadError> reload(std::string_view name);
|
std::expected<void, LoadError> reload(std::string_view name);
|
||||||
|
|
||||||
|
/// Replace `name` from an immutable new library path. The candidate
|
||||||
|
/// must report the same plugin name. It is configured, receives the
|
||||||
|
/// old state, activates and passes host validation before one
|
||||||
|
/// atomic publication. On any error the current instance, source
|
||||||
|
/// path and watcher remain unchanged. Pinned old handles remain
|
||||||
|
/// valid.
|
||||||
|
std::expected<void, LoadError>
|
||||||
|
replace(std::string_view name,
|
||||||
|
const std::filesystem::path& newPath);
|
||||||
|
|
||||||
/// Begin watching the plugin's file; reload automatically when
|
/// Begin watching the plugin's file; reload automatically when
|
||||||
/// it changes (debounced). Reload failures are logged and the
|
/// it changes (debounced). Reload failures are logged and the
|
||||||
/// old instance is kept.
|
/// old instance is kept.
|
||||||
@@ -191,11 +202,13 @@ namespace Void::Plugin
|
|||||||
struct Entry {
|
struct Entry {
|
||||||
std::filesystem::path path;
|
std::filesystem::path path;
|
||||||
std::atomic<std::shared_ptr<detail::Instance>> current;
|
std::atomic<std::shared_ptr<detail::Instance>> current;
|
||||||
|
bool watched{false};
|
||||||
};
|
};
|
||||||
|
|
||||||
Entry* find(std::string_view name) const;
|
Entry* find(std::string_view name) const;
|
||||||
std::expected<void, LoadError> reload_locked(Entry& entry,
|
std::expected<void, LoadError>
|
||||||
std::string_view name);
|
reload_locked(Entry& entry, std::string_view name,
|
||||||
|
const std::filesystem::path& sourcePath);
|
||||||
std::vector<std::function<void(std::string_view)>>
|
std::vector<std::function<void(std::string_view)>>
|
||||||
reload_callbacks_locked() const;
|
reload_callbacks_locked() const;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <chrono>
|
||||||
|
#include <memory>
|
||||||
|
#include <optional>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Process
|
||||||
|
{
|
||||||
|
/// Converts process signals into synchronous, deterministic waits.
|
||||||
|
/// Construct this before worker threads so the selected signals inherit a
|
||||||
|
/// blocked mask. A watcher must be destroyed on the thread that created it.
|
||||||
|
class SignalWatcher
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
/// An empty signal list watches SIGINT and SIGTERM.
|
||||||
|
[[nodiscard]] static Void::Result::Result<SignalWatcher>
|
||||||
|
create(std::vector<int> signals = {});
|
||||||
|
|
||||||
|
~SignalWatcher();
|
||||||
|
SignalWatcher(SignalWatcher&&) noexcept;
|
||||||
|
SignalWatcher& operator=(SignalWatcher&&) noexcept;
|
||||||
|
SignalWatcher(const SignalWatcher&) = delete;
|
||||||
|
SignalWatcher& operator=(const SignalWatcher&) = delete;
|
||||||
|
|
||||||
|
/// Wait for a configured signal. A zero timeout performs a poll;
|
||||||
|
/// milliseconds::max() waits indefinitely.
|
||||||
|
[[nodiscard]] Void::Result::Result<std::optional<int>>
|
||||||
|
wait(std::chrono::milliseconds timeout =
|
||||||
|
std::chrono::milliseconds::max());
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<std::optional<int>> poll();
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
struct Impl;
|
||||||
|
std::unique_ptr<Impl> m_impl;
|
||||||
|
explicit SignalWatcher(std::unique_ptr<Impl> impl) noexcept;
|
||||||
|
};
|
||||||
|
} // namespace Void::Process
|
||||||
+201
-106
@@ -6,121 +6,216 @@
|
|||||||
#include <span>
|
#include <span>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <string_view>
|
#include <string_view>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
namespace Void::Encoding::Base64
|
namespace Void::Encoding::Base64
|
||||||
{
|
{
|
||||||
|
|
||||||
namespace Detail
|
namespace Detail
|
||||||
{
|
{
|
||||||
constexpr std::string_view alphabet =
|
constexpr std::string_view alphabet =
|
||||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||||
|
|
||||||
constexpr std::string_view alphabet_url =
|
constexpr std::string_view alphabet_url =
|
||||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
||||||
|
|
||||||
[[nodiscard]] constexpr std::array<std::int8_t, 256>
|
[[nodiscard]] constexpr std::array<std::int8_t, 256>
|
||||||
make_decode_table(std::string_view alpha) noexcept
|
make_decode_table(std::string_view alpha) noexcept
|
||||||
{
|
{
|
||||||
std::array<std::int8_t, 256> t{};
|
std::array<std::int8_t, 256> t{};
|
||||||
t.fill(-1);
|
t.fill(-1);
|
||||||
for (std::size_t i = 0; i < 64; ++i) {
|
for (std::size_t i = 0; i < 64; ++i) {
|
||||||
t[static_cast<unsigned char>(alpha[i])] = static_cast<std::int8_t>(i);
|
t[static_cast<unsigned char>(alpha[i])] =
|
||||||
}
|
static_cast<std::int8_t>(i);
|
||||||
t[static_cast<unsigned char>('=')] = -2; // padding sentinel
|
}
|
||||||
return t;
|
t[static_cast<unsigned char>('=')] = -2; // padding sentinel
|
||||||
}
|
return t;
|
||||||
} // namespace Detail
|
}
|
||||||
|
} // namespace Detail
|
||||||
|
|
||||||
/// Encode bytes to standard Base64 (with padding).
|
/// Encode bytes to standard Base64 (with padding).
|
||||||
[[nodiscard]] inline std::string encode(std::span<const std::byte> data)
|
[[nodiscard]] inline std::string encode(std::span<const std::byte> data)
|
||||||
{
|
{
|
||||||
const auto& alpha = Detail::alphabet;
|
const auto& alpha = Detail::alphabet;
|
||||||
std::string out;
|
std::string out;
|
||||||
out.reserve(((data.size() + 2) / 3) * 4);
|
out.reserve(((data.size() + 2) / 3) * 4);
|
||||||
std::size_t i = 0;
|
std::size_t i = 0;
|
||||||
for (; i + 2 < data.size(); i += 3) {
|
for (; i + 2 < data.size(); i += 3) {
|
||||||
const auto a = static_cast<std::uint8_t>(data[i]);
|
const auto a = static_cast<std::uint8_t>(data[i]);
|
||||||
const auto b = static_cast<std::uint8_t>(data[i + 1]);
|
const auto b = static_cast<std::uint8_t>(data[i + 1]);
|
||||||
const auto c = static_cast<std::uint8_t>(data[i + 2]);
|
const auto c = static_cast<std::uint8_t>(data[i + 2]);
|
||||||
out += alpha[a >> 2];
|
out += alpha[a >> 2];
|
||||||
out += alpha[((a & 3) << 4) | (b >> 4)];
|
out += alpha[((a & 3) << 4) | (b >> 4)];
|
||||||
out += alpha[((b & 15) << 2) | (c >> 6)];
|
out += alpha[((b & 15) << 2) | (c >> 6)];
|
||||||
out += alpha[c & 63];
|
out += alpha[c & 63];
|
||||||
}
|
}
|
||||||
if (data.size() - i == 2) {
|
if (data.size() - i == 2) {
|
||||||
const auto a = static_cast<std::uint8_t>(data[i]);
|
const auto a = static_cast<std::uint8_t>(data[i]);
|
||||||
const auto b = static_cast<std::uint8_t>(data[i + 1]);
|
const auto b = static_cast<std::uint8_t>(data[i + 1]);
|
||||||
out += alpha[a >> 2];
|
out += alpha[a >> 2];
|
||||||
out += alpha[((a & 3) << 4) | (b >> 4)];
|
out += alpha[((a & 3) << 4) | (b >> 4)];
|
||||||
out += alpha[(b & 15) << 2];
|
out += alpha[(b & 15) << 2];
|
||||||
out += '=';
|
out += '=';
|
||||||
} else if (data.size() - i == 1) {
|
} else if (data.size() - i == 1) {
|
||||||
const auto a = static_cast<std::uint8_t>(data[i]);
|
const auto a = static_cast<std::uint8_t>(data[i]);
|
||||||
out += alpha[a >> 2];
|
out += alpha[a >> 2];
|
||||||
out += alpha[(a & 3) << 4];
|
out += alpha[(a & 3) << 4];
|
||||||
out += '=';
|
out += '=';
|
||||||
out += '=';
|
out += '=';
|
||||||
}
|
}
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Encode a string_view to standard Base64.
|
/// Encode an unsigned-byte view without forcing callers to reinterpret
|
||||||
[[nodiscard]] inline std::string encode(std::string_view s)
|
/// their binary buffers as text.
|
||||||
{
|
[[nodiscard]] inline std::string encode(std::span<const std::uint8_t> data)
|
||||||
return encode(std::as_bytes(std::span{s.data(), s.size()}));
|
{
|
||||||
}
|
return encode(std::as_bytes(data));
|
||||||
|
}
|
||||||
|
|
||||||
/// Encode to URL-safe Base64 (no padding).
|
/// Encode a string_view to standard Base64.
|
||||||
[[nodiscard]] inline std::string encode_url(std::string_view s)
|
[[nodiscard]] inline std::string encode(std::string_view s)
|
||||||
{
|
{
|
||||||
const auto& alpha = Detail::alphabet_url;
|
return encode(std::as_bytes(std::span{s.data(), s.size()}));
|
||||||
auto data = std::as_bytes(std::span{s.data(), s.size()});
|
}
|
||||||
std::string out;
|
|
||||||
out.reserve(((data.size() + 2) / 3) * 4);
|
|
||||||
std::size_t i = 0;
|
|
||||||
for (; i + 2 < data.size(); i += 3) {
|
|
||||||
const auto a = static_cast<std::uint8_t>(data[i]);
|
|
||||||
const auto b = static_cast<std::uint8_t>(data[i + 1]);
|
|
||||||
const auto c = static_cast<std::uint8_t>(data[i + 2]);
|
|
||||||
out += alpha[a >> 2];
|
|
||||||
out += alpha[((a & 3) << 4) | (b >> 4)];
|
|
||||||
out += alpha[((b & 15) << 2) | (c >> 6)];
|
|
||||||
out += alpha[c & 63];
|
|
||||||
}
|
|
||||||
if (data.size() - i == 2) {
|
|
||||||
const auto a = static_cast<std::uint8_t>(data[i]);
|
|
||||||
const auto b = static_cast<std::uint8_t>(data[i + 1]);
|
|
||||||
out += alpha[a >> 2];
|
|
||||||
out += alpha[((a & 3) << 4) | (b >> 4)];
|
|
||||||
out += alpha[(b & 15) << 2];
|
|
||||||
} else if (data.size() - i == 1) {
|
|
||||||
const auto a = static_cast<std::uint8_t>(data[i]);
|
|
||||||
out += alpha[a >> 2];
|
|
||||||
out += alpha[(a & 3) << 4];
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Decode standard Base64 (with or without padding). Returns nullopt on error.
|
/// Encode to URL-safe Base64 (no padding).
|
||||||
[[nodiscard]] inline std::optional<std::string> decode(std::string_view s)
|
[[nodiscard]] inline std::string encode_url(std::string_view s)
|
||||||
{
|
{
|
||||||
static constexpr auto table = Detail::make_decode_table(Detail::alphabet);
|
const auto& alpha = Detail::alphabet_url;
|
||||||
std::string out;
|
auto data = std::as_bytes(std::span{s.data(), s.size()});
|
||||||
out.reserve((s.size() / 4) * 3);
|
std::string out;
|
||||||
int buf = 0, bits = 0;
|
out.reserve(((data.size() + 2) / 3) * 4);
|
||||||
for (unsigned char c : s) {
|
std::size_t i = 0;
|
||||||
if (c == ' ' || c == '\n' || c == '\r' || c == '\t') continue;
|
for (; i + 2 < data.size(); i += 3) {
|
||||||
const std::int8_t v = table[c];
|
const auto a = static_cast<std::uint8_t>(data[i]);
|
||||||
if (v == -2) break; // padding
|
const auto b = static_cast<std::uint8_t>(data[i + 1]);
|
||||||
if (v == -1) return std::nullopt;
|
const auto c = static_cast<std::uint8_t>(data[i + 2]);
|
||||||
buf = (buf << 6) | v;
|
out += alpha[a >> 2];
|
||||||
bits += 6;
|
out += alpha[((a & 3) << 4) | (b >> 4)];
|
||||||
if (bits >= 8) {
|
out += alpha[((b & 15) << 2) | (c >> 6)];
|
||||||
bits -= 8;
|
out += alpha[c & 63];
|
||||||
out += static_cast<char>((buf >> bits) & 0xFF);
|
}
|
||||||
}
|
if (data.size() - i == 2) {
|
||||||
}
|
const auto a = static_cast<std::uint8_t>(data[i]);
|
||||||
return out;
|
const auto b = static_cast<std::uint8_t>(data[i + 1]);
|
||||||
}
|
out += alpha[a >> 2];
|
||||||
|
out += alpha[((a & 3) << 4) | (b >> 4)];
|
||||||
|
out += alpha[(b & 15) << 2];
|
||||||
|
} else if (data.size() - i == 1) {
|
||||||
|
const auto a = static_cast<std::uint8_t>(data[i]);
|
||||||
|
out += alpha[a >> 2];
|
||||||
|
out += alpha[(a & 3) << 4];
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decode canonical URL-safe Base64 without padding. Returns nullopt for
|
||||||
|
/// padding, invalid characters, impossible lengths, or non-zero trailing
|
||||||
|
/// bits.
|
||||||
|
[[nodiscard]] inline std::optional<std::string>
|
||||||
|
decode_url(std::string_view s)
|
||||||
|
{
|
||||||
|
static constexpr auto table =
|
||||||
|
Detail::make_decode_table(Detail::alphabet_url);
|
||||||
|
if (s.size() % 4 == 1 || s.find('=') != std::string_view::npos) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
std::string out;
|
||||||
|
out.reserve((s.size() * 3) / 4);
|
||||||
|
std::uint32_t buffer = 0;
|
||||||
|
int bits = 0;
|
||||||
|
for (const char encoded : s) {
|
||||||
|
const auto character = static_cast<unsigned char>(encoded);
|
||||||
|
const std::int8_t value = table[character];
|
||||||
|
if (value < 0) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
buffer = (buffer << 6) | static_cast<std::uint32_t>(value);
|
||||||
|
bits += 6;
|
||||||
|
if (bits >= 8) {
|
||||||
|
bits -= 8;
|
||||||
|
out += static_cast<char>((buffer >> bits) & 0xFFU);
|
||||||
|
buffer &= bits == 0 ? 0U : ((1U << bits) - 1U);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (bits != 0 && buffer != 0) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decode standard Base64 (with or without padding). Returns nullopt on
|
||||||
|
/// error.
|
||||||
|
[[nodiscard]] inline std::optional<std::string> decode(std::string_view s)
|
||||||
|
{
|
||||||
|
static constexpr auto table =
|
||||||
|
Detail::make_decode_table(Detail::alphabet);
|
||||||
|
std::string out;
|
||||||
|
out.reserve((s.size() / 4) * 3);
|
||||||
|
std::uint32_t buffer = 0;
|
||||||
|
int bits = 0;
|
||||||
|
std::size_t symbols = 0;
|
||||||
|
std::size_t padding = 0;
|
||||||
|
bool saw_padding = false;
|
||||||
|
for (const char encoded : s) {
|
||||||
|
const auto character = static_cast<unsigned char>(encoded);
|
||||||
|
if (character == ' ' || character == '\n' || character == '\r' ||
|
||||||
|
character == '\t') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (character == '=') {
|
||||||
|
saw_padding = true;
|
||||||
|
if (++padding > 2) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (saw_padding) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::int8_t value = table[character];
|
||||||
|
if (value < 0) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
buffer = (buffer << 6) | static_cast<std::uint32_t>(value);
|
||||||
|
++symbols;
|
||||||
|
bits += 6;
|
||||||
|
if (bits >= 8) {
|
||||||
|
bits -= 8;
|
||||||
|
out += static_cast<char>((buffer >> bits) & 0xFFU);
|
||||||
|
buffer &= bits == 0 ? 0U : ((1U << bits) - 1U);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::size_t remainder = symbols % 4;
|
||||||
|
if (remainder == 1) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
const std::size_t expected_padding = remainder == 0 ? 0 : 4 - remainder;
|
||||||
|
if (padding != 0 && padding != expected_padding) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
if (bits != 0 && buffer != 0) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decode standard Base64 into an explicitly binary buffer. This is the
|
||||||
|
/// preferred overload for protocol, cryptographic, and file-format data.
|
||||||
|
[[nodiscard]] inline std::optional<std::vector<std::byte>>
|
||||||
|
decode_bytes(std::string_view s)
|
||||||
|
{
|
||||||
|
const auto decoded = decode(s);
|
||||||
|
if (!decoded) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto bytes =
|
||||||
|
std::as_bytes(std::span{decoded->data(), decoded->size()});
|
||||||
|
return std::vector<std::byte>{bytes.begin(), bytes.end()};
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace Void::Encoding::Base64
|
} // namespace Void::Encoding::Base64
|
||||||
+86
-54
@@ -5,67 +5,99 @@
|
|||||||
#include <span>
|
#include <span>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <string_view>
|
#include <string_view>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
namespace Void::Encoding::Hex
|
namespace Void::Encoding::Hex
|
||||||
{
|
{
|
||||||
|
|
||||||
/// Encode bytes to lowercase hex string.
|
/// Encode bytes to lowercase hex string.
|
||||||
[[nodiscard]] inline std::string encode(std::span<const std::byte> data)
|
[[nodiscard]] inline std::string encode(std::span<const std::byte> data)
|
||||||
{
|
{
|
||||||
constexpr std::string_view digits = "0123456789abcdef";
|
constexpr std::string_view digits = "0123456789abcdef";
|
||||||
std::string out;
|
std::string out;
|
||||||
out.reserve(data.size() * 2);
|
out.reserve(data.size() * 2);
|
||||||
for (auto b : data) {
|
for (auto b : data) {
|
||||||
const auto v = static_cast<std::uint8_t>(b);
|
const auto v = static_cast<std::uint8_t>(b);
|
||||||
out += digits[v >> 4];
|
out += digits[v >> 4];
|
||||||
out += digits[v & 0xF];
|
out += digits[v & 0xF];
|
||||||
}
|
}
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
[[nodiscard]] inline std::string encode(std::string_view s)
|
/// Encode an unsigned-byte view without treating binary data as text.
|
||||||
{
|
[[nodiscard]] inline std::string encode(std::span<const std::uint8_t> data)
|
||||||
return encode(std::as_bytes(std::span{s.data(), s.size()}));
|
{
|
||||||
}
|
return encode(std::as_bytes(data));
|
||||||
|
}
|
||||||
|
|
||||||
/// Decode hex string to bytes. Returns nullopt on invalid input.
|
[[nodiscard]] inline std::string encode(std::string_view s)
|
||||||
[[nodiscard]] inline std::optional<std::string> decode(std::string_view s)
|
{
|
||||||
{
|
return encode(std::as_bytes(std::span{s.data(), s.size()}));
|
||||||
if (s.size() % 2 != 0) return std::nullopt;
|
}
|
||||||
auto hex_val = [](char c) -> std::optional<std::uint8_t> {
|
|
||||||
if (c >= '0' && c <= '9') return static_cast<std::uint8_t>(c - '0');
|
|
||||||
if (c >= 'a' && c <= 'f') return static_cast<std::uint8_t>(c - 'a' + 10);
|
|
||||||
if (c >= 'A' && c <= 'F') return static_cast<std::uint8_t>(c - 'A' + 10);
|
|
||||||
return std::nullopt;
|
|
||||||
};
|
|
||||||
std::string out;
|
|
||||||
out.reserve(s.size() / 2);
|
|
||||||
for (std::size_t i = 0; i < s.size(); i += 2) {
|
|
||||||
auto hi = hex_val(s[i]);
|
|
||||||
auto lo = hex_val(s[i + 1]);
|
|
||||||
if (!hi || !lo) return std::nullopt;
|
|
||||||
out += static_cast<char>((*hi << 4) | *lo);
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Uppercase hex encoding.
|
/// Decode hex string to bytes. Returns nullopt on invalid input.
|
||||||
[[nodiscard]] inline std::string encode_upper(std::span<const std::byte> data)
|
[[nodiscard]] inline std::optional<std::string> decode(std::string_view s)
|
||||||
{
|
{
|
||||||
constexpr std::string_view digits = "0123456789ABCDEF";
|
if (s.size() % 2 != 0) {
|
||||||
std::string out;
|
return std::nullopt;
|
||||||
out.reserve(data.size() * 2);
|
}
|
||||||
for (auto b : data) {
|
auto hex_val = [](char c) -> std::optional<std::uint8_t> {
|
||||||
const auto v = static_cast<std::uint8_t>(b);
|
if (c >= '0' && c <= '9') {
|
||||||
out += digits[v >> 4];
|
return static_cast<std::uint8_t>(c - '0');
|
||||||
out += digits[v & 0xF];
|
}
|
||||||
}
|
if (c >= 'a' && c <= 'f') {
|
||||||
return out;
|
return static_cast<std::uint8_t>(c - 'a' + 10);
|
||||||
}
|
}
|
||||||
|
if (c >= 'A' && c <= 'F') {
|
||||||
|
return static_cast<std::uint8_t>(c - 'A' + 10);
|
||||||
|
}
|
||||||
|
return std::nullopt;
|
||||||
|
};
|
||||||
|
std::string out;
|
||||||
|
out.reserve(s.size() / 2);
|
||||||
|
for (std::size_t i = 0; i < s.size(); i += 2) {
|
||||||
|
auto hi = hex_val(s[i]);
|
||||||
|
auto lo = hex_val(s[i + 1]);
|
||||||
|
if (!hi || !lo) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
out += static_cast<char>((*hi << 4) | *lo);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
[[nodiscard]] inline std::string encode_upper(std::string_view s)
|
/// Decode hexadecimal text into an explicitly binary buffer.
|
||||||
{
|
[[nodiscard]] inline std::optional<std::vector<std::byte>>
|
||||||
return encode_upper(std::as_bytes(std::span{s.data(), s.size()}));
|
decode_bytes(std::string_view s)
|
||||||
}
|
{
|
||||||
|
const auto decoded = decode(s);
|
||||||
|
if (!decoded) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto bytes =
|
||||||
|
std::as_bytes(std::span{decoded->data(), decoded->size()});
|
||||||
|
return std::vector<std::byte>{bytes.begin(), bytes.end()};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Uppercase hex encoding.
|
||||||
|
[[nodiscard]] inline std::string
|
||||||
|
encode_upper(std::span<const std::byte> data)
|
||||||
|
{
|
||||||
|
constexpr std::string_view digits = "0123456789ABCDEF";
|
||||||
|
std::string out;
|
||||||
|
out.reserve(data.size() * 2);
|
||||||
|
for (auto b : data) {
|
||||||
|
const auto v = static_cast<std::uint8_t>(b);
|
||||||
|
out += digits[v >> 4];
|
||||||
|
out += digits[v & 0xF];
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] inline std::string encode_upper(std::string_view s)
|
||||||
|
{
|
||||||
|
return encode_upper(std::as_bytes(std::span{s.data(), s.size()}));
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace Void::Encoding::Hex
|
} // namespace Void::Encoding::Hex
|
||||||
+571
-101
@@ -1,132 +1,602 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#include <charconv>
|
||||||
#include <compare>
|
#include <compare>
|
||||||
#include <cstdlib>
|
|
||||||
#include <format>
|
#include <format>
|
||||||
|
#include <limits>
|
||||||
#include <optional>
|
#include <optional>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <string_view>
|
#include <string_view>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
namespace Void::Semver
|
namespace Void::Semver
|
||||||
{
|
{
|
||||||
|
|
||||||
// ── Version ───────────────────────────────────────────────────────────────────
|
namespace Detail
|
||||||
|
{
|
||||||
|
[[nodiscard]] constexpr bool is_digit(char value) noexcept
|
||||||
|
{
|
||||||
|
return value >= '0' && value <= '9';
|
||||||
|
}
|
||||||
|
|
||||||
struct Version
|
[[nodiscard]] constexpr bool
|
||||||
{
|
is_identifier_character(char value) noexcept
|
||||||
unsigned major{0};
|
{
|
||||||
unsigned minor{0};
|
return is_digit(value) || (value >= 'A' && value <= 'Z') ||
|
||||||
unsigned patch{0};
|
(value >= 'a' && value <= 'z') || value == '-';
|
||||||
std::string pre_release; // e.g. "alpha.1"
|
}
|
||||||
std::string build; // e.g. "20240101"
|
|
||||||
|
|
||||||
[[nodiscard]] std::string to_string() const
|
[[nodiscard]] inline bool
|
||||||
{
|
is_numeric(std::string_view identifier) noexcept
|
||||||
std::string s = std::format("{}.{}.{}", major, minor, patch);
|
{
|
||||||
if (!pre_release.empty()) { s += '-'; s += pre_release; }
|
if (identifier.empty()) {
|
||||||
if (!build.empty()) { s += '+'; s += build; }
|
return false;
|
||||||
return s;
|
}
|
||||||
}
|
for (const char value : identifier) {
|
||||||
|
if (!is_digit(value)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
// Precedence comparison per semver spec (build metadata ignored).
|
[[nodiscard]] inline std::strong_ordering
|
||||||
[[nodiscard]] std::strong_ordering
|
compare_identifier(std::string_view left,
|
||||||
operator<=>(const Version& o) const noexcept
|
std::string_view right) noexcept
|
||||||
{
|
{
|
||||||
if (auto c = major <=> o.major; c != 0) return c;
|
const bool left_numeric = is_numeric(left);
|
||||||
if (auto c = minor <=> o.minor; c != 0) return c;
|
const bool right_numeric = is_numeric(right);
|
||||||
if (auto c = patch <=> o.patch; c != 0) return c;
|
if (left_numeric && right_numeric) {
|
||||||
// No pre-release > has pre-release
|
if (left.size() != right.size()) {
|
||||||
const bool l_pre = !pre_release.empty();
|
return left.size() < right.size()
|
||||||
const bool r_pre = !o.pre_release.empty();
|
? std::strong_ordering::less
|
||||||
if (!l_pre && r_pre) return std::strong_ordering::greater;
|
: std::strong_ordering::greater;
|
||||||
if (l_pre && !r_pre) return std::strong_ordering::less;
|
}
|
||||||
// Both have pre-release — lexicographic (simplified)
|
return left <=> right;
|
||||||
if (auto c = pre_release <=> o.pre_release; c != 0) {
|
}
|
||||||
return c < 0 ? std::strong_ordering::less
|
if (left_numeric != right_numeric) {
|
||||||
: std::strong_ordering::greater;
|
return left_numeric ? std::strong_ordering::less
|
||||||
}
|
: std::strong_ordering::greater;
|
||||||
return std::strong_ordering::equal;
|
}
|
||||||
}
|
return left <=> right;
|
||||||
|
}
|
||||||
|
|
||||||
[[nodiscard]] bool operator==(const Version& o) const noexcept
|
[[nodiscard]] inline std::strong_ordering
|
||||||
{
|
compare_prerelease(std::string_view left,
|
||||||
return major == o.major && minor == o.minor && patch == o.patch &&
|
std::string_view right) noexcept
|
||||||
pre_release == o.pre_release;
|
{
|
||||||
}
|
std::size_t left_begin = 0;
|
||||||
|
std::size_t right_begin = 0;
|
||||||
|
for (;;) {
|
||||||
|
const auto left_end = left.find('.', left_begin);
|
||||||
|
const auto right_end = right.find('.', right_begin);
|
||||||
|
const auto left_id =
|
||||||
|
left.substr(left_begin, left_end == std::string_view::npos
|
||||||
|
? std::string_view::npos
|
||||||
|
: left_end - left_begin);
|
||||||
|
const auto right_id = right.substr(
|
||||||
|
right_begin, right_end == std::string_view::npos
|
||||||
|
? std::string_view::npos
|
||||||
|
: right_end - right_begin);
|
||||||
|
if (const auto comparison =
|
||||||
|
compare_identifier(left_id, right_id);
|
||||||
|
comparison != 0) {
|
||||||
|
return comparison;
|
||||||
|
}
|
||||||
|
const bool left_done = left_end == std::string_view::npos;
|
||||||
|
const bool right_done = right_end == std::string_view::npos;
|
||||||
|
if (left_done || right_done) {
|
||||||
|
if (left_done == right_done) {
|
||||||
|
return std::strong_ordering::equal;
|
||||||
|
}
|
||||||
|
return left_done ? std::strong_ordering::less
|
||||||
|
: std::strong_ordering::greater;
|
||||||
|
}
|
||||||
|
left_begin = left_end + 1;
|
||||||
|
right_begin = right_end + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Is this version compatible with `required`? (same major, >= minor.patch)
|
[[nodiscard]] inline bool
|
||||||
[[nodiscard]] bool compatible_with(const Version& required) const noexcept
|
valid_identifiers(std::string_view value,
|
||||||
{
|
bool reject_numeric_leading_zero) noexcept
|
||||||
if (major != required.major) return false;
|
{
|
||||||
return (*this <=> required) >= 0;
|
if (value.empty()) {
|
||||||
}
|
return false;
|
||||||
|
}
|
||||||
|
std::size_t begin = 0;
|
||||||
|
for (;;) {
|
||||||
|
const auto end = value.find('.', begin);
|
||||||
|
const auto identifier =
|
||||||
|
value.substr(begin, end == std::string_view::npos
|
||||||
|
? std::string_view::npos
|
||||||
|
: end - begin);
|
||||||
|
if (identifier.empty()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for (const char character : identifier) {
|
||||||
|
if (!is_identifier_character(character)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (reject_numeric_leading_zero && identifier.size() > 1 &&
|
||||||
|
identifier.front() == '0' && is_numeric(identifier)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (end == std::string_view::npos) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
begin = end + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
[[nodiscard]] bool is_stable() const noexcept
|
[[nodiscard]] inline bool parse_component(std::string_view value,
|
||||||
{
|
unsigned& output) noexcept
|
||||||
return major >= 1 && pre_release.empty();
|
{
|
||||||
}
|
if (value.empty() || (value.size() > 1 && value.front() == '0')) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
unsigned long long parsed = 0;
|
||||||
|
const auto [end, error] = std::from_chars(
|
||||||
|
value.data(), value.data() + value.size(), parsed);
|
||||||
|
if (error != std::errc{} || end != value.data() + value.size() ||
|
||||||
|
parsed > std::numeric_limits<unsigned>::max()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
output = static_cast<unsigned>(parsed);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
[[nodiscard]] Version bumped_major() const noexcept
|
[[nodiscard]] constexpr std::string_view
|
||||||
{
|
trim(std::string_view value) noexcept
|
||||||
return {major + 1, 0, 0};
|
{
|
||||||
}
|
while (!value.empty() &&
|
||||||
|
(value.front() == ' ' || value.front() == '\t' ||
|
||||||
|
value.front() == '\r' || value.front() == '\n')) {
|
||||||
|
value.remove_prefix(1);
|
||||||
|
}
|
||||||
|
while (!value.empty() &&
|
||||||
|
(value.back() == ' ' || value.back() == '\t' ||
|
||||||
|
value.back() == '\r' || value.back() == '\n')) {
|
||||||
|
value.remove_suffix(1);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
} // namespace Detail
|
||||||
|
|
||||||
[[nodiscard]] Version bumped_minor() const noexcept
|
struct Version {
|
||||||
{
|
unsigned major{0};
|
||||||
return {major, minor + 1, 0};
|
unsigned minor{0};
|
||||||
}
|
unsigned patch{0};
|
||||||
|
std::string pre_release;
|
||||||
|
std::string build;
|
||||||
|
|
||||||
[[nodiscard]] Version bumped_patch() const noexcept
|
[[nodiscard]] std::string to_string() const
|
||||||
{
|
{
|
||||||
return {major, minor, patch + 1};
|
std::string value =
|
||||||
}
|
std::format("{}.{}.{}", major, minor, patch);
|
||||||
};
|
if (!pre_release.empty()) {
|
||||||
|
value += '-';
|
||||||
|
value += pre_release;
|
||||||
|
}
|
||||||
|
if (!build.empty()) {
|
||||||
|
value += '+';
|
||||||
|
value += build;
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
// ── Parsing ───────────────────────────────────────────────────────────────────
|
[[nodiscard]] std::strong_ordering
|
||||||
|
operator<=>(const Version& other) const noexcept
|
||||||
|
{
|
||||||
|
if (const auto comparison = major <=> other.major;
|
||||||
|
comparison != 0) {
|
||||||
|
return comparison;
|
||||||
|
}
|
||||||
|
if (const auto comparison = minor <=> other.minor;
|
||||||
|
comparison != 0) {
|
||||||
|
return comparison;
|
||||||
|
}
|
||||||
|
if (const auto comparison = patch <=> other.patch;
|
||||||
|
comparison != 0) {
|
||||||
|
return comparison;
|
||||||
|
}
|
||||||
|
if (pre_release.empty() != other.pre_release.empty()) {
|
||||||
|
return pre_release.empty() ? std::strong_ordering::greater
|
||||||
|
: std::strong_ordering::less;
|
||||||
|
}
|
||||||
|
if (pre_release.empty()) {
|
||||||
|
return std::strong_ordering::equal;
|
||||||
|
}
|
||||||
|
return Detail::compare_prerelease(pre_release,
|
||||||
|
other.pre_release);
|
||||||
|
}
|
||||||
|
|
||||||
[[nodiscard]] inline std::optional<Version> parse(std::string_view s)
|
[[nodiscard]] bool operator==(const Version& other) const noexcept
|
||||||
{
|
{
|
||||||
Version v;
|
return major == other.major && minor == other.minor &&
|
||||||
|
patch == other.patch && pre_release == other.pre_release;
|
||||||
|
}
|
||||||
|
|
||||||
auto parse_uint = [](std::string_view sv, unsigned& out) -> bool {
|
[[nodiscard]] bool
|
||||||
if (sv.empty()) return false;
|
compatible_with(const Version& required) const noexcept
|
||||||
out = 0;
|
{
|
||||||
for (char c : sv) {
|
return major == required.major && (*this <=> required) >= 0;
|
||||||
if (c < '0' || c > '9') return false;
|
}
|
||||||
out = out * 10 + static_cast<unsigned>(c - '0');
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
};
|
|
||||||
|
|
||||||
// Optional leading 'v'
|
[[nodiscard]] bool is_stable() const noexcept
|
||||||
if (!s.empty() && (s[0] == 'v' || s[0] == 'V')) s.remove_prefix(1);
|
{
|
||||||
|
return major >= 1 && pre_release.empty();
|
||||||
|
}
|
||||||
|
|
||||||
// Split build metadata first
|
[[nodiscard]] Version bumped_major() const noexcept
|
||||||
const auto plus = s.find('+');
|
{
|
||||||
if (plus != std::string_view::npos) {
|
return Version{.major = major + 1,
|
||||||
v.build = std::string{s.substr(plus + 1)};
|
.minor = 0,
|
||||||
s = s.substr(0, plus);
|
.patch = 0,
|
||||||
}
|
.pre_release = {},
|
||||||
|
.build = {}};
|
||||||
|
}
|
||||||
|
|
||||||
// Split pre-release
|
[[nodiscard]] Version bumped_minor() const noexcept
|
||||||
const auto dash = s.find('-');
|
{
|
||||||
if (dash != std::string_view::npos) {
|
return Version{.major = major,
|
||||||
v.pre_release = std::string{s.substr(dash + 1)};
|
.minor = minor + 1,
|
||||||
s = s.substr(0, dash);
|
.patch = 0,
|
||||||
}
|
.pre_release = {},
|
||||||
|
.build = {}};
|
||||||
|
}
|
||||||
|
|
||||||
// Major.minor.patch
|
[[nodiscard]] Version bumped_patch() const noexcept
|
||||||
const auto d1 = s.find('.');
|
{
|
||||||
if (d1 == std::string_view::npos) return std::nullopt;
|
return Version{.major = major,
|
||||||
if (!parse_uint(s.substr(0, d1), v.major)) return std::nullopt;
|
.minor = minor,
|
||||||
s = s.substr(d1 + 1);
|
.patch = patch + 1,
|
||||||
|
.pre_release = {},
|
||||||
|
.build = {}};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const auto d2 = s.find('.');
|
namespace Detail
|
||||||
if (d2 == std::string_view::npos) return std::nullopt;
|
{
|
||||||
if (!parse_uint(s.substr(0, d2), v.minor)) return std::nullopt;
|
[[nodiscard]] inline std::optional<Version>
|
||||||
if (!parse_uint(s.substr(d2 + 1), v.patch)) return std::nullopt;
|
parse_version(std::string_view value, bool allow_v_prefix)
|
||||||
|
{
|
||||||
|
if (allow_v_prefix && !value.empty() &&
|
||||||
|
(value.front() == 'v' || value.front() == 'V')) {
|
||||||
|
value.remove_prefix(1);
|
||||||
|
}
|
||||||
|
if (value.empty()) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
return v;
|
Version version;
|
||||||
}
|
const auto plus = value.find('+');
|
||||||
|
if (plus != std::string_view::npos) {
|
||||||
|
if (value.find('+', plus + 1) != std::string_view::npos) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
const auto metadata = value.substr(plus + 1);
|
||||||
|
if (!valid_identifiers(metadata, false)) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
version.build = std::string{metadata};
|
||||||
|
value = value.substr(0, plus);
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto dash = value.find('-');
|
||||||
|
if (dash != std::string_view::npos) {
|
||||||
|
const auto prerelease = value.substr(dash + 1);
|
||||||
|
if (!valid_identifiers(prerelease, true)) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
version.pre_release = std::string{prerelease};
|
||||||
|
value = value.substr(0, dash);
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto first_dot = value.find('.');
|
||||||
|
if (first_dot == std::string_view::npos) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
const auto second_dot = value.find('.', first_dot + 1);
|
||||||
|
if (second_dot == std::string_view::npos ||
|
||||||
|
value.find('.', second_dot + 1) != std::string_view::npos) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
if (!parse_component(value.substr(0, first_dot), version.major) ||
|
||||||
|
!parse_component(
|
||||||
|
value.substr(first_dot + 1, second_dot - first_dot - 1),
|
||||||
|
version.minor) ||
|
||||||
|
!parse_component(value.substr(second_dot + 1), version.patch)) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return version;
|
||||||
|
}
|
||||||
|
} // namespace Detail
|
||||||
|
|
||||||
|
/// Parse SemVer while retaining the historic optional `v` prefix.
|
||||||
|
[[nodiscard]] inline std::optional<Version> parse(std::string_view value)
|
||||||
|
{
|
||||||
|
return Detail::parse_version(value, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse exactly according to SemVer 2.0.0 (no leading `v`).
|
||||||
|
[[nodiscard]] inline std::optional<Version>
|
||||||
|
parse_strict(std::string_view value)
|
||||||
|
{
|
||||||
|
return Detail::parse_version(value, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
class VersionRange
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
[[nodiscard]] static std::optional<VersionRange>
|
||||||
|
parse(std::string_view expression)
|
||||||
|
{
|
||||||
|
VersionRange result;
|
||||||
|
expression = Detail::trim(expression);
|
||||||
|
if (expression.empty() || expression == "*") {
|
||||||
|
result.m_alternatives.emplace_back();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t clause_begin = 0;
|
||||||
|
for (;;) {
|
||||||
|
const auto separator = expression.find("||", clause_begin);
|
||||||
|
const auto clause_text = Detail::trim(expression.substr(
|
||||||
|
clause_begin, separator == std::string_view::npos
|
||||||
|
? std::string_view::npos
|
||||||
|
: separator - clause_begin));
|
||||||
|
if (clause_text.empty()) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
Clause clause;
|
||||||
|
std::size_t token_begin = 0;
|
||||||
|
while (token_begin < clause_text.size()) {
|
||||||
|
while (token_begin < clause_text.size() &&
|
||||||
|
(clause_text[token_begin] == ' ' ||
|
||||||
|
clause_text[token_begin] == '\t')) {
|
||||||
|
++token_begin;
|
||||||
|
}
|
||||||
|
if (token_begin == clause_text.size()) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
auto token_end =
|
||||||
|
clause_text.find_first_of(" \t", token_begin);
|
||||||
|
if (token_end == std::string_view::npos) {
|
||||||
|
token_end = clause_text.size();
|
||||||
|
}
|
||||||
|
if (!append_token(
|
||||||
|
clause,
|
||||||
|
clause_text.substr(token_begin,
|
||||||
|
token_end - token_begin))) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
token_begin = token_end;
|
||||||
|
}
|
||||||
|
result.m_alternatives.push_back(std::move(clause));
|
||||||
|
if (separator == std::string_view::npos) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
clause_begin = separator + 2;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool contains(const Version& version) const noexcept
|
||||||
|
{
|
||||||
|
for (const auto& clause : m_alternatives) {
|
||||||
|
bool matches = true;
|
||||||
|
for (const auto& comparator : clause) {
|
||||||
|
if (!comparator.matches(version)) {
|
||||||
|
matches = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (matches) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
enum class Operation {
|
||||||
|
Equal,
|
||||||
|
Greater,
|
||||||
|
GreaterEqual,
|
||||||
|
Less,
|
||||||
|
LessEqual
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Comparator {
|
||||||
|
Operation operation{Operation::Equal};
|
||||||
|
Version version;
|
||||||
|
|
||||||
|
[[nodiscard]] bool
|
||||||
|
matches(const Version& candidate) const noexcept
|
||||||
|
{
|
||||||
|
const auto comparison = candidate <=> version;
|
||||||
|
switch (operation) {
|
||||||
|
case Operation::Equal:
|
||||||
|
return comparison == 0;
|
||||||
|
case Operation::Greater:
|
||||||
|
return comparison > 0;
|
||||||
|
case Operation::GreaterEqual:
|
||||||
|
return comparison >= 0;
|
||||||
|
case Operation::Less:
|
||||||
|
return comparison < 0;
|
||||||
|
case Operation::LessEqual:
|
||||||
|
return comparison <= 0;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
using Clause = std::vector<Comparator>;
|
||||||
|
std::vector<Clause> m_alternatives;
|
||||||
|
|
||||||
|
[[nodiscard]] static bool append_token(Clause& clause,
|
||||||
|
std::string_view token)
|
||||||
|
{
|
||||||
|
if (token == "*") {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (token.starts_with('^') || token.starts_with('~')) {
|
||||||
|
const char kind = token.front();
|
||||||
|
token.remove_prefix(1);
|
||||||
|
const auto lower = parse_strict(token);
|
||||||
|
if (!lower) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Version upper;
|
||||||
|
if (kind == '~') {
|
||||||
|
if (lower->minor ==
|
||||||
|
std::numeric_limits<unsigned>::max()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
upper = Version{.major = lower->major,
|
||||||
|
.minor = lower->minor + 1,
|
||||||
|
.patch = 0,
|
||||||
|
.pre_release = {},
|
||||||
|
.build = {}};
|
||||||
|
} else if (lower->major > 0) {
|
||||||
|
if (lower->major ==
|
||||||
|
std::numeric_limits<unsigned>::max()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
upper = Version{.major = lower->major + 1,
|
||||||
|
.minor = 0,
|
||||||
|
.patch = 0,
|
||||||
|
.pre_release = {},
|
||||||
|
.build = {}};
|
||||||
|
} else if (lower->minor > 0) {
|
||||||
|
if (lower->minor ==
|
||||||
|
std::numeric_limits<unsigned>::max()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
upper = Version{.major = 0,
|
||||||
|
.minor = lower->minor + 1,
|
||||||
|
.patch = 0,
|
||||||
|
.pre_release = {},
|
||||||
|
.build = {}};
|
||||||
|
} else {
|
||||||
|
if (lower->patch ==
|
||||||
|
std::numeric_limits<unsigned>::max()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
upper = Version{.major = 0,
|
||||||
|
.minor = 0,
|
||||||
|
.patch = lower->patch + 1,
|
||||||
|
.pre_release = {},
|
||||||
|
.build = {}};
|
||||||
|
}
|
||||||
|
clause.push_back({Operation::GreaterEqual, *lower});
|
||||||
|
clause.push_back({Operation::Less, std::move(upper)});
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (token.find_first_of("xX*") != std::string_view::npos) {
|
||||||
|
return append_wildcard(clause, token);
|
||||||
|
}
|
||||||
|
|
||||||
|
Operation operation = Operation::Equal;
|
||||||
|
if (token.starts_with(">=")) {
|
||||||
|
operation = Operation::GreaterEqual;
|
||||||
|
token.remove_prefix(2);
|
||||||
|
} else if (token.starts_with("<=")) {
|
||||||
|
operation = Operation::LessEqual;
|
||||||
|
token.remove_prefix(2);
|
||||||
|
} else if (token.starts_with('>')) {
|
||||||
|
operation = Operation::Greater;
|
||||||
|
token.remove_prefix(1);
|
||||||
|
} else if (token.starts_with('<')) {
|
||||||
|
operation = Operation::Less;
|
||||||
|
token.remove_prefix(1);
|
||||||
|
} else if (token.starts_with('=')) {
|
||||||
|
token.remove_prefix(1);
|
||||||
|
}
|
||||||
|
const auto version = parse_strict(token);
|
||||||
|
if (!version) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
clause.push_back({operation, *version});
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] static bool append_wildcard(Clause& clause,
|
||||||
|
std::string_view token)
|
||||||
|
{
|
||||||
|
const auto first_dot = token.find('.');
|
||||||
|
if (first_dot == std::string_view::npos) {
|
||||||
|
return token == "x" || token == "X" || token == "*";
|
||||||
|
}
|
||||||
|
const auto second_dot = token.find('.', first_dot + 1);
|
||||||
|
unsigned major = 0;
|
||||||
|
if (!Detail::parse_component(token.substr(0, first_dot),
|
||||||
|
major)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const auto minor_text = token.substr(
|
||||||
|
first_dot + 1, second_dot == std::string_view::npos
|
||||||
|
? std::string_view::npos
|
||||||
|
: second_dot - first_dot - 1);
|
||||||
|
if (minor_text == "x" || minor_text == "X" ||
|
||||||
|
minor_text == "*") {
|
||||||
|
if (second_dot != std::string_view::npos) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (major == std::numeric_limits<unsigned>::max()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
clause.push_back(
|
||||||
|
{Operation::GreaterEqual, Version{.major = major,
|
||||||
|
.minor = 0,
|
||||||
|
.patch = 0,
|
||||||
|
.pre_release = {},
|
||||||
|
.build = {}}});
|
||||||
|
clause.push_back(
|
||||||
|
{Operation::Less, Version{.major = major + 1,
|
||||||
|
.minor = 0,
|
||||||
|
.patch = 0,
|
||||||
|
.pre_release = {},
|
||||||
|
.build = {}}});
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
unsigned minor = 0;
|
||||||
|
if (!Detail::parse_component(minor_text, minor) ||
|
||||||
|
second_dot == std::string_view::npos) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const auto patch_text = token.substr(second_dot + 1);
|
||||||
|
if (patch_text != "x" && patch_text != "X" &&
|
||||||
|
patch_text != "*") {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (minor == std::numeric_limits<unsigned>::max()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
clause.push_back(
|
||||||
|
{Operation::GreaterEqual, Version{.major = major,
|
||||||
|
.minor = minor,
|
||||||
|
.patch = 0,
|
||||||
|
.pre_release = {},
|
||||||
|
.build = {}}});
|
||||||
|
clause.push_back({Operation::Less, Version{.major = major,
|
||||||
|
.minor = minor + 1,
|
||||||
|
.patch = 0,
|
||||||
|
.pre_release = {},
|
||||||
|
.build = {}}});
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
[[nodiscard]] inline std::optional<VersionRange>
|
||||||
|
parse_range(std::string_view expression)
|
||||||
|
{
|
||||||
|
return VersionRange::parse(expression);
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace Void::Semver
|
} // namespace Void::Semver
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Crypto/Crypto.hpp>
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
#include <Void/Text/Semver.hpp>
|
||||||
|
|
||||||
|
#include <array>
|
||||||
|
#include <chrono>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <unordered_map>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Update
|
||||||
|
{
|
||||||
|
struct Compatibility {
|
||||||
|
std::unordered_map<std::string, Semver::VersionRange>
|
||||||
|
versionContracts;
|
||||||
|
std::unordered_map<std::string, std::string> exactContracts;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Release {
|
||||||
|
std::string component;
|
||||||
|
std::string artifactId;
|
||||||
|
std::string channel;
|
||||||
|
Semver::Version version;
|
||||||
|
std::string cohort;
|
||||||
|
std::string platform;
|
||||||
|
std::string architecture;
|
||||||
|
std::string url;
|
||||||
|
std::uint64_t size{0};
|
||||||
|
std::string sha256;
|
||||||
|
std::string packageType;
|
||||||
|
Compatibility compatibility;
|
||||||
|
std::string releaseManifestSha256;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Feed {
|
||||||
|
std::uint32_t schemaVersion{1};
|
||||||
|
std::string feedId;
|
||||||
|
std::uint64_t sequence{0};
|
||||||
|
std::chrono::system_clock::time_point generatedAt;
|
||||||
|
std::chrono::system_clock::time_point expiresAt;
|
||||||
|
std::vector<Release> releases;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct FeedEnvelope {
|
||||||
|
std::uint32_t schemaVersion{1};
|
||||||
|
std::string keyId;
|
||||||
|
std::string payload;
|
||||||
|
Crypto::Digest signature;
|
||||||
|
};
|
||||||
|
|
||||||
|
using Ed25519PublicKey =
|
||||||
|
std::array<std::byte, Crypto::Ed25519PublicKeySize>;
|
||||||
|
using Keyring = std::unordered_map<std::string, Ed25519PublicKey>;
|
||||||
|
|
||||||
|
struct VerificationPolicy {
|
||||||
|
std::size_t maxEnvelopeBytes{5 * 1024 * 1024};
|
||||||
|
std::size_t maxPayloadBytes{4 * 1024 * 1024};
|
||||||
|
std::size_t maxReleases{10'000};
|
||||||
|
std::optional<std::uint64_t> minimumSequence;
|
||||||
|
std::chrono::system_clock::time_point now{
|
||||||
|
std::chrono::system_clock::now()};
|
||||||
|
bool requireUnexpired{true};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct VerifiedFeed {
|
||||||
|
Feed feed;
|
||||||
|
std::string keyId;
|
||||||
|
std::string signedPayload;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Environment {
|
||||||
|
std::unordered_map<std::string, Semver::Version> versionContracts;
|
||||||
|
std::unordered_map<std::string, std::string> exactContracts;
|
||||||
|
std::string platform;
|
||||||
|
std::string architecture;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct SelectionRequest {
|
||||||
|
std::string component;
|
||||||
|
std::string artifactId;
|
||||||
|
std::string channel;
|
||||||
|
Environment environment;
|
||||||
|
std::optional<Semver::Version> currentVersion;
|
||||||
|
std::optional<std::string> requiredCohort;
|
||||||
|
bool allowDowngrade{false};
|
||||||
|
bool includeCurrent{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Parse and validate an unsigned payload. Trust and activation policy is a
|
||||||
|
/// caller concern; all structural, size, expiry and replay checks still
|
||||||
|
/// run.
|
||||||
|
[[nodiscard]] Void::Result::Result<Feed>
|
||||||
|
parseFeedPayload(std::string_view payload,
|
||||||
|
const VerificationPolicy& policy = {});
|
||||||
|
|
||||||
|
/// Verify the envelope signature before parsing the signed payload.
|
||||||
|
[[nodiscard]] Void::Result::Result<VerifiedFeed>
|
||||||
|
verifyFeedEnvelope(std::string_view envelopeJson, const Keyring& keys,
|
||||||
|
const VerificationPolicy& policy = {});
|
||||||
|
|
||||||
|
/// Select the greatest compatible version, independent of feed order.
|
||||||
|
[[nodiscard]] std::optional<Release>
|
||||||
|
selectRelease(const Feed& feed, const SelectionRequest& request);
|
||||||
|
} // namespace Void::Update
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Update/Feed.hpp>
|
||||||
|
#include <Void/Update/VersionStore.hpp>
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
#include <Void/Text/Semver.hpp>
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <optional>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Update
|
||||||
|
{
|
||||||
|
struct PendingActivation {
|
||||||
|
std::optional<Semver::Version> previousVersion;
|
||||||
|
Semver::Version candidateVersion;
|
||||||
|
/// Health-log generation observed before activation. A later
|
||||||
|
/// healthy event for the candidate is the durable commit marker
|
||||||
|
/// used to reconcile an activation journal left behind by a
|
||||||
|
/// post-commit cleanup failure.
|
||||||
|
std::uint64_t healthGeneration{};
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Immutable version directory store with a relative `current` symlink and
|
||||||
|
/// a durable activation journal. An uncommitted activation is rolled back
|
||||||
|
/// by reconcile(), making candidate health checks an explicit commit
|
||||||
|
/// boundary.
|
||||||
|
///
|
||||||
|
/// The crash-durability and cross-process locking guarantees are provided
|
||||||
|
/// by the POSIX implementation. The current Windows fallback is functional
|
||||||
|
/// but does not yet provide equivalent crash durability or process locking.
|
||||||
|
class VersionStore
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
explicit VersionStore(std::filesystem::path root);
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void> initialize();
|
||||||
|
[[nodiscard]] Void::Result::Result<std::filesystem::path>
|
||||||
|
prepare(const Semver::Version& version);
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
publish(const Semver::Version& version,
|
||||||
|
const std::filesystem::path& stagingDirectory);
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
activate(const Semver::Version& version);
|
||||||
|
/// Idempotently accept the candidate. A durable healthy-history
|
||||||
|
/// event is the commit point; activation-journal cleanup after that
|
||||||
|
/// point cannot be reported as a reversible failure.
|
||||||
|
[[nodiscard]] Void::Result::Result<void> commit();
|
||||||
|
/// Idempotently restore the previous version. The journal is
|
||||||
|
/// retained until restoration succeeds. A candidate whose commit
|
||||||
|
/// marker is newer than the journal baseline is finalized instead
|
||||||
|
/// of rolled back.
|
||||||
|
[[nodiscard]] Void::Result::Result<void> rollback();
|
||||||
|
[[nodiscard]] Void::Result::Result<void> reconcile();
|
||||||
|
/// Record a successful activation performed by an external
|
||||||
|
/// lifecycle owner. The published version must be a real immediate
|
||||||
|
/// directory. Every call appends a durable healthy event and
|
||||||
|
/// refreshes retention order. It rejects stores with an internal
|
||||||
|
/// activation journal so it cannot implicitly commit activate().
|
||||||
|
/// This method does not initialize the store or create staging.
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
recordHealthy(const Semver::Version& version);
|
||||||
|
/// Record a failed external activation unless this version's
|
||||||
|
/// current publication lifecycle is already known healthy. A
|
||||||
|
/// retired and later republished SemVer starts a new lifecycle.
|
||||||
|
/// This method does not initialize the store or create staging.
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
recordFailed(const Semver::Version& version);
|
||||||
|
/// Return real, currently published versions whose current
|
||||||
|
/// lifecycle is known healthy, newest durable healthy event first.
|
||||||
|
/// Missing, symlinked, failed, retired, and unknown publications
|
||||||
|
/// are excluded.
|
||||||
|
[[nodiscard]]
|
||||||
|
Void::Result::Result<std::vector<Semver::Version>>
|
||||||
|
healthyPublishedVersions() const;
|
||||||
|
/// Remove structurally valid, published version directories except
|
||||||
|
/// the active version, an in-flight activation's candidate and
|
||||||
|
/// previous version, and the requested number of most recently
|
||||||
|
/// committed healthy versions. Unknown publication state is
|
||||||
|
/// retained conservatively. Symlinks and the staging tree are never
|
||||||
|
/// traversed or removed. Returns the versions that were quarantined
|
||||||
|
/// and removed.
|
||||||
|
[[nodiscard]]
|
||||||
|
Void::Result::Result<std::vector<Semver::Version>>
|
||||||
|
prune(std::size_t retainedPreviousVersions);
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<std::optional<Semver::Version>>
|
||||||
|
currentVersion() const;
|
||||||
|
[[nodiscard]] Void::Result::Result<std::optional<PendingActivation>>
|
||||||
|
pendingActivation() const;
|
||||||
|
|
||||||
|
[[nodiscard]] const std::filesystem::path& root() const noexcept;
|
||||||
|
[[nodiscard]] std::filesystem::path
|
||||||
|
versionPath(const Semver::Version& version) const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
std::filesystem::path m_root;
|
||||||
|
};
|
||||||
|
} // namespace Void::Update
|
||||||
@@ -0,0 +1,652 @@
|
|||||||
|
#include <Void/Archive/Archive.hpp>
|
||||||
|
|
||||||
|
#include <array>
|
||||||
|
#include <atomic>
|
||||||
|
#include <cerrno>
|
||||||
|
#include <cstring>
|
||||||
|
#include <format>
|
||||||
|
#include <memory>
|
||||||
|
#include <optional>
|
||||||
|
#include <set>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <system_error>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
#include <archive.h>
|
||||||
|
#include <archive_entry.h>
|
||||||
|
|
||||||
|
#ifndef _WIN32
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <sys/stat.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
#else
|
||||||
|
#include <fstream>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace Void::Archive
|
||||||
|
{
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
using ArchiveHandle =
|
||||||
|
std::unique_ptr<archive, decltype(&archive_read_free)>;
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Error
|
||||||
|
archive_error(archive *reader, std::string_view operation)
|
||||||
|
{
|
||||||
|
const char *message = archive_error_string(reader);
|
||||||
|
return Void::Result::Error{std::format(
|
||||||
|
"Archive::extract: {}: {}", operation,
|
||||||
|
message == nullptr ? "unknown archive error" : message)};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::optional<std::filesystem::path>
|
||||||
|
safe_relative_path(std::string_view rawPath, bool directory)
|
||||||
|
{
|
||||||
|
if (rawPath.empty() ||
|
||||||
|
rawPath.find('\\') != std::string_view::npos) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rawPath.back() == '/') {
|
||||||
|
if (!directory) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
rawPath.remove_suffix(1);
|
||||||
|
if (rawPath.empty() || rawPath.back() == '/') {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (rawPath.front() == '/' ||
|
||||||
|
rawPath.find("//") != std::string_view::npos) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::filesystem::path path{rawPath};
|
||||||
|
if (path.empty() || path.is_absolute() || path.has_root_name() ||
|
||||||
|
path.lexically_normal() != path) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
for (const auto &component : path) {
|
||||||
|
if (component.empty() || component == "." ||
|
||||||
|
component == "..") {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifndef _WIN32
|
||||||
|
class FileDescriptor
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
explicit FileDescriptor(int descriptor = -1) noexcept
|
||||||
|
: m_descriptor(descriptor)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
~FileDescriptor() { reset(); }
|
||||||
|
|
||||||
|
FileDescriptor(FileDescriptor &&other) noexcept
|
||||||
|
: m_descriptor(std::exchange(other.m_descriptor, -1))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
FileDescriptor &operator=(FileDescriptor &&other) noexcept
|
||||||
|
{
|
||||||
|
if (this != &other) {
|
||||||
|
reset(std::exchange(other.m_descriptor, -1));
|
||||||
|
}
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
FileDescriptor(const FileDescriptor &) = delete;
|
||||||
|
FileDescriptor &operator=(const FileDescriptor &) = delete;
|
||||||
|
|
||||||
|
[[nodiscard]] int get() const noexcept { return m_descriptor; }
|
||||||
|
|
||||||
|
[[nodiscard]] explicit operator bool() const noexcept
|
||||||
|
{
|
||||||
|
return m_descriptor >= 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] int release() noexcept
|
||||||
|
{
|
||||||
|
return std::exchange(m_descriptor, -1);
|
||||||
|
}
|
||||||
|
|
||||||
|
void reset(int descriptor = -1) noexcept
|
||||||
|
{
|
||||||
|
if (m_descriptor >= 0) {
|
||||||
|
(void)::close(m_descriptor);
|
||||||
|
}
|
||||||
|
m_descriptor = descriptor;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
int m_descriptor{-1};
|
||||||
|
};
|
||||||
|
|
||||||
|
constexpr int directoryOpenFlags =
|
||||||
|
O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW;
|
||||||
|
constexpr std::size_t maximumTemporaryAttempts = 128;
|
||||||
|
std::atomic<std::uint64_t> temporaryCounter{0};
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<FileDescriptor>
|
||||||
|
open_destination(const std::filesystem::path &destination)
|
||||||
|
{
|
||||||
|
FileDescriptor descriptor{
|
||||||
|
::open(destination.c_str(), directoryOpenFlags)};
|
||||||
|
if (!descriptor) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
std::format("Archive::extract: open destination '{}': {}",
|
||||||
|
destination.string(), std::strerror(errno)));
|
||||||
|
}
|
||||||
|
return descriptor;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<FileDescriptor>
|
||||||
|
open_parent_directory(int rootDescriptor,
|
||||||
|
const std::filesystem::path &relativeParent,
|
||||||
|
const std::filesystem::path &displayRoot)
|
||||||
|
{
|
||||||
|
FileDescriptor current{
|
||||||
|
::openat(rootDescriptor, ".", directoryOpenFlags)};
|
||||||
|
if (!current) {
|
||||||
|
return Void::Result::fail(std::format(
|
||||||
|
"Archive::extract: duplicate destination '{}': {}",
|
||||||
|
displayRoot.string(), std::strerror(errno)));
|
||||||
|
}
|
||||||
|
|
||||||
|
std::filesystem::path displayPath = displayRoot;
|
||||||
|
for (const auto &component : relativeParent) {
|
||||||
|
const std::string name{component.native()};
|
||||||
|
displayPath /= component;
|
||||||
|
int descriptor =
|
||||||
|
::openat(current.get(), name.c_str(), directoryOpenFlags);
|
||||||
|
if (descriptor < 0 && errno == ENOENT) {
|
||||||
|
if (::mkdirat(current.get(), name.c_str(), 0755) != 0 &&
|
||||||
|
errno != EEXIST) {
|
||||||
|
return Void::Result::fail(std::format(
|
||||||
|
"Archive::extract: cannot create directory '{}': "
|
||||||
|
"{}",
|
||||||
|
displayPath.string(), std::strerror(errno)));
|
||||||
|
}
|
||||||
|
descriptor = ::openat(current.get(), name.c_str(),
|
||||||
|
directoryOpenFlags);
|
||||||
|
}
|
||||||
|
if (descriptor < 0) {
|
||||||
|
return Void::Result::fail(std::format(
|
||||||
|
"Archive::extract: unsafe parent '{}': {}",
|
||||||
|
displayPath.string(), std::strerror(errno)));
|
||||||
|
}
|
||||||
|
current = FileDescriptor{descriptor};
|
||||||
|
}
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void> create_directory_entry(
|
||||||
|
int rootDescriptor, const std::filesystem::path &relative,
|
||||||
|
const std::filesystem::path &displayRoot, bool overwrite)
|
||||||
|
{
|
||||||
|
auto openedParent = open_parent_directory(
|
||||||
|
rootDescriptor, relative.parent_path(), displayRoot);
|
||||||
|
if (!openedParent) {
|
||||||
|
return std::unexpected{openedParent.error()};
|
||||||
|
}
|
||||||
|
auto parent = std::move(*openedParent);
|
||||||
|
const std::string name{relative.filename().native()};
|
||||||
|
const auto displayPath = displayRoot / relative;
|
||||||
|
|
||||||
|
if (::mkdirat(parent.get(), name.c_str(), 0755) == 0) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
if (errno != EEXIST) {
|
||||||
|
return Void::Result::fail(std::format(
|
||||||
|
"Archive::extract: cannot create directory '{}': {}",
|
||||||
|
displayPath.string(), std::strerror(errno)));
|
||||||
|
}
|
||||||
|
if (!overwrite) {
|
||||||
|
return Void::Result::fail(std::format(
|
||||||
|
"Archive::extract: destination '{}' already exists",
|
||||||
|
displayPath.string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
FileDescriptor existing{
|
||||||
|
::openat(parent.get(), name.c_str(), directoryOpenFlags)};
|
||||||
|
if (!existing) {
|
||||||
|
return Void::Result::fail(std::format(
|
||||||
|
"Archive::extract: destination '{}' is not a real "
|
||||||
|
"directory",
|
||||||
|
displayPath.string()));
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<std::uint64_t>
|
||||||
|
extract_regular(archive *reader, int rootDescriptor,
|
||||||
|
const std::filesystem::path &relative,
|
||||||
|
const std::filesystem::path &displayRoot,
|
||||||
|
const ExtractionOptions &options,
|
||||||
|
std::uint64_t alreadyExtracted, bool executable)
|
||||||
|
{
|
||||||
|
auto openedParent = open_parent_directory(
|
||||||
|
rootDescriptor, relative.parent_path(), displayRoot);
|
||||||
|
if (!openedParent) {
|
||||||
|
return std::unexpected{openedParent.error()};
|
||||||
|
}
|
||||||
|
auto parent = std::move(*openedParent);
|
||||||
|
const std::string outputName{relative.filename().native()};
|
||||||
|
const auto displayPath = displayRoot / relative;
|
||||||
|
|
||||||
|
FileDescriptor descriptor;
|
||||||
|
std::string temporaryName;
|
||||||
|
for (std::size_t attempt = 0; attempt < maximumTemporaryAttempts;
|
||||||
|
++attempt) {
|
||||||
|
const auto sequence =
|
||||||
|
temporaryCounter.fetch_add(1, std::memory_order_relaxed);
|
||||||
|
temporaryName =
|
||||||
|
std::format(".void-archive-{}-{}",
|
||||||
|
static_cast<long long>(::getpid()), sequence);
|
||||||
|
const int opened = ::openat(parent.get(), temporaryName.c_str(),
|
||||||
|
O_WRONLY | O_CREAT | O_EXCL |
|
||||||
|
O_CLOEXEC | O_NOFOLLOW,
|
||||||
|
executable ? 0755 : 0644);
|
||||||
|
if (opened >= 0) {
|
||||||
|
descriptor = FileDescriptor{opened};
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (errno != EEXIST) {
|
||||||
|
return Void::Result::fail(std::format(
|
||||||
|
"Archive::extract: create temporary file for '{}': {}",
|
||||||
|
displayPath.string(), std::strerror(errno)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!descriptor) {
|
||||||
|
return Void::Result::fail(std::format(
|
||||||
|
"Archive::extract: cannot allocate temporary file for '{}'",
|
||||||
|
displayPath.string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
auto removeTemporary = [&]() noexcept {
|
||||||
|
descriptor.reset();
|
||||||
|
if (!temporaryName.empty()) {
|
||||||
|
(void)::unlinkat(parent.get(), temporaryName.c_str(), 0);
|
||||||
|
temporaryName.clear();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
auto fail = [&](std::string message)
|
||||||
|
-> Void::Result::Result<std::uint64_t> {
|
||||||
|
removeTemporary();
|
||||||
|
return Void::Result::fail(std::move(message));
|
||||||
|
};
|
||||||
|
|
||||||
|
std::array<std::byte, 64 * 1024> buffer{};
|
||||||
|
std::uint64_t fileBytes = 0;
|
||||||
|
for (;;) {
|
||||||
|
const auto count =
|
||||||
|
archive_read_data(reader, buffer.data(), buffer.size());
|
||||||
|
if (count == 0) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (count < 0) {
|
||||||
|
return fail(archive_error(reader, "read entry").message());
|
||||||
|
}
|
||||||
|
const auto amount = static_cast<std::uint64_t>(count);
|
||||||
|
if (amount > options.maxFileBytes - fileBytes ||
|
||||||
|
amount >
|
||||||
|
options.maxTotalBytes - alreadyExtracted - fileBytes) {
|
||||||
|
return fail(
|
||||||
|
"Archive::extract: extracted size exceeds policy");
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t written = 0;
|
||||||
|
while (written < static_cast<std::size_t>(count)) {
|
||||||
|
const auto result = ::write(
|
||||||
|
descriptor.get(),
|
||||||
|
reinterpret_cast<const char *>(buffer.data()) + written,
|
||||||
|
static_cast<std::size_t>(count) - written);
|
||||||
|
if (result < 0 && errno == EINTR) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (result <= 0) {
|
||||||
|
const int error = errno;
|
||||||
|
return fail(std::format(
|
||||||
|
"Archive::extract: write '{}': {}",
|
||||||
|
displayPath.string(), std::strerror(error)));
|
||||||
|
}
|
||||||
|
written += static_cast<std::size_t>(result);
|
||||||
|
}
|
||||||
|
fileBytes += amount;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (::fsync(descriptor.get()) != 0) {
|
||||||
|
const int error = errno;
|
||||||
|
return fail(std::format("Archive::extract: fsync '{}': {}",
|
||||||
|
displayPath.string(),
|
||||||
|
std::strerror(error)));
|
||||||
|
}
|
||||||
|
const int rawDescriptor = descriptor.release();
|
||||||
|
if (::close(rawDescriptor) != 0) {
|
||||||
|
const int error = errno;
|
||||||
|
return fail(std::format("Archive::extract: close '{}': {}",
|
||||||
|
displayPath.string(),
|
||||||
|
std::strerror(error)));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.overwriteExisting) {
|
||||||
|
struct stat status{};
|
||||||
|
if (::fstatat(parent.get(), outputName.c_str(), &status,
|
||||||
|
AT_SYMLINK_NOFOLLOW) == 0) {
|
||||||
|
if (!S_ISREG(status.st_mode)) {
|
||||||
|
return fail(std::format(
|
||||||
|
"Archive::extract: destination '{}' is not a "
|
||||||
|
"regular file",
|
||||||
|
displayPath.string()));
|
||||||
|
}
|
||||||
|
} else if (errno != ENOENT) {
|
||||||
|
const int error = errno;
|
||||||
|
return fail(std::format(
|
||||||
|
"Archive::extract: inspect destination '{}': {}",
|
||||||
|
displayPath.string(), std::strerror(error)));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (::renameat(parent.get(), temporaryName.c_str(),
|
||||||
|
parent.get(), outputName.c_str()) != 0) {
|
||||||
|
const int error = errno;
|
||||||
|
return fail(std::format(
|
||||||
|
"Archive::extract: publish '{}': {}",
|
||||||
|
displayPath.string(), std::strerror(error)));
|
||||||
|
}
|
||||||
|
temporaryName.clear();
|
||||||
|
} else {
|
||||||
|
if (::linkat(parent.get(), temporaryName.c_str(), parent.get(),
|
||||||
|
outputName.c_str(), 0) != 0) {
|
||||||
|
const int error = errno;
|
||||||
|
return fail(std::format(
|
||||||
|
"Archive::extract: publish '{}': {}",
|
||||||
|
displayPath.string(), std::strerror(error)));
|
||||||
|
}
|
||||||
|
|
||||||
|
int unlinkResult = 0;
|
||||||
|
do {
|
||||||
|
unlinkResult =
|
||||||
|
::unlinkat(parent.get(), temporaryName.c_str(), 0);
|
||||||
|
} while (unlinkResult != 0 && errno == EINTR);
|
||||||
|
if (unlinkResult != 0 && errno != ENOENT) {
|
||||||
|
const int error = errno;
|
||||||
|
return fail(std::format(
|
||||||
|
"Archive::extract: remove temporary file for '{}': {}",
|
||||||
|
displayPath.string(), std::strerror(error)));
|
||||||
|
}
|
||||||
|
temporaryName.clear();
|
||||||
|
}
|
||||||
|
return fileBytes;
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
safe_parents(const std::filesystem::path &root,
|
||||||
|
const std::filesystem::path &relativeParent)
|
||||||
|
{
|
||||||
|
std::filesystem::path current = root;
|
||||||
|
for (const auto &component : relativeParent) {
|
||||||
|
current /= component;
|
||||||
|
std::error_code error;
|
||||||
|
const auto status =
|
||||||
|
std::filesystem::symlink_status(current, error);
|
||||||
|
if (!error &&
|
||||||
|
status.type() != std::filesystem::file_type::not_found) {
|
||||||
|
if (std::filesystem::is_symlink(status) ||
|
||||||
|
!std::filesystem::is_directory(status)) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
std::format("Archive::extract: unsafe parent '{}'",
|
||||||
|
current.string()));
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (error && error != std::errc::no_such_file_or_directory) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
std::format("Archive::extract: cannot inspect '{}': {}",
|
||||||
|
current.string(), error.message()));
|
||||||
|
}
|
||||||
|
error.clear();
|
||||||
|
std::filesystem::create_directory(current, error);
|
||||||
|
if (error) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
std::format("Archive::extract: cannot create '{}': {}",
|
||||||
|
current.string(), error.message()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
create_directory_entry(const std::filesystem::path &path,
|
||||||
|
bool overwrite)
|
||||||
|
{
|
||||||
|
std::error_code error;
|
||||||
|
const auto status = std::filesystem::symlink_status(path, error);
|
||||||
|
if (!error &&
|
||||||
|
status.type() != std::filesystem::file_type::not_found) {
|
||||||
|
if (std::filesystem::is_symlink(status) ||
|
||||||
|
!std::filesystem::is_directory(status) || !overwrite) {
|
||||||
|
return Void::Result::fail(std::format(
|
||||||
|
"Archive::extract: destination '{}' already exists",
|
||||||
|
path.string()));
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
error.clear();
|
||||||
|
std::filesystem::create_directory(path, error);
|
||||||
|
if (error) {
|
||||||
|
return Void::Result::fail(std::format(
|
||||||
|
"Archive::extract: cannot create directory '{}': {}",
|
||||||
|
path.string(), error.message()));
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<std::uint64_t>
|
||||||
|
extract_regular(archive *reader, const std::filesystem::path &path,
|
||||||
|
const ExtractionOptions &options,
|
||||||
|
std::uint64_t alreadyExtracted)
|
||||||
|
{
|
||||||
|
std::error_code error;
|
||||||
|
const auto status = std::filesystem::symlink_status(path, error);
|
||||||
|
if (!error &&
|
||||||
|
status.type() != std::filesystem::file_type::not_found &&
|
||||||
|
(std::filesystem::is_symlink(status) ||
|
||||||
|
!std::filesystem::is_regular_file(status))) {
|
||||||
|
return Void::Result::fail(std::format(
|
||||||
|
"Archive::extract: destination '{}' is not a regular file",
|
||||||
|
path.string()));
|
||||||
|
}
|
||||||
|
if (!options.overwriteExisting && !error &&
|
||||||
|
status.type() != std::filesystem::file_type::not_found) {
|
||||||
|
return Void::Result::fail(std::format(
|
||||||
|
"Archive::extract: destination '{}' already exists",
|
||||||
|
path.string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
std::ofstream output{path, std::ios::binary | std::ios::trunc};
|
||||||
|
if (!output) {
|
||||||
|
return Void::Result::fail(std::format(
|
||||||
|
"Archive::extract: create '{}' failed", path.string()));
|
||||||
|
}
|
||||||
|
auto fail = [&](std::string message)
|
||||||
|
-> Void::Result::Result<std::uint64_t> {
|
||||||
|
output.close();
|
||||||
|
std::error_code removeError;
|
||||||
|
std::filesystem::remove(path, removeError);
|
||||||
|
return Void::Result::fail(std::move(message));
|
||||||
|
};
|
||||||
|
|
||||||
|
std::array<std::byte, 64 * 1024> buffer{};
|
||||||
|
std::uint64_t fileBytes = 0;
|
||||||
|
for (;;) {
|
||||||
|
const auto count =
|
||||||
|
archive_read_data(reader, buffer.data(), buffer.size());
|
||||||
|
if (count == 0) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (count < 0) {
|
||||||
|
return fail(archive_error(reader, "read entry").message());
|
||||||
|
}
|
||||||
|
const auto amount = static_cast<std::uint64_t>(count);
|
||||||
|
if (amount > options.maxFileBytes - fileBytes ||
|
||||||
|
amount >
|
||||||
|
options.maxTotalBytes - alreadyExtracted - fileBytes) {
|
||||||
|
return fail(
|
||||||
|
"Archive::extract: extracted size exceeds policy");
|
||||||
|
}
|
||||||
|
output.write(reinterpret_cast<const char *>(buffer.data()),
|
||||||
|
count);
|
||||||
|
if (!output) {
|
||||||
|
return fail("Archive::extract: write failed");
|
||||||
|
}
|
||||||
|
fileBytes += amount;
|
||||||
|
}
|
||||||
|
return fileBytes;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Result::Result<ExtractionResult>
|
||||||
|
extract(const std::filesystem::path &archivePath,
|
||||||
|
const std::filesystem::path &destination,
|
||||||
|
const ExtractionOptions &options)
|
||||||
|
{
|
||||||
|
if (options.maxEntries == 0 || options.maxFileBytes == 0 ||
|
||||||
|
options.maxTotalBytes == 0) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Archive::extract: extraction limits must be positive");
|
||||||
|
}
|
||||||
|
std::error_code error;
|
||||||
|
std::filesystem::create_directories(destination, error);
|
||||||
|
if (error) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
std::format("Archive::extract: cannot create destination: {}",
|
||||||
|
error.message()));
|
||||||
|
}
|
||||||
|
#ifndef _WIN32
|
||||||
|
auto root = open_destination(destination);
|
||||||
|
if (!root) {
|
||||||
|
return std::unexpected{root.error()};
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
const auto root = std::filesystem::canonical(destination, error);
|
||||||
|
if (error || std::filesystem::is_symlink(
|
||||||
|
std::filesystem::symlink_status(destination, error))) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Archive::extract: destination must be a real directory");
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
ArchiveHandle reader{archive_read_new(), &archive_read_free};
|
||||||
|
if (!reader) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Archive::extract: cannot allocate archive reader");
|
||||||
|
}
|
||||||
|
archive_read_support_filter_zstd(reader.get());
|
||||||
|
archive_read_support_filter_none(reader.get());
|
||||||
|
archive_read_support_format_tar(reader.get());
|
||||||
|
#ifdef _WIN32
|
||||||
|
const int opened = archive_read_open_filename_w(
|
||||||
|
reader.get(), archivePath.c_str(), 64 * 1024);
|
||||||
|
#else
|
||||||
|
const int opened = archive_read_open_filename(
|
||||||
|
reader.get(), archivePath.c_str(), 64 * 1024);
|
||||||
|
#endif
|
||||||
|
if (opened != ARCHIVE_OK) {
|
||||||
|
return std::unexpected{archive_error(reader.get(), "open archive")};
|
||||||
|
}
|
||||||
|
|
||||||
|
ExtractionResult result;
|
||||||
|
std::set<std::filesystem::path> seen;
|
||||||
|
archive_entry *entry = nullptr;
|
||||||
|
for (;;) {
|
||||||
|
const int status = archive_read_next_header(reader.get(), &entry);
|
||||||
|
if (status == ARCHIVE_EOF) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (status != ARCHIVE_OK) {
|
||||||
|
return std::unexpected{
|
||||||
|
archive_error(reader.get(), "read header")};
|
||||||
|
}
|
||||||
|
if (++result.entries > options.maxEntries) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Archive::extract: entry count exceeds policy");
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *rawPath = archive_entry_pathname(entry);
|
||||||
|
if (rawPath == nullptr) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Archive::extract: entry has no path");
|
||||||
|
}
|
||||||
|
if (archive_entry_hardlink(entry) != nullptr ||
|
||||||
|
archive_entry_symlink(entry) != nullptr) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Archive::extract: links are not allowed");
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto type = archive_entry_filetype(entry);
|
||||||
|
if (type != AE_IFDIR && type != AE_IFREG) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Archive::extract: special files are not allowed");
|
||||||
|
}
|
||||||
|
auto relative = safe_relative_path(rawPath, type == AE_IFDIR);
|
||||||
|
if (!relative || !seen.insert(*relative).second) {
|
||||||
|
return Void::Result::fail(std::format(
|
||||||
|
"Archive::extract: unsafe or duplicate path '{}'",
|
||||||
|
rawPath));
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifdef _WIN32
|
||||||
|
if (auto parents = safe_parents(root, relative->parent_path());
|
||||||
|
!parents) {
|
||||||
|
return std::unexpected{parents.error()};
|
||||||
|
}
|
||||||
|
const auto output = root / *relative;
|
||||||
|
#endif
|
||||||
|
if (type == AE_IFDIR) {
|
||||||
|
#ifndef _WIN32
|
||||||
|
auto created =
|
||||||
|
create_directory_entry(root->get(), *relative, destination,
|
||||||
|
options.overwriteExisting);
|
||||||
|
#else
|
||||||
|
auto created =
|
||||||
|
create_directory_entry(output, options.overwriteExisting);
|
||||||
|
#endif
|
||||||
|
if (!created) {
|
||||||
|
return std::unexpected{created.error()};
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto declared = archive_entry_size(entry);
|
||||||
|
if (declared < 0 ||
|
||||||
|
static_cast<std::uint64_t>(declared) > options.maxFileBytes ||
|
||||||
|
static_cast<std::uint64_t>(declared) >
|
||||||
|
options.maxTotalBytes - result.bytes) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Archive::extract: declared entry size exceeds policy");
|
||||||
|
}
|
||||||
|
#ifndef _WIN32
|
||||||
|
const bool executable = (archive_entry_perm(entry) & 0111) != 0;
|
||||||
|
auto extracted =
|
||||||
|
extract_regular(reader.get(), root->get(), *relative,
|
||||||
|
destination, options, result.bytes, executable);
|
||||||
|
#else
|
||||||
|
auto extracted =
|
||||||
|
extract_regular(reader.get(), output, options, result.bytes);
|
||||||
|
#endif
|
||||||
|
if (!extracted) {
|
||||||
|
return std::unexpected{extracted.error()};
|
||||||
|
}
|
||||||
|
result.bytes += *extracted;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
} // namespace Void::Archive
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
void_add_module(Archive
|
||||||
|
INTERNAL_DEPS Functional
|
||||||
|
EXTERNAL_DEPS LibArchive::LibArchive
|
||||||
|
)
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
void_add_module(Binary
|
||||||
|
INTERNAL_DEPS Functional
|
||||||
|
)
|
||||||
@@ -0,0 +1,257 @@
|
|||||||
|
#include <Void/Crypto/Crypto.hpp>
|
||||||
|
|
||||||
|
#include <array>
|
||||||
|
#include <format>
|
||||||
|
#include <fstream>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
#include <openssl/err.h>
|
||||||
|
#include <openssl/evp.h>
|
||||||
|
|
||||||
|
namespace Void::Crypto
|
||||||
|
{
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
[[nodiscard]] const EVP_MD*
|
||||||
|
algorithm_impl(HashAlgorithm algorithm) noexcept
|
||||||
|
{
|
||||||
|
switch (algorithm) {
|
||||||
|
case HashAlgorithm::Sha1:
|
||||||
|
return EVP_sha1();
|
||||||
|
case HashAlgorithm::Sha256:
|
||||||
|
return EVP_sha256();
|
||||||
|
case HashAlgorithm::Sha512:
|
||||||
|
return EVP_sha512();
|
||||||
|
}
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::string openssl_error(std::string_view operation)
|
||||||
|
{
|
||||||
|
const unsigned long code = ERR_get_error();
|
||||||
|
if (code == 0) {
|
||||||
|
return std::string{operation};
|
||||||
|
}
|
||||||
|
std::array<char, 256> buffer{};
|
||||||
|
ERR_error_string_n(code, buffer.data(), buffer.size());
|
||||||
|
return std::format("{}: {}", operation, buffer.data());
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
struct Hasher::Impl {
|
||||||
|
EVP_MD_CTX* context{nullptr};
|
||||||
|
const EVP_MD* algorithm{nullptr};
|
||||||
|
bool finalized{false};
|
||||||
|
~Impl() { EVP_MD_CTX_free(context); }
|
||||||
|
};
|
||||||
|
|
||||||
|
Hasher::Hasher(std::unique_ptr<Impl> impl) noexcept
|
||||||
|
: m_impl(std::move(impl))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
Hasher::~Hasher() = default;
|
||||||
|
Hasher::Hasher(Hasher&&) noexcept = default;
|
||||||
|
Hasher& Hasher::operator=(Hasher&&) noexcept = default;
|
||||||
|
|
||||||
|
Void::Result::Result<Hasher> Hasher::create(HashAlgorithm algorithm)
|
||||||
|
{
|
||||||
|
auto impl = std::make_unique<Impl>();
|
||||||
|
impl->algorithm = algorithm_impl(algorithm);
|
||||||
|
if (impl->algorithm == nullptr) {
|
||||||
|
return Void::Result::fail("Crypto::Hasher: unsupported algorithm");
|
||||||
|
}
|
||||||
|
impl->context = EVP_MD_CTX_new();
|
||||||
|
if (impl->context == nullptr) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
openssl_error("Crypto::Hasher: EVP_MD_CTX_new failed"));
|
||||||
|
}
|
||||||
|
if (EVP_DigestInit_ex(impl->context, impl->algorithm, nullptr) != 1) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
openssl_error("Crypto::Hasher: digest initialization failed"));
|
||||||
|
}
|
||||||
|
return Hasher{std::move(impl)};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void> Hasher::update(std::span<const std::byte> data)
|
||||||
|
{
|
||||||
|
if (!m_impl || m_impl->finalized) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Crypto::Hasher::update: hasher is finalized or moved-from");
|
||||||
|
}
|
||||||
|
if (!data.empty() &&
|
||||||
|
EVP_DigestUpdate(m_impl->context, data.data(), data.size()) != 1) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
openssl_error("Crypto::Hasher::update failed"));
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void> Hasher::update(std::string_view data)
|
||||||
|
{
|
||||||
|
return update(std::as_bytes(std::span{data.data(), data.size()}));
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<Digest> Hasher::finalize()
|
||||||
|
{
|
||||||
|
if (!m_impl || m_impl->finalized) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Crypto::Hasher::finalize: hasher is finalized or moved-from");
|
||||||
|
}
|
||||||
|
const int digest_size = EVP_MD_get_size(m_impl->algorithm);
|
||||||
|
if (digest_size <= 0) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Crypto::Hasher::finalize: invalid digest size");
|
||||||
|
}
|
||||||
|
Digest digest(static_cast<std::size_t>(digest_size));
|
||||||
|
unsigned int written = 0;
|
||||||
|
if (EVP_DigestFinal_ex(m_impl->context,
|
||||||
|
reinterpret_cast<unsigned char*>(digest.data()),
|
||||||
|
&written) != 1) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
openssl_error("Crypto::Hasher::finalize failed"));
|
||||||
|
}
|
||||||
|
m_impl->finalized = true;
|
||||||
|
digest.resize(written);
|
||||||
|
return digest;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto hash(HashAlgorithm algorithm, std::span<const std::byte> data)
|
||||||
|
-> Void::Result::Result<Digest>
|
||||||
|
{
|
||||||
|
auto hasher = Hasher::create(algorithm);
|
||||||
|
if (!hasher) {
|
||||||
|
return std::unexpected{hasher.error()};
|
||||||
|
}
|
||||||
|
if (auto updated = hasher->update(data); !updated) {
|
||||||
|
return std::unexpected{updated.error()};
|
||||||
|
}
|
||||||
|
return hasher->finalize();
|
||||||
|
}
|
||||||
|
|
||||||
|
auto hash(HashAlgorithm algorithm, std::string_view data)
|
||||||
|
-> Void::Result::Result<Digest>
|
||||||
|
{
|
||||||
|
return hash(algorithm,
|
||||||
|
std::as_bytes(std::span{data.data(), data.size()}));
|
||||||
|
}
|
||||||
|
|
||||||
|
auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path)
|
||||||
|
-> Void::Result::Result<Digest>
|
||||||
|
{
|
||||||
|
std::ifstream input{path, std::ios::binary};
|
||||||
|
if (!input.is_open()) {
|
||||||
|
return Void::Result::fail(std::format(
|
||||||
|
"Crypto::hashFile: cannot open '{}'", path.string()));
|
||||||
|
}
|
||||||
|
auto hasher = Hasher::create(algorithm);
|
||||||
|
if (!hasher) {
|
||||||
|
return std::unexpected{hasher.error()};
|
||||||
|
}
|
||||||
|
std::array<char, 64 * 1024> buffer{};
|
||||||
|
while (input) {
|
||||||
|
input.read(buffer.data(),
|
||||||
|
static_cast<std::streamsize>(buffer.size()));
|
||||||
|
const auto count = input.gcount();
|
||||||
|
if (count > 0) {
|
||||||
|
const auto bytes = std::as_bytes(
|
||||||
|
std::span{buffer.data(), static_cast<std::size_t>(count)});
|
||||||
|
if (auto updated = hasher->update(bytes); !updated) {
|
||||||
|
return std::unexpected{updated.error()};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (input.bad()) {
|
||||||
|
return Void::Result::fail(std::format(
|
||||||
|
"Crypto::hashFile: I/O error reading '{}'", path.string()));
|
||||||
|
}
|
||||||
|
return hasher->finalize();
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<Digest> sha1(std::span<const std::byte> data)
|
||||||
|
{
|
||||||
|
return hash(HashAlgorithm::Sha1, data);
|
||||||
|
}
|
||||||
|
Void::Result::Result<Digest> sha1(std::string_view data)
|
||||||
|
{
|
||||||
|
return hash(HashAlgorithm::Sha1, data);
|
||||||
|
}
|
||||||
|
Void::Result::Result<Digest> sha256(std::span<const std::byte> data)
|
||||||
|
{
|
||||||
|
return hash(HashAlgorithm::Sha256, data);
|
||||||
|
}
|
||||||
|
Void::Result::Result<Digest> sha256(std::string_view data)
|
||||||
|
{
|
||||||
|
return hash(HashAlgorithm::Sha256, data);
|
||||||
|
}
|
||||||
|
Void::Result::Result<Digest> sha512(std::span<const std::byte> data)
|
||||||
|
{
|
||||||
|
return hash(HashAlgorithm::Sha512, data);
|
||||||
|
}
|
||||||
|
Void::Result::Result<Digest> sha512(std::string_view data)
|
||||||
|
{
|
||||||
|
return hash(HashAlgorithm::Sha512, data);
|
||||||
|
}
|
||||||
|
Void::Result::Result<Digest> sha1File(const std::filesystem::path& path)
|
||||||
|
{
|
||||||
|
return hashFile(HashAlgorithm::Sha1, path);
|
||||||
|
}
|
||||||
|
Void::Result::Result<Digest> sha256File(const std::filesystem::path& path)
|
||||||
|
{
|
||||||
|
return hashFile(HashAlgorithm::Sha256, path);
|
||||||
|
}
|
||||||
|
Void::Result::Result<Digest> sha512File(const std::filesystem::path& path)
|
||||||
|
{
|
||||||
|
return hashFile(HashAlgorithm::Sha512, path);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<bool> verifyEd25519(std::span<const std::byte> message,
|
||||||
|
std::span<const std::byte>
|
||||||
|
signature,
|
||||||
|
std::span<const std::byte>
|
||||||
|
publicKey)
|
||||||
|
{
|
||||||
|
if (signature.size() != Ed25519SignatureSize) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
std::format("Crypto::verifyEd25519: signature must be {} bytes",
|
||||||
|
Ed25519SignatureSize));
|
||||||
|
}
|
||||||
|
if (publicKey.size() != Ed25519PublicKeySize) {
|
||||||
|
return Void::Result::fail(std::format(
|
||||||
|
"Crypto::verifyEd25519: public key must be {} bytes",
|
||||||
|
Ed25519PublicKeySize));
|
||||||
|
}
|
||||||
|
|
||||||
|
using Key = std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)>;
|
||||||
|
using Context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>;
|
||||||
|
Key key{EVP_PKEY_new_raw_public_key(
|
||||||
|
EVP_PKEY_ED25519, nullptr,
|
||||||
|
reinterpret_cast<const unsigned char*>(publicKey.data()),
|
||||||
|
publicKey.size()),
|
||||||
|
&EVP_PKEY_free};
|
||||||
|
if (!key) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
openssl_error("Crypto::verifyEd25519: invalid public key"));
|
||||||
|
}
|
||||||
|
Context context{EVP_MD_CTX_new(), &EVP_MD_CTX_free};
|
||||||
|
if (!context) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
openssl_error("Crypto::verifyEd25519: EVP_MD_CTX_new failed"));
|
||||||
|
}
|
||||||
|
if (EVP_DigestVerifyInit(context.get(), nullptr, nullptr, nullptr,
|
||||||
|
key.get()) != 1) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
openssl_error("Crypto::verifyEd25519: initialization failed"));
|
||||||
|
}
|
||||||
|
const int result = EVP_DigestVerify(
|
||||||
|
context.get(),
|
||||||
|
reinterpret_cast<const unsigned char*>(signature.data()),
|
||||||
|
signature.size(),
|
||||||
|
reinterpret_cast<const unsigned char*>(message.data()),
|
||||||
|
message.size());
|
||||||
|
if (result < 0) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
openssl_error("Crypto::verifyEd25519 failed"));
|
||||||
|
}
|
||||||
|
return result == 1;
|
||||||
|
}
|
||||||
|
} // namespace Void::Crypto
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
void_add_module(Crypto
|
||||||
|
INTERNAL_DEPS Functional
|
||||||
|
EXTERNAL_DEPS OpenSSL::Crypto
|
||||||
|
)
|
||||||
+247
-224
@@ -1,9 +1,9 @@
|
|||||||
#include <Void/Log/Log.hpp>
|
|
||||||
#include <Void/Plugin/Loader.hpp>
|
#include <Void/Plugin/Loader.hpp>
|
||||||
|
#include <Void/Log/Log.hpp>
|
||||||
|
|
||||||
#if defined(__unix__) || defined(__APPLE__)
|
#if defined(__unix__) || defined(__APPLE__)
|
||||||
# include <dlfcn.h>
|
#include <dlfcn.h>
|
||||||
# define VOID_HAS_DLOPEN 1
|
#define VOID_HAS_DLOPEN 1
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
@@ -13,258 +13,281 @@
|
|||||||
namespace Void::Plugin
|
namespace Void::Plugin
|
||||||
{
|
{
|
||||||
|
|
||||||
std::string_view to_string(LoadError e) noexcept
|
std::string_view to_string(LoadError e) noexcept
|
||||||
{
|
{
|
||||||
switch (e) {
|
switch (e) {
|
||||||
case LoadError::FileNotFound: return "file not found";
|
case LoadError::FileNotFound:
|
||||||
case LoadError::DlopenFailed: return "dlopen failed";
|
return "file not found";
|
||||||
case LoadError::SymbolMissing: return "required symbol missing";
|
case LoadError::DlopenFailed:
|
||||||
case LoadError::AbiMismatch: return "ABI version mismatch";
|
return "dlopen failed";
|
||||||
case LoadError::CreateFailed: return "plugin create() returned null";
|
case LoadError::SymbolMissing:
|
||||||
case LoadError::NotSupported: return "platform does not support dlopen";
|
return "required symbol missing";
|
||||||
case LoadError::StateRejected: return "new instance rejected state";
|
case LoadError::AbiMismatch:
|
||||||
case LoadError::ActivationFailed: return "plugin activation failed";
|
return "ABI version mismatch";
|
||||||
case LoadError::UnknownPlugin: return "no plugin registered under name";
|
case LoadError::CreateFailed:
|
||||||
}
|
return "plugin create() returned null";
|
||||||
return "unknown";
|
case LoadError::NotSupported:
|
||||||
}
|
return "platform does not support dlopen";
|
||||||
|
case LoadError::StateRejected:
|
||||||
|
return "new instance rejected state";
|
||||||
|
case LoadError::ActivationFailed:
|
||||||
|
return "plugin activation failed";
|
||||||
|
case LoadError::UnknownPlugin:
|
||||||
|
return "no plugin registered under name";
|
||||||
|
case LoadError::NameMismatch:
|
||||||
|
return "replacement plugin name mismatch";
|
||||||
|
}
|
||||||
|
return "unknown";
|
||||||
|
}
|
||||||
|
|
||||||
// ── internal helpers ──────────────────────────────────────────────────────────
|
// ── internal helpers
|
||||||
|
// ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
void PluginLoader::destroy_current() noexcept
|
void PluginLoader::destroy_current() noexcept
|
||||||
{
|
{
|
||||||
#ifdef VOID_HAS_DLOPEN
|
#ifdef VOID_HAS_DLOPEN
|
||||||
if (plugin_) {
|
if (plugin_) {
|
||||||
plugin_->on_unload();
|
plugin_->on_unload();
|
||||||
if (destroy_) destroy_(plugin_);
|
if (destroy_) {
|
||||||
plugin_ = nullptr;
|
destroy_(plugin_);
|
||||||
}
|
}
|
||||||
if (handle_) {
|
plugin_ = nullptr;
|
||||||
dlclose(handle_);
|
}
|
||||||
handle_ = nullptr;
|
if (handle_) {
|
||||||
}
|
dlclose(handle_);
|
||||||
destroy_ = nullptr;
|
handle_ = nullptr;
|
||||||
transfer_ = nullptr;
|
}
|
||||||
ready_ = nullptr;
|
destroy_ = nullptr;
|
||||||
state_version_ = nullptr;
|
transfer_ = nullptr;
|
||||||
serialize_ = nullptr;
|
ready_ = nullptr;
|
||||||
free_string_ = nullptr;
|
state_version_ = nullptr;
|
||||||
deserialize_ = nullptr;
|
serialize_ = nullptr;
|
||||||
|
free_string_ = nullptr;
|
||||||
|
deserialize_ = nullptr;
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
// Move plugin state old -> new across a reload. Prefers the v2
|
// Move plugin state old -> new across a reload. Prefers the v2
|
||||||
// serialize/deserialize protocol (survives layout changes between
|
// serialize/deserialize protocol (survives layout changes between
|
||||||
// versions); falls back to the raw transfer_state hook; else no-op.
|
// versions); falls back to the raw transfer_state hook; else no-op.
|
||||||
// Returns false only when the new instance actively rejects the state.
|
// Returns false only when the new instance actively rejects the state.
|
||||||
bool transfer_plugin_state(const PluginLoader& from, PluginLoader& to)
|
bool transfer_plugin_state(const PluginLoader& from, PluginLoader& to)
|
||||||
{
|
{
|
||||||
if (!from.plugin_ || !to.plugin_) {
|
if (!from.plugin_ || !to.plugin_) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (from.serialize_ && to.deserialize_) {
|
if (from.serialize_ && to.deserialize_) {
|
||||||
const std::uint32_t from_version =
|
const std::uint32_t from_version =
|
||||||
from.state_version_ ? from.state_version_() : 0;
|
from.state_version_ ? from.state_version_() : 0;
|
||||||
const char* json = from.serialize_(from.plugin_);
|
const char* json = from.serialize_(from.plugin_);
|
||||||
if (json != nullptr) {
|
if (json != nullptr) {
|
||||||
const int rc = to.deserialize_(to.plugin_, json, from_version);
|
const int rc = to.deserialize_(to.plugin_, json, from_version);
|
||||||
if (from.free_string_) {
|
if (from.free_string_) {
|
||||||
from.free_string_(json);
|
from.free_string_(json);
|
||||||
}
|
}
|
||||||
if (rc != 0) {
|
if (rc != 0) {
|
||||||
Void::Log::warn("Plugin",
|
Void::Log::warn("Plugin",
|
||||||
"deserialize_state rejected state "
|
"deserialize_state rejected state "
|
||||||
"(from v{}, rc={})",
|
"(from v{}, rc={})",
|
||||||
from_version, rc);
|
from_version, rc);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
Void::Log::debug("Plugin",
|
Void::Log::debug("Plugin",
|
||||||
"state transferred via v2 protocol (v{})",
|
"state transferred via v2 protocol (v{})",
|
||||||
from_version);
|
from_version);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (to.transfer_) {
|
if (to.transfer_) {
|
||||||
to.transfer_(from.plugin_, to.plugin_);
|
to.transfer_(from.plugin_, to.plugin_);
|
||||||
Void::Log::debug("Plugin", "state transferred via transfer_state");
|
Void::Log::debug("Plugin", "state transferred via transfer_state");
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::expected<void, LoadError>
|
std::expected<void, LoadError>
|
||||||
PluginLoader::load_from(const std::filesystem::path& path)
|
PluginLoader::load_from(const std::filesystem::path& path)
|
||||||
{
|
{
|
||||||
#ifdef VOID_HAS_DLOPEN
|
#ifdef VOID_HAS_DLOPEN
|
||||||
void* h = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL);
|
void* h = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL);
|
||||||
if (!h) return std::unexpected{LoadError::DlopenFailed};
|
if (!h) {
|
||||||
|
return std::unexpected{LoadError::DlopenFailed};
|
||||||
|
}
|
||||||
|
|
||||||
const auto sym_info = reinterpret_cast<info_fn> (dlsym(h, kInfoSymbol));
|
const auto sym_info = reinterpret_cast<info_fn>(dlsym(h, kInfoSymbol));
|
||||||
const auto sym_create = reinterpret_cast<create_fn> (dlsym(h, kCreateSymbol));
|
const auto sym_create =
|
||||||
const auto sym_destroy = reinterpret_cast<destroy_fn>(dlsym(h, kDestroySymbol));
|
reinterpret_cast<create_fn>(dlsym(h, kCreateSymbol));
|
||||||
|
const auto sym_destroy =
|
||||||
|
reinterpret_cast<destroy_fn>(dlsym(h, kDestroySymbol));
|
||||||
|
|
||||||
if (!sym_info || !sym_create || !sym_destroy) {
|
if (!sym_info || !sym_create || !sym_destroy) {
|
||||||
dlclose(h);
|
dlclose(h);
|
||||||
return std::unexpected{LoadError::SymbolMissing};
|
return std::unexpected{LoadError::SymbolMissing};
|
||||||
}
|
}
|
||||||
|
|
||||||
const PluginInfo info = sym_info();
|
const PluginInfo info = sym_info();
|
||||||
if (info.abi_version != ABI_VERSION) {
|
if (info.abi_version != ABI_VERSION) {
|
||||||
dlclose(h);
|
dlclose(h);
|
||||||
return std::unexpected{LoadError::AbiMismatch};
|
return std::unexpected{LoadError::AbiMismatch};
|
||||||
}
|
}
|
||||||
|
|
||||||
void* raw = sym_create();
|
void* raw = sym_create();
|
||||||
if (!raw) {
|
if (!raw) {
|
||||||
dlclose(h);
|
dlclose(h);
|
||||||
return std::unexpected{LoadError::CreateFailed};
|
return std::unexpected{LoadError::CreateFailed};
|
||||||
}
|
}
|
||||||
|
|
||||||
handle_ = h;
|
handle_ = h;
|
||||||
plugin_ = static_cast<IPlugin*>(raw);
|
plugin_ = static_cast<IPlugin*>(raw);
|
||||||
destroy_ = sym_destroy;
|
destroy_ = sym_destroy;
|
||||||
transfer_ = reinterpret_cast<transfer_fn>(dlsym(h, kTransferSymbol));
|
transfer_ = reinterpret_cast<transfer_fn>(dlsym(h, kTransferSymbol));
|
||||||
ready_ = reinterpret_cast<ready_fn>(dlsym(h, kReadySymbol));
|
ready_ = reinterpret_cast<ready_fn>(dlsym(h, kReadySymbol));
|
||||||
state_version_ = reinterpret_cast<state_version_fn>(
|
state_version_ =
|
||||||
dlsym(h, kStateVersionSymbol));
|
reinterpret_cast<state_version_fn>(dlsym(h, kStateVersionSymbol));
|
||||||
serialize_ = reinterpret_cast<serialize_fn>(dlsym(h, kSerializeSymbol));
|
serialize_ = reinterpret_cast<serialize_fn>(dlsym(h, kSerializeSymbol));
|
||||||
free_string_ = reinterpret_cast<free_string_fn>(
|
free_string_ =
|
||||||
dlsym(h, kFreeStringSymbol));
|
reinterpret_cast<free_string_fn>(dlsym(h, kFreeStringSymbol));
|
||||||
deserialize_ = reinterpret_cast<deserialize_fn>(
|
deserialize_ =
|
||||||
dlsym(h, kDeserializeSymbol));
|
reinterpret_cast<deserialize_fn>(dlsym(h, kDeserializeSymbol));
|
||||||
info_ = info;
|
info_ = info;
|
||||||
return {};
|
return {};
|
||||||
#else
|
#else
|
||||||
(void)path;
|
(void)path;
|
||||||
return std::unexpected{LoadError::NotSupported};
|
return std::unexpected{LoadError::NotSupported};
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── public API ────────────────────────────────────────────────────────────────
|
// ── public API
|
||||||
|
// ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
std::expected<PluginLoader, LoadError>
|
std::expected<PluginLoader, LoadError>
|
||||||
PluginLoader::load(std::filesystem::path path)
|
PluginLoader::load(std::filesystem::path path)
|
||||||
{
|
{
|
||||||
if (!std::filesystem::exists(path))
|
if (!std::filesystem::exists(path)) {
|
||||||
return std::unexpected{LoadError::FileNotFound};
|
return std::unexpected{LoadError::FileNotFound};
|
||||||
|
}
|
||||||
|
|
||||||
PluginLoader ldr;
|
PluginLoader ldr;
|
||||||
ldr.path_ = path;
|
ldr.path_ = path;
|
||||||
|
|
||||||
if (auto r = ldr.load_from(path); !r) {
|
if (auto r = ldr.load_from(path); !r) {
|
||||||
Void::Log::warn("Plugin", "load '{}' failed: {}", path.string(),
|
Void::Log::warn("Plugin", "load '{}' failed: {}", path.string(),
|
||||||
to_string(r.error()));
|
to_string(r.error()));
|
||||||
return std::unexpected{r.error()};
|
return std::unexpected{r.error()};
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
ldr.plugin_->on_load();
|
ldr.plugin_->on_load();
|
||||||
} catch (...) {
|
} catch (...) {
|
||||||
return std::unexpected{LoadError::ActivationFailed};
|
return std::unexpected{LoadError::ActivationFailed};
|
||||||
}
|
}
|
||||||
if (ldr.ready_ && ldr.ready_(ldr.plugin_) != 0) {
|
if (ldr.ready_ && ldr.ready_(ldr.plugin_) != 0) {
|
||||||
return std::unexpected{LoadError::ActivationFailed};
|
return std::unexpected{LoadError::ActivationFailed};
|
||||||
}
|
}
|
||||||
Void::Log::info("Plugin", "loaded '{}' ({} v{})", path.string(),
|
Void::Log::info("Plugin", "loaded '{}' ({} v{})", path.string(),
|
||||||
ldr.info_.name, ldr.info_.plugin_version);
|
ldr.info_.name, ldr.info_.plugin_version);
|
||||||
return ldr;
|
return ldr;
|
||||||
}
|
}
|
||||||
|
|
||||||
PluginLoader::~PluginLoader() { destroy_current(); }
|
PluginLoader::~PluginLoader() { destroy_current(); }
|
||||||
|
|
||||||
PluginLoader::PluginLoader(PluginLoader&& o) noexcept
|
PluginLoader::PluginLoader(PluginLoader&& o) noexcept
|
||||||
: handle_ {std::exchange(o.handle_, nullptr)}
|
: handle_{std::exchange(o.handle_, nullptr)},
|
||||||
, plugin_ {std::exchange(o.plugin_, nullptr)}
|
plugin_{std::exchange(o.plugin_, nullptr)},
|
||||||
, destroy_ {std::exchange(o.destroy_, nullptr)}
|
destroy_{std::exchange(o.destroy_, nullptr)},
|
||||||
, transfer_ {std::exchange(o.transfer_, nullptr)}
|
transfer_{std::exchange(o.transfer_, nullptr)},
|
||||||
, ready_ {std::exchange(o.ready_, nullptr)}
|
ready_{std::exchange(o.ready_, nullptr)},
|
||||||
, state_version_{std::exchange(o.state_version_, nullptr)}
|
state_version_{std::exchange(o.state_version_, nullptr)},
|
||||||
, serialize_ {std::exchange(o.serialize_, nullptr)}
|
serialize_{std::exchange(o.serialize_, nullptr)},
|
||||||
, free_string_ {std::exchange(o.free_string_, nullptr)}
|
free_string_{std::exchange(o.free_string_, nullptr)},
|
||||||
, deserialize_ {std::exchange(o.deserialize_, nullptr)}
|
deserialize_{std::exchange(o.deserialize_, nullptr)}, info_{o.info_},
|
||||||
, info_ {o.info_}
|
path_{std::move(o.path_)}
|
||||||
, path_ {std::move(o.path_)}
|
{
|
||||||
{}
|
}
|
||||||
|
|
||||||
PluginLoader& PluginLoader::operator=(PluginLoader&& o) noexcept
|
PluginLoader& PluginLoader::operator=(PluginLoader&& o) noexcept
|
||||||
{
|
{
|
||||||
if (this != &o) {
|
if (this != &o) {
|
||||||
destroy_current();
|
destroy_current();
|
||||||
handle_ = std::exchange(o.handle_, nullptr);
|
handle_ = std::exchange(o.handle_, nullptr);
|
||||||
plugin_ = std::exchange(o.plugin_, nullptr);
|
plugin_ = std::exchange(o.plugin_, nullptr);
|
||||||
destroy_ = std::exchange(o.destroy_, nullptr);
|
destroy_ = std::exchange(o.destroy_, nullptr);
|
||||||
transfer_ = std::exchange(o.transfer_, nullptr);
|
transfer_ = std::exchange(o.transfer_, nullptr);
|
||||||
ready_ = std::exchange(o.ready_, nullptr);
|
ready_ = std::exchange(o.ready_, nullptr);
|
||||||
state_version_ = std::exchange(o.state_version_, nullptr);
|
state_version_ = std::exchange(o.state_version_, nullptr);
|
||||||
serialize_ = std::exchange(o.serialize_, nullptr);
|
serialize_ = std::exchange(o.serialize_, nullptr);
|
||||||
free_string_ = std::exchange(o.free_string_, nullptr);
|
free_string_ = std::exchange(o.free_string_, nullptr);
|
||||||
deserialize_ = std::exchange(o.deserialize_, nullptr);
|
deserialize_ = std::exchange(o.deserialize_, nullptr);
|
||||||
info_ = o.info_;
|
info_ = o.info_;
|
||||||
path_ = std::move(o.path_);
|
path_ = std::move(o.path_);
|
||||||
}
|
}
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::expected<void, LoadError> PluginLoader::reload()
|
std::expected<void, LoadError> PluginLoader::reload()
|
||||||
{
|
{
|
||||||
#ifdef VOID_HAS_DLOPEN
|
#ifdef VOID_HAS_DLOPEN
|
||||||
// Copy to a unique temp path so dlopen gets a fresh inode (bypasses the
|
// Copy to a unique temp path so dlopen gets a fresh inode (bypasses the
|
||||||
// path-based cache) even if the file was replaced in-place.
|
// path-based cache) even if the file was replaced in-place.
|
||||||
const auto tmp = path_.parent_path()
|
const auto tmp =
|
||||||
/ (path_.filename().string() + ".void_hotswap");
|
path_.parent_path() / (path_.filename().string() + ".void_hotswap");
|
||||||
|
|
||||||
{
|
{
|
||||||
std::error_code ec;
|
std::error_code ec;
|
||||||
std::filesystem::copy_file(path_, tmp,
|
std::filesystem::copy_file(
|
||||||
std::filesystem::copy_options::overwrite_existing, ec);
|
path_, tmp, std::filesystem::copy_options::overwrite_existing,
|
||||||
if (ec) return std::unexpected{LoadError::FileNotFound};
|
ec);
|
||||||
}
|
if (ec) {
|
||||||
|
return std::unexpected{LoadError::FileNotFound};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Load new instance while old is still alive (for state transfer).
|
// Load new instance while old is still alive (for state transfer).
|
||||||
PluginLoader next;
|
PluginLoader next;
|
||||||
next.path_ = path_;
|
next.path_ = path_;
|
||||||
if (auto r = next.load_from(tmp); !r) {
|
if (auto r = next.load_from(tmp); !r) {
|
||||||
std::error_code ec;
|
std::error_code ec;
|
||||||
std::filesystem::remove(tmp, ec);
|
std::filesystem::remove(tmp, ec);
|
||||||
Void::Log::warn("Plugin", "reload '{}' failed: {}; keeping old",
|
Void::Log::warn("Plugin", "reload '{}' failed: {}; keeping old",
|
||||||
path_.string(), to_string(r.error()));
|
path_.string(), to_string(r.error()));
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Transfer state with both instances alive. A rejection aborts the
|
// Transfer state with both instances alive. A rejection aborts the
|
||||||
// reload and keeps the old instance.
|
// reload and keeps the old instance.
|
||||||
if (!transfer_plugin_state(*this, next)) {
|
if (!transfer_plugin_state(*this, next)) {
|
||||||
std::error_code ec;
|
std::error_code ec;
|
||||||
std::filesystem::remove(tmp, ec);
|
std::filesystem::remove(tmp, ec);
|
||||||
Void::Log::warn("Plugin", "reload '{}' aborted: state rejected",
|
Void::Log::warn("Plugin", "reload '{}' aborted: state rejected",
|
||||||
path_.string());
|
path_.string());
|
||||||
return std::unexpected{LoadError::StateRejected};
|
return std::unexpected{LoadError::StateRejected};
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
next.plugin_->on_load();
|
next.plugin_->on_load();
|
||||||
} catch (...) {
|
} catch (...) {
|
||||||
std::error_code ec;
|
std::error_code ec;
|
||||||
std::filesystem::remove(tmp, ec);
|
std::filesystem::remove(tmp, ec);
|
||||||
return std::unexpected{LoadError::ActivationFailed};
|
return std::unexpected{LoadError::ActivationFailed};
|
||||||
}
|
}
|
||||||
if (next.ready_ && next.ready_(next.plugin_) != 0) {
|
if (next.ready_ && next.ready_(next.plugin_) != 0) {
|
||||||
std::error_code ec;
|
std::error_code ec;
|
||||||
std::filesystem::remove(tmp, ec);
|
std::filesystem::remove(tmp, ec);
|
||||||
return std::unexpected{LoadError::ActivationFailed};
|
return std::unexpected{LoadError::ActivationFailed};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Activation succeeded; only now destroy old and install new.
|
// Activation succeeded; only now destroy old and install new.
|
||||||
destroy_current();
|
destroy_current();
|
||||||
*this = std::move(next);
|
*this = std::move(next);
|
||||||
Void::Log::info("Plugin", "reloaded '{}' ({} v{})", path_.string(),
|
Void::Log::info("Plugin", "reloaded '{}' ({} v{})", path_.string(),
|
||||||
info_.name, info_.plugin_version);
|
info_.name, info_.plugin_version);
|
||||||
|
|
||||||
std::error_code ec;
|
std::error_code ec;
|
||||||
std::filesystem::remove(tmp, ec);
|
std::filesystem::remove(tmp, ec);
|
||||||
return {};
|
return {};
|
||||||
#else
|
#else
|
||||||
return std::unexpected{LoadError::NotSupported};
|
return std::unexpected{LoadError::NotSupported};
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace Void::Plugin
|
} // namespace Void::Plugin
|
||||||
+76
-33
@@ -122,8 +122,7 @@ namespace Void::Plugin
|
|||||||
reinterpret_cast<transfer_fn>(dlsym(h, kTransferSymbol));
|
reinterpret_cast<transfer_fn>(dlsym(h, kTransferSymbol));
|
||||||
inst->configure =
|
inst->configure =
|
||||||
reinterpret_cast<configure_fn>(dlsym(h, kConfigureSymbol));
|
reinterpret_cast<configure_fn>(dlsym(h, kConfigureSymbol));
|
||||||
inst->ready =
|
inst->ready = reinterpret_cast<ready_fn>(dlsym(h, kReadySymbol));
|
||||||
reinterpret_cast<ready_fn>(dlsym(h, kReadySymbol));
|
|
||||||
inst->state_version = reinterpret_cast<state_version_fn>(
|
inst->state_version = reinterpret_cast<state_version_fn>(
|
||||||
dlsym(h, kStateVersionSymbol));
|
dlsym(h, kStateVersionSymbol));
|
||||||
inst->serialize =
|
inst->serialize =
|
||||||
@@ -183,10 +182,10 @@ namespace Void::Plugin
|
|||||||
hotswap_copy(const std::filesystem::path& path)
|
hotswap_copy(const std::filesystem::path& path)
|
||||||
{
|
{
|
||||||
static std::atomic<std::uint64_t> counter{0};
|
static std::atomic<std::uint64_t> counter{0};
|
||||||
const auto tmp =
|
const auto tmp = path.parent_path() /
|
||||||
path.parent_path() /
|
(path.filename().string() + ".void_hotswap." +
|
||||||
(path.filename().string() + ".void_hotswap." +
|
std::to_string(counter.fetch_add(
|
||||||
std::to_string(counter.fetch_add(1, std::memory_order_relaxed)));
|
1, std::memory_order_relaxed)));
|
||||||
std::error_code ec;
|
std::error_code ec;
|
||||||
std::filesystem::copy_file(
|
std::filesystem::copy_file(
|
||||||
path, tmp, std::filesystem::copy_options::overwrite_existing,
|
path, tmp, std::filesystem::copy_options::overwrite_existing,
|
||||||
@@ -251,8 +250,7 @@ namespace Void::Plugin
|
|||||||
} catch (...) {
|
} catch (...) {
|
||||||
return std::unexpected{LoadError::ActivationFailed};
|
return std::unexpected{LoadError::ActivationFailed};
|
||||||
}
|
}
|
||||||
if ((*inst)->ready != nullptr &&
|
if ((*inst)->ready != nullptr && (*inst)->ready((*inst)->plugin) != 0) {
|
||||||
(*inst)->ready((*inst)->plugin) != 0) {
|
|
||||||
return std::unexpected{LoadError::ActivationFailed};
|
return std::unexpected{LoadError::ActivationFailed};
|
||||||
}
|
}
|
||||||
if (m_options.instance_validator &&
|
if (m_options.instance_validator &&
|
||||||
@@ -338,7 +336,7 @@ namespace Void::Plugin
|
|||||||
if (entry == nullptr) {
|
if (entry == nullptr) {
|
||||||
return std::unexpected{LoadError::UnknownPlugin};
|
return std::unexpected{LoadError::UnknownPlugin};
|
||||||
}
|
}
|
||||||
auto result = reload_locked(*entry, name);
|
auto result = reload_locked(*entry, name, entry->path);
|
||||||
if (!result.has_value()) {
|
if (!result.has_value()) {
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
@@ -351,14 +349,51 @@ namespace Void::Plugin
|
|||||||
}
|
}
|
||||||
|
|
||||||
std::expected<void, LoadError>
|
std::expected<void, LoadError>
|
||||||
PluginManager::reload_locked(Entry& entry, std::string_view name)
|
PluginManager::replace(std::string_view name,
|
||||||
|
const std::filesystem::path& newPath)
|
||||||
|
{
|
||||||
|
std::vector<std::function<void(std::string_view)>> callbacks;
|
||||||
|
bool restartWatcher = false;
|
||||||
|
{
|
||||||
|
std::lock_guard lock(m_mutex);
|
||||||
|
auto* entry = find(name);
|
||||||
|
if (entry == nullptr) {
|
||||||
|
return std::unexpected{LoadError::UnknownPlugin};
|
||||||
|
}
|
||||||
|
std::error_code error;
|
||||||
|
if (!std::filesystem::is_regular_file(newPath, error)) {
|
||||||
|
return std::unexpected{LoadError::FileNotFound};
|
||||||
|
}
|
||||||
|
auto result = reload_locked(*entry, name, newPath);
|
||||||
|
if (!result) {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
restartWatcher = entry->watched;
|
||||||
|
if (restartWatcher) {
|
||||||
|
m_watcher.unwatch(entry->path);
|
||||||
|
}
|
||||||
|
entry->path = newPath;
|
||||||
|
callbacks = reload_callbacks_locked();
|
||||||
|
}
|
||||||
|
if (restartWatcher) {
|
||||||
|
watch(name);
|
||||||
|
}
|
||||||
|
for (const auto& callback : callbacks) {
|
||||||
|
callback(name);
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::expected<void, LoadError>
|
||||||
|
PluginManager::reload_locked(Entry& entry, std::string_view name,
|
||||||
|
const std::filesystem::path& sourcePath)
|
||||||
{
|
{
|
||||||
// Copy to a fresh inode so dlopen loads the new bytes instead of
|
// Copy to a fresh inode so dlopen loads the new bytes instead of
|
||||||
// returning the still-open handle for this path. The caller must
|
// returning the still-open handle for this path. The caller must
|
||||||
// have installed the new file via atomic rename (a fresh inode of
|
// have installed the new file via atomic rename (a fresh inode of
|
||||||
// its own) — overwriting the mapped file in place corrupts the
|
// its own) — overwriting the mapped file in place corrupts the
|
||||||
// running instance's mapping (SIGBUS).
|
// running instance's mapping (SIGBUS).
|
||||||
auto tmp = hotswap_copy(entry.path);
|
auto tmp = hotswap_copy(sourcePath);
|
||||||
if (!tmp.has_value()) {
|
if (!tmp.has_value()) {
|
||||||
return std::unexpected{tmp.error()};
|
return std::unexpected{tmp.error()};
|
||||||
}
|
}
|
||||||
@@ -371,6 +406,12 @@ namespace Void::Plugin
|
|||||||
to_string(next.error()));
|
to_string(next.error()));
|
||||||
return std::unexpected{next.error()};
|
return std::unexpected{next.error()};
|
||||||
}
|
}
|
||||||
|
if ((*next)->plugin->name() != name) {
|
||||||
|
Void::Log::warn("Plugin.Manager",
|
||||||
|
"replace '{}' rejected: candidate reports '{}'",
|
||||||
|
name, (*next)->plugin->name());
|
||||||
|
return std::unexpected{LoadError::NameMismatch};
|
||||||
|
}
|
||||||
|
|
||||||
if (m_options.config_provider && (*next)->configure != nullptr) {
|
if (m_options.config_provider && (*next)->configure != nullptr) {
|
||||||
const std::string config = m_options.config_provider(name);
|
const std::string config = m_options.config_provider(name);
|
||||||
@@ -392,16 +433,16 @@ namespace Void::Plugin
|
|||||||
} catch (...) {
|
} catch (...) {
|
||||||
return std::unexpected{LoadError::ActivationFailed};
|
return std::unexpected{LoadError::ActivationFailed};
|
||||||
}
|
}
|
||||||
if ((*next)->ready != nullptr &&
|
if ((*next)->ready != nullptr && (*next)->ready((*next)->plugin) != 0) {
|
||||||
(*next)->ready((*next)->plugin) != 0) {
|
|
||||||
Void::Log::warn("Plugin.Manager",
|
Void::Log::warn("Plugin.Manager",
|
||||||
"reload '{}' aborted: activation failed", name);
|
"reload '{}' aborted: activation failed", name);
|
||||||
return std::unexpected{LoadError::ActivationFailed};
|
return std::unexpected{LoadError::ActivationFailed};
|
||||||
}
|
}
|
||||||
if (m_options.instance_validator &&
|
if (m_options.instance_validator &&
|
||||||
!m_options.instance_validator(*(*next)->plugin, (*next)->info)) {
|
!m_options.instance_validator(*(*next)->plugin, (*next)->info)) {
|
||||||
Void::Log::warn("Plugin.Manager",
|
Void::Log::warn("Plugin.Manager",
|
||||||
"reload '{}' aborted: host validation failed", name);
|
"reload '{}' aborted: host validation failed",
|
||||||
|
name);
|
||||||
return std::unexpected{LoadError::ActivationFailed};
|
return std::unexpected{LoadError::ActivationFailed};
|
||||||
}
|
}
|
||||||
// Atomic swap. The old instance keeps living while any acquired
|
// Atomic swap. The old instance keeps living while any acquired
|
||||||
@@ -421,29 +462,30 @@ namespace Void::Plugin
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
path = entry->path;
|
path = entry->path;
|
||||||
|
entry->watched = true;
|
||||||
}
|
}
|
||||||
const std::string name_str{name};
|
const std::string name_str{name};
|
||||||
m_watcher.watch(
|
m_watcher.watch(path, [this, name_str](
|
||||||
path, [this, name_str](const FileSystem::FileWatcher::Event& e) {
|
const FileSystem::FileWatcher::Event& e) {
|
||||||
if (!e.exists) {
|
if (!e.exists) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
std::vector<std::function<void(std::string_view)>> callbacks;
|
||||||
|
{
|
||||||
|
std::lock_guard lock(m_mutex);
|
||||||
|
auto* entry = find(name_str);
|
||||||
|
if (entry == nullptr) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
std::vector<std::function<void(std::string_view)>> callbacks;
|
if (!reload_locked(*entry, name_str, entry->path).has_value()) {
|
||||||
{
|
return;
|
||||||
std::lock_guard lock(m_mutex);
|
|
||||||
auto* entry = find(name_str);
|
|
||||||
if (entry == nullptr) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!reload_locked(*entry, name_str).has_value()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
callbacks = reload_callbacks_locked();
|
|
||||||
}
|
}
|
||||||
for (const auto& cb : callbacks) {
|
callbacks = reload_callbacks_locked();
|
||||||
cb(name_str);
|
}
|
||||||
}
|
for (const auto& cb : callbacks) {
|
||||||
});
|
cb(name_str);
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
void PluginManager::unwatch(std::string_view name)
|
void PluginManager::unwatch(std::string_view name)
|
||||||
@@ -452,6 +494,7 @@ namespace Void::Plugin
|
|||||||
auto* entry = find(name);
|
auto* entry = find(name);
|
||||||
if (entry != nullptr) {
|
if (entry != nullptr) {
|
||||||
m_watcher.unwatch(entry->path);
|
m_watcher.unwatch(entry->path);
|
||||||
|
entry->watched = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,146 @@
|
|||||||
|
#include <Void/System/SignalWatcher.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cerrno>
|
||||||
|
#include <climits>
|
||||||
|
#include <csignal>
|
||||||
|
#include <cstring>
|
||||||
|
#include <format>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
#ifdef __linux__
|
||||||
|
#include <poll.h>
|
||||||
|
#include <pthread.h>
|
||||||
|
#include <sys/signalfd.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace Void::Process
|
||||||
|
{
|
||||||
|
struct SignalWatcher::Impl {
|
||||||
|
#ifdef __linux__
|
||||||
|
int descriptor{-1};
|
||||||
|
sigset_t previousMask{};
|
||||||
|
bool maskInstalled{false};
|
||||||
|
pthread_t owner{};
|
||||||
|
|
||||||
|
~Impl()
|
||||||
|
{
|
||||||
|
if (descriptor >= 0) {
|
||||||
|
::close(descriptor);
|
||||||
|
}
|
||||||
|
if (maskInstalled &&
|
||||||
|
pthread_equal(owner, pthread_self()) != 0) {
|
||||||
|
(void)::pthread_sigmask(
|
||||||
|
SIG_SETMASK, &previousMask, nullptr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
~Impl() = default;
|
||||||
|
#endif
|
||||||
|
};
|
||||||
|
|
||||||
|
SignalWatcher::SignalWatcher(std::unique_ptr<Impl> impl) noexcept
|
||||||
|
: m_impl(std::move(impl))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
SignalWatcher::~SignalWatcher() = default;
|
||||||
|
SignalWatcher::SignalWatcher(SignalWatcher&&) noexcept = default;
|
||||||
|
SignalWatcher& SignalWatcher::operator=(SignalWatcher&&) noexcept = default;
|
||||||
|
|
||||||
|
Void::Result::Result<SignalWatcher>
|
||||||
|
SignalWatcher::create(std::vector<int> signals)
|
||||||
|
{
|
||||||
|
#ifdef __linux__
|
||||||
|
if (signals.empty()) {
|
||||||
|
signals = {SIGINT, SIGTERM};
|
||||||
|
}
|
||||||
|
sigset_t mask{};
|
||||||
|
if (::sigemptyset(&mask) != 0) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
std::format("Process::SignalWatcher: sigemptyset failed: {}",
|
||||||
|
std::strerror(errno)));
|
||||||
|
}
|
||||||
|
for (const int signal : signals) {
|
||||||
|
if (signal <= 0 || signal == SIGKILL || signal == SIGSTOP ||
|
||||||
|
::sigaddset(&mask, signal) != 0) {
|
||||||
|
return Void::Result::fail(std::format(
|
||||||
|
"Process::SignalWatcher: signal {} cannot be watched",
|
||||||
|
signal));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
auto impl = std::make_unique<Impl>();
|
||||||
|
impl->owner = ::pthread_self();
|
||||||
|
const int maskResult =
|
||||||
|
::pthread_sigmask(SIG_BLOCK, &mask, &impl->previousMask);
|
||||||
|
if (maskResult != 0) {
|
||||||
|
return Void::Result::fail(std::format(
|
||||||
|
"Process::SignalWatcher: pthread_sigmask failed: {}",
|
||||||
|
std::strerror(maskResult)));
|
||||||
|
}
|
||||||
|
impl->maskInstalled = true;
|
||||||
|
impl->descriptor = ::signalfd(-1, &mask, SFD_CLOEXEC | SFD_NONBLOCK);
|
||||||
|
if (impl->descriptor < 0) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
std::format("Process::SignalWatcher: signalfd failed: {}",
|
||||||
|
std::strerror(errno)));
|
||||||
|
}
|
||||||
|
return SignalWatcher{std::move(impl)};
|
||||||
|
#else
|
||||||
|
(void)signals;
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Process::SignalWatcher is currently supported only on Linux");
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::optional<int>>
|
||||||
|
SignalWatcher::wait(std::chrono::milliseconds timeout)
|
||||||
|
{
|
||||||
|
#ifdef __linux__
|
||||||
|
if (!m_impl || m_impl->descriptor < 0) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Process::SignalWatcher::wait: watcher is moved-from");
|
||||||
|
}
|
||||||
|
const int timeoutMs = timeout == std::chrono::milliseconds::max()
|
||||||
|
? -1
|
||||||
|
: static_cast<int>(std::clamp<std::int64_t>(
|
||||||
|
timeout.count(), 0, INT_MAX));
|
||||||
|
pollfd descriptor{m_impl->descriptor, POLLIN, 0};
|
||||||
|
int pollResult = 0;
|
||||||
|
do {
|
||||||
|
pollResult = ::poll(&descriptor, 1, timeoutMs);
|
||||||
|
} while (pollResult < 0 && errno == EINTR);
|
||||||
|
if (pollResult == 0) {
|
||||||
|
return std::optional<int>{};
|
||||||
|
}
|
||||||
|
if (pollResult < 0) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
std::format("Process::SignalWatcher::wait: poll failed: {}",
|
||||||
|
std::strerror(errno)));
|
||||||
|
}
|
||||||
|
if ((descriptor.revents & POLLIN) == 0) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Process::SignalWatcher::wait: signal descriptor closed");
|
||||||
|
}
|
||||||
|
signalfd_siginfo info{};
|
||||||
|
const auto readCount = ::read(m_impl->descriptor, &info, sizeof(info));
|
||||||
|
if (readCount != static_cast<ssize_t>(sizeof(info))) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
std::format("Process::SignalWatcher::wait: read failed: {}",
|
||||||
|
std::strerror(errno)));
|
||||||
|
}
|
||||||
|
return std::optional<int>{static_cast<int>(info.ssi_signo)};
|
||||||
|
#else
|
||||||
|
(void)timeout;
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Process::SignalWatcher is currently supported only on Linux");
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::optional<int>> SignalWatcher::poll()
|
||||||
|
{
|
||||||
|
return wait(std::chrono::milliseconds{0});
|
||||||
|
}
|
||||||
|
} // namespace Void::Process
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
void_add_module(System
|
void_add_module(System
|
||||||
INTERNAL_DEPS Functional
|
INTERNAL_DEPS Functional
|
||||||
|
EXTERNAL_DEPS Threads::Threads
|
||||||
)
|
)
|
||||||
@@ -0,0 +1,488 @@
|
|||||||
|
#include <Void/Update/Feed.hpp>
|
||||||
|
|
||||||
|
#include <Void/Data/Json.hpp>
|
||||||
|
#include <Void/Text/Base64.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cmath>
|
||||||
|
#include <concepts>
|
||||||
|
#include <format>
|
||||||
|
#include <limits>
|
||||||
|
#include <set>
|
||||||
|
#include <tuple>
|
||||||
|
|
||||||
|
namespace Void::Update
|
||||||
|
{
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
using JsonResult = Void::Result::Result<const Json::Value*>;
|
||||||
|
|
||||||
|
[[nodiscard]] JsonResult member(const Json::Value& object,
|
||||||
|
std::string_view name,
|
||||||
|
bool (*predicate)(const Json::Value&),
|
||||||
|
std::string_view expected)
|
||||||
|
{
|
||||||
|
const auto* value = object.find(name);
|
||||||
|
if (value == nullptr || !predicate(*value)) {
|
||||||
|
return Void::Result::fail(std::format(
|
||||||
|
"Update feed: '{}' must be {}", name, expected));
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool is_array(const Json::Value& value) noexcept
|
||||||
|
{
|
||||||
|
return value.is_array();
|
||||||
|
}
|
||||||
|
[[nodiscard]] bool is_string(const Json::Value& value) noexcept
|
||||||
|
{
|
||||||
|
return value.is_string();
|
||||||
|
}
|
||||||
|
[[nodiscard]] bool is_number(const Json::Value& value) noexcept
|
||||||
|
{
|
||||||
|
return value.is_number();
|
||||||
|
}
|
||||||
|
|
||||||
|
template <std::unsigned_integral T>
|
||||||
|
[[nodiscard]] Void::Result::Result<T>
|
||||||
|
unsigned_number(const Json::Value& object, std::string_view name)
|
||||||
|
{
|
||||||
|
auto value = member(object, name, is_number, "an unsigned integer");
|
||||||
|
if (!value) {
|
||||||
|
return std::unexpected{value.error()};
|
||||||
|
}
|
||||||
|
const double number = (*value)->as_number();
|
||||||
|
constexpr double maxSafeInteger = 9'007'199'254'740'991.0;
|
||||||
|
if (!std::isfinite(number) || number < 0 ||
|
||||||
|
std::floor(number) != number || number > maxSafeInteger ||
|
||||||
|
number > static_cast<double>(std::numeric_limits<T>::max())) {
|
||||||
|
return Void::Result::fail(std::format(
|
||||||
|
"Update feed: '{}' is outside its integer range", name));
|
||||||
|
}
|
||||||
|
return static_cast<T>(number);
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<std::string>
|
||||||
|
string_member(const Json::Value& object, std::string_view name)
|
||||||
|
{
|
||||||
|
auto value = member(object, name, is_string, "a string");
|
||||||
|
if (!value) {
|
||||||
|
return std::unexpected{value.error()};
|
||||||
|
}
|
||||||
|
return (*value)->as_string();
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool valid_token(std::string_view value,
|
||||||
|
std::size_t maximum = 128) noexcept
|
||||||
|
{
|
||||||
|
if (value.empty() || value.size() > maximum) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for (const char character : value) {
|
||||||
|
if (!((character >= 'a' && character <= 'z') ||
|
||||||
|
(character >= 'A' && character <= 'Z') ||
|
||||||
|
(character >= '0' && character <= '9') ||
|
||||||
|
character == '.' || character == '_' ||
|
||||||
|
character == '-')) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool valid_sha256(std::string_view value) noexcept
|
||||||
|
{
|
||||||
|
if (value.size() != 64) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return std::ranges::all_of(value, [](const char character) {
|
||||||
|
return (character >= '0' && character <= '9') ||
|
||||||
|
(character >= 'a' && character <= 'f');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool valid_package_type(std::string_view value) noexcept
|
||||||
|
{
|
||||||
|
return !value.empty() && value.size() <= 128 &&
|
||||||
|
std::ranges::all_of(value, [](const char character) {
|
||||||
|
return (character >= 'a' && character <= 'z') ||
|
||||||
|
(character >= '0' && character <= '9') ||
|
||||||
|
character == '.' || character == '-' ||
|
||||||
|
character == '_';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::optional<int>
|
||||||
|
decimal(std::string_view value) noexcept
|
||||||
|
{
|
||||||
|
int result = 0;
|
||||||
|
for (const char character : value) {
|
||||||
|
if (character < '0' || character > '9') {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
result = result * 10 + (character - '0');
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::optional<std::chrono::system_clock::time_point>
|
||||||
|
parse_timestamp(std::string_view value) noexcept
|
||||||
|
{
|
||||||
|
if (value.size() < 20 || value[4] != '-' || value[7] != '-' ||
|
||||||
|
value[10] != 'T' || value[13] != ':' || value[16] != ':' ||
|
||||||
|
value.back() != 'Z') {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
const auto year = decimal(value.substr(0, 4));
|
||||||
|
const auto month = decimal(value.substr(5, 2));
|
||||||
|
const auto day = decimal(value.substr(8, 2));
|
||||||
|
const auto hour = decimal(value.substr(11, 2));
|
||||||
|
const auto minute = decimal(value.substr(14, 2));
|
||||||
|
const auto second = decimal(value.substr(17, 2));
|
||||||
|
if (!year || !month || !day || !hour || !minute || !second ||
|
||||||
|
*hour > 23 || *minute > 59 || *second > 59) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
if (value.size() > 20) {
|
||||||
|
if (value.size() == 21 || value[19] != '.') {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
for (std::size_t index = 20; index + 1 < value.size();
|
||||||
|
++index) {
|
||||||
|
if (value[index] < '0' || value[index] > '9') {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const std::chrono::year_month_day date{
|
||||||
|
std::chrono::year{*year},
|
||||||
|
std::chrono::month{static_cast<unsigned>(*month)},
|
||||||
|
std::chrono::day{static_cast<unsigned>(*day)}};
|
||||||
|
if (!date.ok()) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return std::chrono::sys_days{date} + std::chrono::hours{*hour} +
|
||||||
|
std::chrono::minutes{*minute} +
|
||||||
|
std::chrono::seconds{*second};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<Compatibility>
|
||||||
|
parse_compatibility(const Json::Value& value)
|
||||||
|
{
|
||||||
|
if (!value.is_object()) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Update feed: compatibility must be an object");
|
||||||
|
}
|
||||||
|
Compatibility result;
|
||||||
|
if (const auto* contracts = value.find("versionContracts")) {
|
||||||
|
if (!contracts->is_object()) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Update feed: compatibility.versionContracts must be "
|
||||||
|
"an object");
|
||||||
|
}
|
||||||
|
for (const auto& [name, rangeValue] : contracts->as_object()) {
|
||||||
|
if (!valid_token(name, 256) || !rangeValue.is_string()) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Update feed: invalid version contract");
|
||||||
|
}
|
||||||
|
auto range = Semver::parse_range(rangeValue.as_string());
|
||||||
|
if (!range) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
std::format("Update feed: version contract '{}' "
|
||||||
|
"has an invalid range",
|
||||||
|
name));
|
||||||
|
}
|
||||||
|
result.versionContracts.emplace(name, std::move(*range));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (const auto* contracts = value.find("exactContracts")) {
|
||||||
|
if (!contracts->is_object()) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Update feed: compatibility.exactContracts must be an "
|
||||||
|
"object");
|
||||||
|
}
|
||||||
|
for (const auto& [name, contractValue] :
|
||||||
|
contracts->as_object()) {
|
||||||
|
if (!valid_token(name, 256) || !contractValue.is_string() ||
|
||||||
|
contractValue.as_string().empty() ||
|
||||||
|
contractValue.as_string().size() > 512) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Update feed: invalid exact contract");
|
||||||
|
}
|
||||||
|
result.exactContracts.emplace(name,
|
||||||
|
contractValue.as_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<Release>
|
||||||
|
parse_release(const Json::Value& value)
|
||||||
|
{
|
||||||
|
if (!value.is_object()) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Update feed: release must be an object");
|
||||||
|
}
|
||||||
|
Release release;
|
||||||
|
auto component = string_member(value, "component");
|
||||||
|
if (!component || !valid_token(*component, 256)) {
|
||||||
|
return Void::Result::fail("Update feed: component is invalid");
|
||||||
|
}
|
||||||
|
release.component = std::move(*component);
|
||||||
|
release.artifactId = value.get_str("artifactId");
|
||||||
|
if (!release.artifactId.empty() &&
|
||||||
|
!valid_token(release.artifactId, 256)) {
|
||||||
|
return Void::Result::fail("Update feed: artifactId is invalid");
|
||||||
|
}
|
||||||
|
|
||||||
|
auto channel = string_member(value, "channel");
|
||||||
|
auto versionText = string_member(value, "version");
|
||||||
|
auto platform = string_member(value, "platform");
|
||||||
|
auto architecture = string_member(value, "arch");
|
||||||
|
auto url = string_member(value, "url");
|
||||||
|
auto size = unsigned_number<std::uint64_t>(value, "size");
|
||||||
|
auto sha256 = string_member(value, "sha256");
|
||||||
|
auto packageType = string_member(value, "packageType");
|
||||||
|
if (!channel || !versionText || !platform || !architecture ||
|
||||||
|
!url || !size || !sha256 || !packageType) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Update feed: release has invalid required fields");
|
||||||
|
}
|
||||||
|
const auto cohort = value.get_str("cohort");
|
||||||
|
const auto manifestHash = value.get_str("releaseManifestSha256");
|
||||||
|
const bool urlIsBounded =
|
||||||
|
!url->empty() && url->size() <= 8192 &&
|
||||||
|
std::ranges::none_of(*url, [](const unsigned char character) {
|
||||||
|
return character < 0x20 || character == 0x7f;
|
||||||
|
});
|
||||||
|
if (!valid_token(*channel) ||
|
||||||
|
(!cohort.empty() && !valid_token(cohort, 256)) ||
|
||||||
|
!valid_token(*platform) || !valid_token(*architecture) ||
|
||||||
|
!urlIsBounded || *size == 0 || !valid_sha256(*sha256) ||
|
||||||
|
!valid_package_type(*packageType) ||
|
||||||
|
(!manifestHash.empty() && !valid_sha256(manifestHash))) {
|
||||||
|
return Void::Result::fail("Update feed: release contains an "
|
||||||
|
"unsafe or unsupported field");
|
||||||
|
}
|
||||||
|
auto version = Semver::parse_strict(*versionText);
|
||||||
|
if (!version) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Update feed: release version is invalid SemVer");
|
||||||
|
}
|
||||||
|
release.channel = std::move(*channel);
|
||||||
|
release.version = std::move(*version);
|
||||||
|
release.cohort = cohort;
|
||||||
|
release.platform = std::move(*platform);
|
||||||
|
release.architecture = std::move(*architecture);
|
||||||
|
release.url = std::move(*url);
|
||||||
|
release.size = *size;
|
||||||
|
release.sha256 = std::move(*sha256);
|
||||||
|
release.packageType = std::move(*packageType);
|
||||||
|
release.releaseManifestSha256 = manifestHash;
|
||||||
|
const auto* compatibility = value.find("compatibility");
|
||||||
|
if (compatibility) {
|
||||||
|
auto parsedCompatibility = parse_compatibility(*compatibility);
|
||||||
|
if (!parsedCompatibility) {
|
||||||
|
return std::unexpected{parsedCompatibility.error()};
|
||||||
|
}
|
||||||
|
release.compatibility = std::move(*parsedCompatibility);
|
||||||
|
}
|
||||||
|
return release;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<Feed>
|
||||||
|
parse_feed(std::string_view payload,
|
||||||
|
const VerificationPolicy& policy)
|
||||||
|
{
|
||||||
|
auto document = Json::parse(payload);
|
||||||
|
if (!document || !document->is_object()) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Update feed: signed payload is not a JSON object");
|
||||||
|
}
|
||||||
|
auto schema =
|
||||||
|
unsigned_number<std::uint32_t>(*document, "schemaVersion");
|
||||||
|
auto feedId = string_member(*document, "feedId");
|
||||||
|
auto sequence =
|
||||||
|
unsigned_number<std::uint64_t>(*document, "sequence");
|
||||||
|
auto generated = string_member(*document, "generatedAt");
|
||||||
|
auto expires = string_member(*document, "expiresAt");
|
||||||
|
auto releasesValue =
|
||||||
|
member(*document, "releases", is_array, "an array");
|
||||||
|
if (!schema || !feedId || !sequence || !generated || !expires ||
|
||||||
|
!releasesValue) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Update feed: invalid top-level fields");
|
||||||
|
}
|
||||||
|
if (*schema != 1 || !valid_token(*feedId, 256)) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Update feed: unsupported schema or invalid feedId");
|
||||||
|
}
|
||||||
|
if (policy.minimumSequence &&
|
||||||
|
*sequence <= *policy.minimumSequence) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Update feed: sequence is not newer than the replay floor");
|
||||||
|
}
|
||||||
|
const auto generatedAt = parse_timestamp(*generated);
|
||||||
|
const auto expiresAt = parse_timestamp(*expires);
|
||||||
|
if (!generatedAt || !expiresAt || *expiresAt <= *generatedAt) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Update feed: timestamps are invalid");
|
||||||
|
}
|
||||||
|
if (policy.requireUnexpired && policy.now >= *expiresAt) {
|
||||||
|
return Void::Result::fail("Update feed: feed has expired");
|
||||||
|
}
|
||||||
|
const auto& values = (*releasesValue)->as_array();
|
||||||
|
if (values.size() > policy.maxReleases) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Update feed: release count exceeds policy");
|
||||||
|
}
|
||||||
|
Feed feed{.schemaVersion = *schema,
|
||||||
|
.feedId = std::move(*feedId),
|
||||||
|
.sequence = *sequence,
|
||||||
|
.generatedAt = *generatedAt,
|
||||||
|
.expiresAt = *expiresAt};
|
||||||
|
std::set<std::tuple<std::string, std::string, std::string,
|
||||||
|
std::string, std::string, std::string>>
|
||||||
|
identities;
|
||||||
|
feed.releases.reserve(values.size());
|
||||||
|
for (const auto& value : values) {
|
||||||
|
auto release = parse_release(value);
|
||||||
|
if (!release) {
|
||||||
|
return std::unexpected{release.error()};
|
||||||
|
}
|
||||||
|
auto identity =
|
||||||
|
std::tuple{release->component, release->artifactId,
|
||||||
|
release->channel, release->version.to_string(),
|
||||||
|
release->platform, release->architecture};
|
||||||
|
if (!identities.insert(std::move(identity)).second) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Update feed: ambiguous duplicate release identity");
|
||||||
|
}
|
||||||
|
feed.releases.push_back(std::move(*release));
|
||||||
|
}
|
||||||
|
return feed;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool compatible(const Compatibility& compatibility,
|
||||||
|
const Environment& environment) noexcept
|
||||||
|
{
|
||||||
|
for (const auto& [name, range] : compatibility.versionContracts) {
|
||||||
|
const auto installed = environment.versionContracts.find(name);
|
||||||
|
if (installed == environment.versionContracts.end() ||
|
||||||
|
!range.contains(installed->second)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const auto& [name, value] : compatibility.exactContracts) {
|
||||||
|
const auto installed = environment.exactContracts.find(name);
|
||||||
|
if (installed == environment.exactContracts.end() ||
|
||||||
|
installed->second != value) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Result::Result<Feed>
|
||||||
|
parseFeedPayload(std::string_view payload,
|
||||||
|
const VerificationPolicy& policy)
|
||||||
|
{
|
||||||
|
if (payload.size() > policy.maxPayloadBytes) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Update feed: payload exceeds policy size");
|
||||||
|
}
|
||||||
|
return parse_feed(payload, policy);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<VerifiedFeed>
|
||||||
|
verifyFeedEnvelope(std::string_view envelopeJson, const Keyring& keys,
|
||||||
|
const VerificationPolicy& policy)
|
||||||
|
{
|
||||||
|
if (envelopeJson.size() > policy.maxEnvelopeBytes) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Update feed: envelope exceeds policy size");
|
||||||
|
}
|
||||||
|
auto envelope = Json::parse(envelopeJson);
|
||||||
|
if (!envelope || !envelope->is_object()) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Update feed: envelope is not a JSON object");
|
||||||
|
}
|
||||||
|
auto schema =
|
||||||
|
unsigned_number<std::uint32_t>(*envelope, "schemaVersion");
|
||||||
|
auto keyId = string_member(*envelope, "keyId");
|
||||||
|
auto payloadText = string_member(*envelope, "payload");
|
||||||
|
auto signatureText = string_member(*envelope, "signature");
|
||||||
|
if (!schema || !keyId || !payloadText || !signatureText ||
|
||||||
|
*schema != 1 || !valid_token(*keyId, 256)) {
|
||||||
|
return Void::Result::fail("Update feed: invalid envelope fields");
|
||||||
|
}
|
||||||
|
const auto key = keys.find(*keyId);
|
||||||
|
if (key == keys.end()) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Update feed: envelope key is not trusted");
|
||||||
|
}
|
||||||
|
auto payload = Encoding::Base64::decode_url(*payloadText);
|
||||||
|
auto signature = Encoding::Base64::decode_url(*signatureText);
|
||||||
|
if (!payload || !signature ||
|
||||||
|
payload->size() > policy.maxPayloadBytes) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Update feed: invalid or oversized envelope encoding");
|
||||||
|
}
|
||||||
|
const auto signatureBytes =
|
||||||
|
std::as_bytes(std::span{signature->data(), signature->size()});
|
||||||
|
const auto payloadBytes =
|
||||||
|
std::as_bytes(std::span{payload->data(), payload->size()});
|
||||||
|
auto valid =
|
||||||
|
Crypto::verifyEd25519(payloadBytes, signatureBytes, key->second);
|
||||||
|
if (!valid) {
|
||||||
|
return std::unexpected{valid.error()};
|
||||||
|
}
|
||||||
|
if (!*valid) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
"Update feed: signature verification failed");
|
||||||
|
}
|
||||||
|
auto feed = parseFeedPayload(*payload, policy);
|
||||||
|
if (!feed) {
|
||||||
|
return std::unexpected{feed.error()};
|
||||||
|
}
|
||||||
|
return VerifiedFeed{.feed = std::move(*feed),
|
||||||
|
.keyId = std::move(*keyId),
|
||||||
|
.signedPayload = std::move(*payload)};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<Release> selectRelease(const Feed& feed,
|
||||||
|
const SelectionRequest& request)
|
||||||
|
{
|
||||||
|
const Release* selected = nullptr;
|
||||||
|
for (const auto& release : feed.releases) {
|
||||||
|
if (release.component != request.component ||
|
||||||
|
release.artifactId != request.artifactId ||
|
||||||
|
release.channel != request.channel ||
|
||||||
|
release.platform != request.environment.platform ||
|
||||||
|
release.architecture != request.environment.architecture ||
|
||||||
|
(request.requiredCohort &&
|
||||||
|
release.cohort != *request.requiredCohort) ||
|
||||||
|
!compatible(release.compatibility, request.environment)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (request.currentVersion) {
|
||||||
|
const auto comparison =
|
||||||
|
release.version <=> *request.currentVersion;
|
||||||
|
if (comparison == 0 && !request.includeCurrent) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (comparison < 0 && !request.allowDowngrade) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (selected == nullptr || release.version > selected->version) {
|
||||||
|
selected = &release;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (selected == nullptr) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return *selected;
|
||||||
|
}
|
||||||
|
} // namespace Void::Update
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,3 @@
|
|||||||
|
void_add_module(Update
|
||||||
|
INTERNAL_DEPS Crypto Data Functional System Text
|
||||||
|
)
|
||||||
@@ -81,6 +81,19 @@ if(_all_generated)
|
|||||||
endforeach()
|
endforeach()
|
||||||
|
|
||||||
add_test(NAME VoidTests COMMAND VoidTests)
|
add_test(NAME VoidTests COMMAND VoidTests)
|
||||||
|
|
||||||
|
add_test(NAME VoidInstalledComponentConsumers
|
||||||
|
COMMAND ${CMAKE_COMMAND}
|
||||||
|
-DVOID_BUILD_DIR=${CMAKE_BINARY_DIR}
|
||||||
|
-DVOID_TEST_SOURCE_DIR=${CMAKE_CURRENT_SOURCE_DIR}/package
|
||||||
|
-DVOID_TEST_ROOT=${CMAKE_CURRENT_BINARY_DIR}/package-consumer
|
||||||
|
-DVOID_CXX_COMPILER=${CMAKE_CXX_COMPILER}
|
||||||
|
-DVOID_CTEST_COMMAND=${CMAKE_CTEST_COMMAND}
|
||||||
|
-DVOID_BUILD_CONFIG=$<CONFIG>
|
||||||
|
-P ${CMAKE_CURRENT_SOURCE_DIR}/package/InstalledComponents.cmake
|
||||||
|
)
|
||||||
|
set_tests_properties(VoidInstalledComponentConsumers PROPERTIES
|
||||||
|
DEPENDS VoidTests)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
# ── Test-support libraries ────────────────────────────────────────────────────
|
# ── Test-support libraries ────────────────────────────────────────────────────
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
cmake_minimum_required(VERSION 4.0)
|
||||||
|
project(VoidAuditedConsumer LANGUAGES CXX)
|
||||||
|
|
||||||
|
find_package(Void CONFIG REQUIRED COMPONENTS
|
||||||
|
Archive
|
||||||
|
Binary
|
||||||
|
Crypto
|
||||||
|
Plugin
|
||||||
|
System
|
||||||
|
Update
|
||||||
|
)
|
||||||
|
|
||||||
|
add_executable(void_audited_consumer main.cpp)
|
||||||
|
target_link_libraries(void_audited_consumer PRIVATE
|
||||||
|
Void::Archive
|
||||||
|
Void::Binary
|
||||||
|
Void::Crypto
|
||||||
|
Void::Plugin
|
||||||
|
Void::System
|
||||||
|
Void::Update
|
||||||
|
)
|
||||||
|
|
||||||
|
enable_testing()
|
||||||
|
add_test(NAME VoidAuditedConsumer COMMAND void_audited_consumer)
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
#include <Void/Archive/Archive.hpp>
|
||||||
|
#include <Void/Binary/Reader.hpp>
|
||||||
|
#include <Void/Crypto/Crypto.hpp>
|
||||||
|
#include <Void/Plugin/Loader.hpp>
|
||||||
|
#include <Void/Plugin/Manager.hpp>
|
||||||
|
#include <Void/System/SignalWatcher.hpp>
|
||||||
|
#include <Void/Update/Update.hpp>
|
||||||
|
|
||||||
|
#include <array>
|
||||||
|
#include <bit>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
|
||||||
|
int main()
|
||||||
|
{
|
||||||
|
const std::array bytes{std::byte{0x01}, std::byte{0x02}};
|
||||||
|
Void::Binary::Reader reader{bytes};
|
||||||
|
const auto value = reader.read<std::uint16_t>(std::endian::big);
|
||||||
|
const auto digest = Void::Crypto::sha256(bytes);
|
||||||
|
const Void::Archive::ExtractionOptions limits{};
|
||||||
|
const Void::Update::VerificationPolicy policy{};
|
||||||
|
const Void::Plugin::PluginManager::Options plugins{};
|
||||||
|
return value && *value == 0x0102 && digest && !digest->empty() &&
|
||||||
|
limits.maxEntries > 0 && policy.maxReleases > 0 &&
|
||||||
|
plugins.debounce_polls > 0
|
||||||
|
? 0
|
||||||
|
: 1;
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
cmake_minimum_required(VERSION 4.0)
|
||||||
|
project(VoidBinaryConsumer LANGUAGES CXX)
|
||||||
|
|
||||||
|
find_package(Void CONFIG REQUIRED COMPONENTS Binary)
|
||||||
|
|
||||||
|
add_executable(void_binary_consumer main.cpp)
|
||||||
|
target_link_libraries(void_binary_consumer PRIVATE Void::Binary)
|
||||||
|
|
||||||
|
enable_testing()
|
||||||
|
add_test(NAME VoidBinaryConsumer COMMAND void_binary_consumer)
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
#include <Void/Binary/Reader.hpp>
|
||||||
|
|
||||||
|
#include <array>
|
||||||
|
#include <bit>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
|
||||||
|
int main()
|
||||||
|
{
|
||||||
|
const std::array bytes{std::byte{0x01}, std::byte{0x02}};
|
||||||
|
Void::Binary::Reader reader{bytes};
|
||||||
|
const auto value = reader.read<std::uint16_t>(std::endian::big);
|
||||||
|
return value && *value == 0x0102 ? 0 : 1;
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
cmake_minimum_required(VERSION 4.0)
|
||||||
|
|
||||||
|
foreach(required IN ITEMS VOID_BUILD_DIR VOID_TEST_SOURCE_DIR VOID_TEST_ROOT
|
||||||
|
VOID_CXX_COMPILER VOID_CTEST_COMMAND)
|
||||||
|
if(NOT DEFINED ${required} OR "${${required}}" STREQUAL "")
|
||||||
|
message(FATAL_ERROR "${required} is required")
|
||||||
|
endif()
|
||||||
|
endforeach()
|
||||||
|
|
||||||
|
file(REMOVE_RECURSE "${VOID_TEST_ROOT}")
|
||||||
|
set(install_prefix "${VOID_TEST_ROOT}/install")
|
||||||
|
|
||||||
|
set(install_command "${CMAKE_COMMAND}" --install "${VOID_BUILD_DIR}"
|
||||||
|
--prefix "${install_prefix}")
|
||||||
|
if(DEFINED VOID_BUILD_CONFIG AND NOT VOID_BUILD_CONFIG STREQUAL "")
|
||||||
|
list(APPEND install_command --config "${VOID_BUILD_CONFIG}")
|
||||||
|
endif()
|
||||||
|
execute_process(COMMAND ${install_command} COMMAND_ERROR_IS_FATAL ANY)
|
||||||
|
|
||||||
|
function(run_consumer name)
|
||||||
|
set(source_dir "${VOID_TEST_SOURCE_DIR}/${name}")
|
||||||
|
set(build_dir "${VOID_TEST_ROOT}/${name}")
|
||||||
|
execute_process(
|
||||||
|
COMMAND "${CMAKE_COMMAND}" -S "${source_dir}" -B "${build_dir}"
|
||||||
|
"-DCMAKE_PREFIX_PATH=${install_prefix}"
|
||||||
|
"-DCMAKE_CXX_COMPILER=${VOID_CXX_COMPILER}"
|
||||||
|
${ARGN}
|
||||||
|
COMMAND_ERROR_IS_FATAL ANY)
|
||||||
|
|
||||||
|
set(build_command "${CMAKE_COMMAND}" --build "${build_dir}")
|
||||||
|
set(test_command "${VOID_CTEST_COMMAND}" --test-dir "${build_dir}"
|
||||||
|
--output-on-failure)
|
||||||
|
if(DEFINED VOID_BUILD_CONFIG AND NOT VOID_BUILD_CONFIG STREQUAL "")
|
||||||
|
list(APPEND build_command --config "${VOID_BUILD_CONFIG}")
|
||||||
|
list(APPEND test_command -C "${VOID_BUILD_CONFIG}")
|
||||||
|
endif()
|
||||||
|
execute_process(COMMAND ${build_command} COMMAND_ERROR_IS_FATAL ANY)
|
||||||
|
execute_process(COMMAND ${test_command} COMMAND_ERROR_IS_FATAL ANY)
|
||||||
|
endfunction()
|
||||||
|
|
||||||
|
# A header-only component must remain independently consumable even when every
|
||||||
|
# optional external package is explicitly unavailable.
|
||||||
|
run_consumer(Binary
|
||||||
|
-DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE
|
||||||
|
-DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE
|
||||||
|
-DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE
|
||||||
|
-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE
|
||||||
|
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE
|
||||||
|
-DCMAKE_DISABLE_FIND_PACKAGE_Threads=TRUE)
|
||||||
|
|
||||||
|
# Exercise the transitive dependency closure for every newly extracted runtime
|
||||||
|
# module while proving unrelated Sodium and SQLite dependencies are not loaded.
|
||||||
|
run_consumer(Audited
|
||||||
|
-DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE
|
||||||
|
-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE
|
||||||
|
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
#include <Void/Archive/Archive.hpp>
|
||||||
|
#include <Void/System/TempDir.hpp>
|
||||||
|
#include <Void/Testing/Assert.hpp>
|
||||||
|
#include <Void/Testing/Test.hpp>
|
||||||
|
|
||||||
|
#include <array>
|
||||||
|
#include <atomic>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <fstream>
|
||||||
|
#include <memory>
|
||||||
|
#include <span>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <system_error>
|
||||||
|
#include <thread>
|
||||||
|
|
||||||
|
#include <archive.h>
|
||||||
|
#include <archive_entry.h>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
struct ArchiveEntry {
|
||||||
|
std::string_view path;
|
||||||
|
std::string_view contents;
|
||||||
|
unsigned int type{AE_IFREG};
|
||||||
|
std::string_view link;
|
||||||
|
};
|
||||||
|
|
||||||
|
void write_archive(const std::filesystem::path &path,
|
||||||
|
std::span<const ArchiveEntry>
|
||||||
|
entries)
|
||||||
|
{
|
||||||
|
using Writer = std::unique_ptr<archive, decltype(&archive_write_free)>;
|
||||||
|
using Entry =
|
||||||
|
std::unique_ptr<archive_entry, decltype(&archive_entry_free)>;
|
||||||
|
Writer writer{archive_write_new(), &archive_write_free};
|
||||||
|
Void::Testing::require(static_cast<bool>(writer));
|
||||||
|
Void::Testing::require(archive_write_add_filter_zstd(writer.get()) ==
|
||||||
|
ARCHIVE_OK);
|
||||||
|
Void::Testing::require(archive_write_set_format_pax_restricted(
|
||||||
|
writer.get()) == ARCHIVE_OK);
|
||||||
|
#ifdef _WIN32
|
||||||
|
Void::Testing::require(archive_write_open_filename_w(
|
||||||
|
writer.get(), path.c_str()) == ARCHIVE_OK);
|
||||||
|
#else
|
||||||
|
Void::Testing::require(archive_write_open_filename(
|
||||||
|
writer.get(), path.c_str()) == ARCHIVE_OK);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
for (const auto &specification : entries) {
|
||||||
|
Entry entry{archive_entry_new(), &archive_entry_free};
|
||||||
|
const std::string entryPath{specification.path};
|
||||||
|
archive_entry_set_pathname(entry.get(), entryPath.c_str());
|
||||||
|
archive_entry_set_filetype(entry.get(), specification.type);
|
||||||
|
archive_entry_set_perm(
|
||||||
|
entry.get(), specification.type == AE_IFDIR ? 0755 : 0644);
|
||||||
|
if (specification.type == AE_IFREG) {
|
||||||
|
archive_entry_set_size(
|
||||||
|
entry.get(),
|
||||||
|
static_cast<la_int64_t>(specification.contents.size()));
|
||||||
|
}
|
||||||
|
if (!specification.link.empty()) {
|
||||||
|
const std::string link{specification.link};
|
||||||
|
archive_entry_set_symlink(entry.get(), link.c_str());
|
||||||
|
}
|
||||||
|
Void::Testing::require(
|
||||||
|
archive_write_header(writer.get(), entry.get()) == ARCHIVE_OK);
|
||||||
|
|
||||||
|
std::size_t offset = 0;
|
||||||
|
while (offset < specification.contents.size()) {
|
||||||
|
const auto count = archive_write_data(
|
||||||
|
writer.get(), specification.contents.data() + offset,
|
||||||
|
specification.contents.size() - offset);
|
||||||
|
Void::Testing::require(count > 0);
|
||||||
|
offset += static_cast<std::size_t>(count);
|
||||||
|
}
|
||||||
|
Void::Testing::require(archive_write_finish_entry(writer.get()) ==
|
||||||
|
ARCHIVE_OK);
|
||||||
|
}
|
||||||
|
Void::Testing::require(archive_write_close(writer.get()) == ARCHIVE_OK);
|
||||||
|
}
|
||||||
|
|
||||||
|
void write_archive(const std::filesystem::path &path,
|
||||||
|
std::string_view entryPath, std::string_view contents,
|
||||||
|
unsigned int type = AE_IFREG, std::string_view link = {})
|
||||||
|
{
|
||||||
|
const std::array entries{ArchiveEntry{entryPath, contents, type, link}};
|
||||||
|
write_archive(path, entries);
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool
|
||||||
|
extraction_file_visible(const std::filesystem::path &destination)
|
||||||
|
{
|
||||||
|
std::error_code error;
|
||||||
|
if (std::filesystem::exists(destination / "anchor", error)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
error.clear();
|
||||||
|
for (std::filesystem::directory_iterator iterator{destination, error};
|
||||||
|
!error && iterator != std::filesystem::directory_iterator{};
|
||||||
|
iterator.increment(error)) {
|
||||||
|
if (iterator->path().filename().string().starts_with(
|
||||||
|
".void-archive-")) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Testing::Test archive_extracts_bounded_tar_zstd()
|
||||||
|
{
|
||||||
|
Void::FileSystem::TempDir temporary{"void_archive_"};
|
||||||
|
const auto source = temporary / "package.tar.zst";
|
||||||
|
const auto destination = temporary / "output";
|
||||||
|
write_archive(source, "bin/tool", "payload");
|
||||||
|
auto extracted = Void::Archive::extract(source, destination);
|
||||||
|
Void::Testing::require(extracted.has_value());
|
||||||
|
Void::Testing::expect_eq(extracted->entries, std::size_t{1});
|
||||||
|
Void::Testing::expect_eq(extracted->bytes, std::uint64_t{7});
|
||||||
|
std::ifstream input{destination / "bin/tool"};
|
||||||
|
std::string contents;
|
||||||
|
input >> contents;
|
||||||
|
Void::Testing::expect_eq(contents, std::string{"payload"});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test archive_accepts_explicit_directory_entries()
|
||||||
|
{
|
||||||
|
Void::FileSystem::TempDir temporary{"void_archive_"};
|
||||||
|
const auto source = temporary / "directory.tar.zst";
|
||||||
|
const auto destination = temporary / "output";
|
||||||
|
const std::array entries{ArchiveEntry{"bin/", {}, AE_IFDIR},
|
||||||
|
ArchiveEntry{"bin/tool", "payload"}};
|
||||||
|
write_archive(source, entries);
|
||||||
|
|
||||||
|
auto extracted = Void::Archive::extract(source, destination);
|
||||||
|
Void::Testing::require(extracted.has_value());
|
||||||
|
Void::Testing::expect_eq(extracted->entries, std::size_t{2});
|
||||||
|
Void::Testing::expect_eq(extracted->bytes, std::uint64_t{7});
|
||||||
|
Void::Testing::expect(std::filesystem::is_directory(destination / "bin"));
|
||||||
|
std::ifstream input{destination / "bin/tool"};
|
||||||
|
std::string contents;
|
||||||
|
input >> contents;
|
||||||
|
Void::Testing::expect_eq(contents, std::string{"payload"});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test archive_rejects_traversal_and_links()
|
||||||
|
{
|
||||||
|
Void::FileSystem::TempDir temporary{"void_archive_"};
|
||||||
|
const auto traversal = temporary / "traversal.tar.zst";
|
||||||
|
write_archive(traversal, "../escape", "bad");
|
||||||
|
Void::Testing::expect(
|
||||||
|
!Void::Archive::extract(traversal, temporary / "out1").has_value());
|
||||||
|
Void::Testing::expect(
|
||||||
|
!std::filesystem::exists(temporary.path() / "escape"));
|
||||||
|
const auto symlink = temporary / "symlink.tar.zst";
|
||||||
|
write_archive(symlink, "link", {}, AE_IFLNK, "/tmp/escape");
|
||||||
|
Void::Testing::expect(
|
||||||
|
!Void::Archive::extract(symlink, temporary / "out2").has_value());
|
||||||
|
const auto trailingFile = temporary / "trailing-file.tar.zst";
|
||||||
|
write_archive(trailingFile, "file/", "bad");
|
||||||
|
Void::Testing::expect(
|
||||||
|
!Void::Archive::extract(trailingFile, temporary / "out3").has_value());
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test archive_rejects_symlink_parent()
|
||||||
|
{
|
||||||
|
#ifndef _WIN32
|
||||||
|
Void::FileSystem::TempDir temporary{"void_archive_"};
|
||||||
|
const auto source = temporary / "parent-link.tar.zst";
|
||||||
|
const auto destination = temporary / "output";
|
||||||
|
const auto outside = temporary / "outside";
|
||||||
|
std::filesystem::create_directories(destination);
|
||||||
|
std::filesystem::create_directories(outside);
|
||||||
|
std::filesystem::create_directory_symlink(outside, destination / "parent");
|
||||||
|
write_archive(source, "parent/escape", "bad");
|
||||||
|
|
||||||
|
Void::Testing::expect(
|
||||||
|
!Void::Archive::extract(source, destination).has_value());
|
||||||
|
Void::Testing::expect(!std::filesystem::exists(outside / "escape"));
|
||||||
|
#else
|
||||||
|
Void::Testing::expect(true);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test archive_pins_destination_during_path_swap()
|
||||||
|
{
|
||||||
|
#ifndef _WIN32
|
||||||
|
Void::FileSystem::TempDir temporary{"void_archive_"};
|
||||||
|
const auto source = temporary / "swap.tar.zst";
|
||||||
|
const auto destination = temporary / "output";
|
||||||
|
const auto displaced = temporary / "displaced";
|
||||||
|
const auto outside = temporary / "outside";
|
||||||
|
std::filesystem::create_directories(destination);
|
||||||
|
std::filesystem::create_directories(outside);
|
||||||
|
|
||||||
|
const std::string largePayload(32U * 1024U * 1024U, 'x');
|
||||||
|
const std::array entries{ArchiveEntry{"anchor", largePayload},
|
||||||
|
ArchiveEntry{"second", "safe"}};
|
||||||
|
write_archive(source, entries);
|
||||||
|
|
||||||
|
std::atomic_bool extractionFinished{false};
|
||||||
|
std::atomic_bool swapped{false};
|
||||||
|
std::jthread attacker{[&] {
|
||||||
|
while (!extractionFinished.load(std::memory_order_acquire)) {
|
||||||
|
if (!extraction_file_visible(destination)) {
|
||||||
|
std::this_thread::yield();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::error_code error;
|
||||||
|
std::filesystem::rename(destination, displaced, error);
|
||||||
|
if (error) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
std::filesystem::create_directory_symlink(outside, destination,
|
||||||
|
error);
|
||||||
|
if (error) {
|
||||||
|
std::error_code restoreError;
|
||||||
|
std::filesystem::rename(displaced, destination, restoreError);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
swapped.store(true, std::memory_order_release);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}};
|
||||||
|
|
||||||
|
auto extracted = Void::Archive::extract(source, destination);
|
||||||
|
extractionFinished.store(true, std::memory_order_release);
|
||||||
|
attacker.join();
|
||||||
|
|
||||||
|
Void::Testing::require(swapped.load(std::memory_order_acquire));
|
||||||
|
Void::Testing::require(extracted.has_value());
|
||||||
|
Void::Testing::expect(!std::filesystem::exists(outside / "second"));
|
||||||
|
Void::Testing::expect(std::filesystem::exists(displaced / "second"));
|
||||||
|
#else
|
||||||
|
Void::Testing::expect(true);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test archive_enforces_actual_size_limit()
|
||||||
|
{
|
||||||
|
Void::FileSystem::TempDir temporary{"void_archive_"};
|
||||||
|
const auto source = temporary / "large.tar.zst";
|
||||||
|
write_archive(source, "file", "12345678");
|
||||||
|
Void::Archive::ExtractionOptions options;
|
||||||
|
options.maxFileBytes = 4;
|
||||||
|
Void::Testing::expect(
|
||||||
|
!Void::Archive::extract(source, temporary / "out", options)
|
||||||
|
.has_value());
|
||||||
|
Void::Testing::expect(
|
||||||
|
!std::filesystem::exists(temporary.path() / "out/file"));
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
#include <Void/Binary/Reader.hpp>
|
||||||
|
#include <Void/Testing/Assert.hpp>
|
||||||
|
#include <Void/Testing/Test.hpp>
|
||||||
|
|
||||||
|
#include <array>
|
||||||
|
|
||||||
|
Void::Testing::Test binary_reader_checks_bounds_and_endian()
|
||||||
|
{
|
||||||
|
const std::array bytes{std::byte{0x12}, std::byte{0x34}, std::byte{0x56}};
|
||||||
|
Void::Binary::Reader reader{bytes};
|
||||||
|
auto value = reader.read<std::uint16_t>(std::endian::big);
|
||||||
|
Void::Testing::require(value.has_value());
|
||||||
|
Void::Testing::expect_eq(*value, static_cast<std::uint16_t>(0x1234));
|
||||||
|
Void::Testing::expect_eq(reader.position(), static_cast<std::size_t>(2));
|
||||||
|
auto overflow = reader.read<std::uint16_t>(std::endian::big);
|
||||||
|
Void::Testing::expect(!overflow.has_value());
|
||||||
|
Void::Testing::expect_eq(reader.position(), static_cast<std::size_t>(2));
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test binary_reader_subreader_is_bounded()
|
||||||
|
{
|
||||||
|
const std::array bytes{std::byte{'a'}, std::byte{'b'}, std::byte{'c'}};
|
||||||
|
Void::Binary::Reader reader{bytes};
|
||||||
|
auto child = reader.subreader(2);
|
||||||
|
Void::Testing::require(child.has_value());
|
||||||
|
auto value = child->readString(2);
|
||||||
|
Void::Testing::require(value.has_value());
|
||||||
|
Void::Testing::expect_eq(*value, std::string{"ab"});
|
||||||
|
Void::Testing::expect(!child->readBytes(1).has_value());
|
||||||
|
Void::Testing::expect_eq(reader.remaining(), static_cast<std::size_t>(1));
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
#include <Void/Crypto/Crypto.hpp>
|
||||||
|
#include <Void/System/TempDir.hpp>
|
||||||
|
#include <Void/Testing/Assert.hpp>
|
||||||
|
#include <Void/Testing/Test.hpp>
|
||||||
|
#include <Void/Text/Hex.hpp>
|
||||||
|
|
||||||
|
#include <array>
|
||||||
|
#include <fstream>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
std::string hex(const Void::Crypto::Digest& digest)
|
||||||
|
{
|
||||||
|
return Void::Encoding::Hex::encode(digest);
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Testing::Test crypto_known_hash_vectors()
|
||||||
|
{
|
||||||
|
auto sha1 = Void::Crypto::sha1("abc");
|
||||||
|
auto sha256 = Void::Crypto::sha256("abc");
|
||||||
|
auto sha512 = Void::Crypto::sha512("abc");
|
||||||
|
Void::Testing::require(sha1.has_value());
|
||||||
|
Void::Testing::require(sha256.has_value());
|
||||||
|
Void::Testing::require(sha512.has_value());
|
||||||
|
Void::Testing::expect_eq(
|
||||||
|
hex(*sha1), std::string{"a9993e364706816aba3e25717850c26c9cd0d89d"});
|
||||||
|
Void::Testing::expect_eq(hex(*sha256),
|
||||||
|
std::string{"ba7816bf8f01cfea414140de5dae2223b0036"
|
||||||
|
"1a396177a9cb410ff61f20015ad"});
|
||||||
|
Void::Testing::expect_eq(
|
||||||
|
hex(*sha512),
|
||||||
|
std::string{
|
||||||
|
"ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a21"
|
||||||
|
"92992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test crypto_streaming_and_file_hash_match()
|
||||||
|
{
|
||||||
|
auto hasher =
|
||||||
|
Void::Crypto::Hasher::create(Void::Crypto::HashAlgorithm::Sha256);
|
||||||
|
Void::Testing::require(hasher.has_value());
|
||||||
|
Void::Testing::require(hasher->update("ab").has_value());
|
||||||
|
Void::Testing::require(hasher->update("c").has_value());
|
||||||
|
auto streamed = hasher->finalize();
|
||||||
|
Void::Testing::require(streamed.has_value());
|
||||||
|
Void::Testing::expect(!hasher->update("again").has_value());
|
||||||
|
|
||||||
|
Void::FileSystem::TempDir temporary{"void_crypto_"};
|
||||||
|
const auto path = temporary / "data";
|
||||||
|
std::ofstream{path, std::ios::binary} << "abc";
|
||||||
|
auto file = Void::Crypto::sha256File(path);
|
||||||
|
Void::Testing::require(file.has_value());
|
||||||
|
Void::Testing::expect_eq(*file, *streamed);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test crypto_ed25519_rfc8032_vector()
|
||||||
|
{
|
||||||
|
const auto publicText = Void::Encoding::Hex::decode(
|
||||||
|
"d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a");
|
||||||
|
const auto signatureText = Void::Encoding::Hex::decode(
|
||||||
|
"e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e06522490155"
|
||||||
|
"5fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b");
|
||||||
|
Void::Testing::require(publicText.has_value());
|
||||||
|
Void::Testing::require(signatureText.has_value());
|
||||||
|
const auto publicKey =
|
||||||
|
std::as_bytes(std::span{publicText->data(), publicText->size()});
|
||||||
|
const auto signature =
|
||||||
|
std::as_bytes(std::span{signatureText->data(), signatureText->size()});
|
||||||
|
auto valid = Void::Crypto::verifyEd25519({}, signature, publicKey);
|
||||||
|
Void::Testing::require(valid.has_value());
|
||||||
|
Void::Testing::expect(*valid);
|
||||||
|
const std::array message{std::byte{1}};
|
||||||
|
auto invalid = Void::Crypto::verifyEd25519(message, signature, publicKey);
|
||||||
|
Void::Testing::require(invalid.has_value());
|
||||||
|
Void::Testing::expect(!*invalid);
|
||||||
|
}
|
||||||
@@ -90,6 +90,40 @@ Void::Testing::Test manager_reload_migrates_v1_state_to_v2()
|
|||||||
Void::Testing::expect_eq(stateful(h)->counter(), 3); // migrated
|
Void::Testing::expect_eq(stateful(h)->counter(), 3); // migrated
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test manager_replace_migrates_from_immutable_new_path()
|
||||||
|
{
|
||||||
|
PluginManager manager;
|
||||||
|
Void::Testing::require(manager.load(VOID_STATEFUL_V1_PATH).has_value());
|
||||||
|
auto pinned = manager.acquire("StatefulPlugin");
|
||||||
|
stateful(pinned)->bump();
|
||||||
|
stateful(pinned)->bump();
|
||||||
|
auto replaced = manager.replace("StatefulPlugin", VOID_STATEFUL_V2_PATH);
|
||||||
|
Void::Testing::require(replaced.has_value());
|
||||||
|
Void::Testing::expect_eq(stateful(pinned)->schema_version(), 1);
|
||||||
|
auto current = manager.acquire("StatefulPlugin");
|
||||||
|
Void::Testing::expect_eq(stateful(current)->schema_version(), 2);
|
||||||
|
Void::Testing::expect_eq(stateful(current)->counter(), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test manager_replace_failure_keeps_current_generation()
|
||||||
|
{
|
||||||
|
PluginManager manager;
|
||||||
|
Void::Testing::require(manager.load(VOID_STATEFUL_V1_PATH).has_value());
|
||||||
|
auto before = manager.acquire("StatefulPlugin");
|
||||||
|
stateful(before)->bump();
|
||||||
|
#ifdef VOID_TEST_PLUGIN_PATH
|
||||||
|
auto mismatch = manager.replace("StatefulPlugin", VOID_TEST_PLUGIN_PATH);
|
||||||
|
Void::Testing::expect(!mismatch.has_value());
|
||||||
|
Void::Testing::expect(mismatch.error() == LoadError::NameMismatch);
|
||||||
|
#endif
|
||||||
|
auto missing = manager.replace("StatefulPlugin", "/no/such/plugin.so");
|
||||||
|
Void::Testing::expect(!missing.has_value());
|
||||||
|
Void::Testing::expect(missing.error() == LoadError::FileNotFound);
|
||||||
|
auto after = manager.acquire("StatefulPlugin");
|
||||||
|
Void::Testing::expect_eq(stateful(after)->schema_version(), 1);
|
||||||
|
Void::Testing::expect_eq(stateful(after)->counter(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
Void::Testing::Test manager_pinned_handle_survives_reload()
|
Void::Testing::Test manager_pinned_handle_survives_reload()
|
||||||
{
|
{
|
||||||
Void::FileSystem::TempDir tmp{"void_mgr"};
|
Void::FileSystem::TempDir tmp{"void_mgr"};
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
#include <Void/System/SignalWatcher.hpp>
|
||||||
|
#include <Void/Testing/Assert.hpp>
|
||||||
|
#include <Void/Testing/Test.hpp>
|
||||||
|
|
||||||
|
#include <chrono>
|
||||||
|
#include <csignal>
|
||||||
|
|
||||||
|
Void::Testing::Test signal_watcher_polls_and_receives_blocked_signal()
|
||||||
|
{
|
||||||
|
#ifdef __linux__
|
||||||
|
auto watcher = Void::Process::SignalWatcher::create({SIGUSR1});
|
||||||
|
Void::Testing::require(watcher.has_value());
|
||||||
|
auto empty = watcher->poll();
|
||||||
|
Void::Testing::require(empty.has_value());
|
||||||
|
Void::Testing::expect(!empty->has_value());
|
||||||
|
Void::Testing::require(::raise(SIGUSR1) == 0);
|
||||||
|
auto received = watcher->wait(std::chrono::milliseconds{100});
|
||||||
|
Void::Testing::require(received.has_value());
|
||||||
|
Void::Testing::require(received->has_value());
|
||||||
|
Void::Testing::expect_eq(**received, SIGUSR1);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
@@ -1,240 +1,290 @@
|
|||||||
|
#include <Void/Testing/Assert.hpp>
|
||||||
|
#include <Void/Testing/Test.hpp>
|
||||||
#include <Void/Text/Base64.hpp>
|
#include <Void/Text/Base64.hpp>
|
||||||
#include <Void/Text/Hex.hpp>
|
#include <Void/Text/Hex.hpp>
|
||||||
#include <Void/Text/Html.hpp>
|
#include <Void/Text/Html.hpp>
|
||||||
#include <Void/Text/Url.hpp>
|
#include <Void/Text/Url.hpp>
|
||||||
#include <Void/Testing/Assert.hpp>
|
|
||||||
#include <Void/Testing/Test.hpp>
|
|
||||||
|
|
||||||
// ── Base64 encode ─────────────────────────────────────────────────────────────
|
#include <array>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <span>
|
||||||
|
|
||||||
|
// ── Base64 encode
|
||||||
|
// ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
Void::Testing::Test base64_encode_empty()
|
Void::Testing::Test base64_encode_empty()
|
||||||
{
|
{
|
||||||
Void::Testing::expect(Void::Encoding::Base64::encode("").empty());
|
Void::Testing::expect(Void::Encoding::Base64::encode("").empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test base64_encode_man()
|
Void::Testing::Test base64_encode_man()
|
||||||
{
|
{
|
||||||
Void::Testing::expect_eq(Void::Encoding::Base64::encode("Man"),
|
Void::Testing::expect_eq(Void::Encoding::Base64::encode("Man"),
|
||||||
std::string{"TWFu"});
|
std::string{"TWFu"});
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test base64_encode_ma()
|
Void::Testing::Test base64_encode_ma()
|
||||||
{
|
{
|
||||||
Void::Testing::expect_eq(Void::Encoding::Base64::encode("Ma"),
|
Void::Testing::expect_eq(Void::Encoding::Base64::encode("Ma"),
|
||||||
std::string{"TWE="});
|
std::string{"TWE="});
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test base64_encode_m()
|
Void::Testing::Test base64_encode_m()
|
||||||
{
|
{
|
||||||
Void::Testing::expect_eq(Void::Encoding::Base64::encode("M"),
|
Void::Testing::expect_eq(Void::Encoding::Base64::encode("M"),
|
||||||
std::string{"TQ=="});
|
std::string{"TQ=="});
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test base64_encode_hello_world()
|
Void::Testing::Test base64_encode_hello_world()
|
||||||
{
|
{
|
||||||
Void::Testing::expect_eq(Void::Encoding::Base64::encode("Hello, World!"),
|
Void::Testing::expect_eq(Void::Encoding::Base64::encode("Hello, World!"),
|
||||||
std::string{"SGVsbG8sIFdvcmxkIQ=="});
|
std::string{"SGVsbG8sIFdvcmxkIQ=="});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Base64 decode ─────────────────────────────────────────────────────────────
|
// ── Base64 decode
|
||||||
|
// ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
Void::Testing::Test base64_decode_empty()
|
Void::Testing::Test base64_decode_empty()
|
||||||
{
|
{
|
||||||
const auto r = Void::Encoding::Base64::decode("");
|
const auto r = Void::Encoding::Base64::decode("");
|
||||||
Void::Testing::expect(r.has_value());
|
Void::Testing::expect(r.has_value());
|
||||||
Void::Testing::expect(r->empty());
|
Void::Testing::expect(r->empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test base64_decode_man()
|
Void::Testing::Test base64_decode_man()
|
||||||
{
|
{
|
||||||
const auto r = Void::Encoding::Base64::decode("TWFu");
|
const auto r = Void::Encoding::Base64::decode("TWFu");
|
||||||
Void::Testing::expect(r.has_value());
|
Void::Testing::expect(r.has_value());
|
||||||
Void::Testing::expect_eq(*r, std::string{"Man"});
|
Void::Testing::expect_eq(*r, std::string{"Man"});
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test base64_decode_with_padding()
|
Void::Testing::Test base64_decode_with_padding()
|
||||||
{
|
{
|
||||||
const auto r = Void::Encoding::Base64::decode("SGVsbG8sIFdvcmxkIQ==");
|
const auto r = Void::Encoding::Base64::decode("SGVsbG8sIFdvcmxkIQ==");
|
||||||
Void::Testing::expect(r.has_value());
|
Void::Testing::expect(r.has_value());
|
||||||
Void::Testing::expect_eq(*r, std::string{"Hello, World!"});
|
Void::Testing::expect_eq(*r, std::string{"Hello, World!"});
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test base64_decode_invalid_returns_nullopt()
|
Void::Testing::Test base64_decode_invalid_returns_nullopt()
|
||||||
{
|
{
|
||||||
const auto r = Void::Encoding::Base64::decode("!!");
|
const auto r = Void::Encoding::Base64::decode("!!");
|
||||||
Void::Testing::expect(!r.has_value());
|
Void::Testing::expect(!r.has_value());
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test base64_decode_rejects_malformed_padding()
|
||||||
|
{
|
||||||
|
Void::Testing::expect(!Void::Encoding::Base64::decode("T=WE").has_value());
|
||||||
|
Void::Testing::expect(!Void::Encoding::Base64::decode("TWFu=").has_value());
|
||||||
|
Void::Testing::expect(!Void::Encoding::Base64::decode("TQ===").has_value());
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test base64_decode_rejects_nonzero_trailing_bits()
|
||||||
|
{
|
||||||
|
Void::Testing::expect(!Void::Encoding::Base64::decode("TR==").has_value());
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test base64_round_trip()
|
Void::Testing::Test base64_round_trip()
|
||||||
{
|
{
|
||||||
const std::string original = "The quick brown fox jumps over the lazy dog";
|
const std::string original = "The quick brown fox jumps over the lazy dog";
|
||||||
const auto encoded = Void::Encoding::Base64::encode(original);
|
const auto encoded = Void::Encoding::Base64::encode(original);
|
||||||
const auto decoded = Void::Encoding::Base64::decode(encoded);
|
const auto decoded = Void::Encoding::Base64::decode(encoded);
|
||||||
Void::Testing::expect(decoded.has_value());
|
Void::Testing::expect(decoded.has_value());
|
||||||
Void::Testing::expect_eq(*decoded, original);
|
Void::Testing::expect_eq(*decoded, original);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Base64 URL ────────────────────────────────────────────────────────────────
|
Void::Testing::Test base64_byte_buffer_round_trip()
|
||||||
|
{
|
||||||
|
const std::array<std::uint8_t, 5> original{0x00, 0x7F, 0x80, 0xFE, 0xFF};
|
||||||
|
const auto encoded =
|
||||||
|
Void::Encoding::Base64::encode(std::span<const std::uint8_t>{original});
|
||||||
|
const auto decoded = Void::Encoding::Base64::decode_bytes(encoded);
|
||||||
|
Void::Testing::expect(decoded.has_value());
|
||||||
|
Void::Testing::expect_eq(decoded->size(), original.size());
|
||||||
|
for (std::size_t i = 0; i < original.size(); ++i) {
|
||||||
|
Void::Testing::expect_eq(std::to_integer<std::uint8_t>((*decoded)[i]),
|
||||||
|
original[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Base64 URL
|
||||||
|
// ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
Void::Testing::Test base64url_no_padding()
|
Void::Testing::Test base64url_no_padding()
|
||||||
{
|
{
|
||||||
const auto s = Void::Encoding::Base64::encode_url("Man");
|
const auto s = Void::Encoding::Base64::encode_url("Man");
|
||||||
Void::Testing::expect_eq(s, std::string{"TWFu"});
|
Void::Testing::expect_eq(s, std::string{"TWFu"});
|
||||||
Void::Testing::expect(s.find('=') == std::string::npos);
|
Void::Testing::expect(s.find('=') == std::string::npos);
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test base64url_no_plus_or_slash()
|
Void::Testing::Test base64url_no_plus_or_slash()
|
||||||
{
|
{
|
||||||
// encode something that would produce + or / in standard base64
|
// encode something that would produce + or / in standard base64
|
||||||
const std::string tricky = "\xfb\xff\xfe";
|
const std::string tricky = "\xfb\xff\xfe";
|
||||||
const auto s = Void::Encoding::Base64::encode_url(tricky);
|
const auto s = Void::Encoding::Base64::encode_url(tricky);
|
||||||
Void::Testing::expect(s.find('+') == std::string::npos);
|
Void::Testing::expect(s.find('+') == std::string::npos);
|
||||||
Void::Testing::expect(s.find('/') == std::string::npos);
|
Void::Testing::expect(s.find('/') == std::string::npos);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Hex encode ───────────────────────────────────────────────────────────────
|
// ── Hex encode ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
Void::Testing::Test hex_encode_empty()
|
Void::Testing::Test hex_encode_empty()
|
||||||
{
|
{
|
||||||
Void::Testing::expect(Void::Encoding::Hex::encode("").empty());
|
Void::Testing::expect(Void::Encoding::Hex::encode("").empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test hex_encode_hello()
|
Void::Testing::Test hex_encode_hello()
|
||||||
{
|
{
|
||||||
Void::Testing::expect_eq(Void::Encoding::Hex::encode("Hi"),
|
Void::Testing::expect_eq(Void::Encoding::Hex::encode("Hi"),
|
||||||
std::string{"4869"});
|
std::string{"4869"});
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test hex_encode_binary()
|
Void::Testing::Test hex_encode_binary()
|
||||||
{
|
{
|
||||||
const std::string bin{'\x00', '\xff', '\xab'};
|
const std::string bin{'\x00', '\xff', '\xab'};
|
||||||
Void::Testing::expect_eq(Void::Encoding::Hex::encode(bin),
|
Void::Testing::expect_eq(Void::Encoding::Hex::encode(bin),
|
||||||
std::string{"00ffab"});
|
std::string{"00ffab"});
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test hex_encode_upper()
|
Void::Testing::Test hex_encode_upper()
|
||||||
{
|
{
|
||||||
Void::Testing::expect_eq(Void::Encoding::Hex::encode_upper("Hi"),
|
Void::Testing::expect_eq(Void::Encoding::Hex::encode_upper("Hi"),
|
||||||
std::string{"4869"});
|
std::string{"4869"});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Hex decode ───────────────────────────────────────────────────────────────
|
// ── Hex decode ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
Void::Testing::Test hex_decode_empty()
|
Void::Testing::Test hex_decode_empty()
|
||||||
{
|
{
|
||||||
const auto r = Void::Encoding::Hex::decode("");
|
const auto r = Void::Encoding::Hex::decode("");
|
||||||
Void::Testing::expect(r.has_value());
|
Void::Testing::expect(r.has_value());
|
||||||
Void::Testing::expect(r->empty());
|
Void::Testing::expect(r->empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test hex_decode_hello()
|
Void::Testing::Test hex_decode_hello()
|
||||||
{
|
{
|
||||||
const auto r = Void::Encoding::Hex::decode("4869");
|
const auto r = Void::Encoding::Hex::decode("4869");
|
||||||
Void::Testing::expect(r.has_value());
|
Void::Testing::expect(r.has_value());
|
||||||
Void::Testing::expect_eq(*r, std::string{"Hi"});
|
Void::Testing::expect_eq(*r, std::string{"Hi"});
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test hex_decode_uppercase()
|
Void::Testing::Test hex_decode_uppercase()
|
||||||
{
|
{
|
||||||
const auto r = Void::Encoding::Hex::decode("4869");
|
const auto r = Void::Encoding::Hex::decode("4869");
|
||||||
Void::Testing::expect(r.has_value());
|
Void::Testing::expect(r.has_value());
|
||||||
Void::Testing::expect_eq(*r, std::string{"Hi"});
|
Void::Testing::expect_eq(*r, std::string{"Hi"});
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test hex_decode_odd_length_fails()
|
Void::Testing::Test hex_decode_odd_length_fails()
|
||||||
{
|
{
|
||||||
Void::Testing::expect(!Void::Encoding::Hex::decode("abc").has_value());
|
Void::Testing::expect(!Void::Encoding::Hex::decode("abc").has_value());
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test hex_decode_invalid_char_fails()
|
Void::Testing::Test hex_decode_invalid_char_fails()
|
||||||
{
|
{
|
||||||
Void::Testing::expect(!Void::Encoding::Hex::decode("zz").has_value());
|
Void::Testing::expect(!Void::Encoding::Hex::decode("zz").has_value());
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test hex_round_trip()
|
Void::Testing::Test hex_round_trip()
|
||||||
{
|
{
|
||||||
const std::string original = "binary\x00\x01\x02\xff";
|
const std::string original = "binary\x00\x01\x02\xff";
|
||||||
const auto encoded = Void::Encoding::Hex::encode(original);
|
const auto encoded = Void::Encoding::Hex::encode(original);
|
||||||
const auto decoded = Void::Encoding::Hex::decode(encoded);
|
const auto decoded = Void::Encoding::Hex::decode(encoded);
|
||||||
Void::Testing::expect(decoded.has_value());
|
Void::Testing::expect(decoded.has_value());
|
||||||
Void::Testing::expect_eq(*decoded, original);
|
Void::Testing::expect_eq(*decoded, original);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── URL / percent encoding ─────────────────────────────────────────────────────
|
Void::Testing::Test hex_byte_buffer_round_trip()
|
||||||
|
{
|
||||||
|
const std::array<std::uint8_t, 5> original{0x00, 0x7F, 0x80, 0xFE, 0xFF};
|
||||||
|
const auto encoded =
|
||||||
|
Void::Encoding::Hex::encode(std::span<const std::uint8_t>{original});
|
||||||
|
const auto decoded = Void::Encoding::Hex::decode_bytes(encoded);
|
||||||
|
Void::Testing::expect(decoded.has_value());
|
||||||
|
Void::Testing::expect_eq(decoded->size(), original.size());
|
||||||
|
for (std::size_t i = 0; i < original.size(); ++i) {
|
||||||
|
Void::Testing::expect_eq(std::to_integer<std::uint8_t>((*decoded)[i]),
|
||||||
|
original[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── URL / percent encoding
|
||||||
|
// ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
Void::Testing::Test url_encode_unreserved_passthrough()
|
Void::Testing::Test url_encode_unreserved_passthrough()
|
||||||
{
|
{
|
||||||
Void::Testing::expect_eq(Void::Encoding::Url::encode("AZaz09-._~"),
|
Void::Testing::expect_eq(Void::Encoding::Url::encode("AZaz09-._~"),
|
||||||
std::string{"AZaz09-._~"});
|
std::string{"AZaz09-._~"});
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test url_encode_reserved()
|
Void::Testing::Test url_encode_reserved()
|
||||||
{
|
{
|
||||||
Void::Testing::expect_eq(Void::Encoding::Url::encode("a b/c?d=e&f"),
|
Void::Testing::expect_eq(Void::Encoding::Url::encode("a b/c?d=e&f"),
|
||||||
std::string{"a%20b%2Fc%3Fd%3De%26f"});
|
std::string{"a%20b%2Fc%3Fd%3De%26f"});
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test url_query_encode_space_as_plus()
|
Void::Testing::Test url_query_encode_space_as_plus()
|
||||||
{
|
{
|
||||||
Void::Testing::expect_eq(Void::Encoding::Url::query_encode("a b c"),
|
Void::Testing::expect_eq(Void::Encoding::Url::query_encode("a b c"),
|
||||||
std::string{"a+b+c"});
|
std::string{"a+b+c"});
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test url_decode_basic()
|
Void::Testing::Test url_decode_basic()
|
||||||
{
|
{
|
||||||
const auto r = Void::Encoding::Url::decode("a%20b%2Fc");
|
const auto r = Void::Encoding::Url::decode("a%20b%2Fc");
|
||||||
Void::Testing::expect(r.has_value());
|
Void::Testing::expect(r.has_value());
|
||||||
Void::Testing::expect_eq(*r, std::string{"a b/c"});
|
Void::Testing::expect_eq(*r, std::string{"a b/c"});
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test url_decode_plus_as_space()
|
Void::Testing::Test url_decode_plus_as_space()
|
||||||
{
|
{
|
||||||
const auto r = Void::Encoding::Url::decode("a+b", /*plus_as_space=*/true);
|
const auto r = Void::Encoding::Url::decode("a+b", /*plus_as_space=*/true);
|
||||||
Void::Testing::expect(r.has_value());
|
Void::Testing::expect(r.has_value());
|
||||||
Void::Testing::expect_eq(*r, std::string{"a b"});
|
Void::Testing::expect_eq(*r, std::string{"a b"});
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test url_decode_malformed_fails()
|
Void::Testing::Test url_decode_malformed_fails()
|
||||||
{
|
{
|
||||||
Void::Testing::expect(!Void::Encoding::Url::decode("a%2").has_value());
|
Void::Testing::expect(!Void::Encoding::Url::decode("a%2").has_value());
|
||||||
Void::Testing::expect(!Void::Encoding::Url::decode("a%zz").has_value());
|
Void::Testing::expect(!Void::Encoding::Url::decode("a%zz").has_value());
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test url_round_trip_utf8()
|
Void::Testing::Test url_round_trip_utf8()
|
||||||
{
|
{
|
||||||
const std::string original = "café/naïve?x=1 2";
|
const std::string original = "café/naïve?x=1 2";
|
||||||
const auto enc = Void::Encoding::Url::encode(original);
|
const auto enc = Void::Encoding::Url::encode(original);
|
||||||
const auto dec = Void::Encoding::Url::decode(enc);
|
const auto dec = Void::Encoding::Url::decode(enc);
|
||||||
Void::Testing::expect(dec.has_value());
|
Void::Testing::expect(dec.has_value());
|
||||||
Void::Testing::expect_eq(*dec, original);
|
Void::Testing::expect_eq(*dec, original);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── HTML entity decoding ───────────────────────────────────────────────────────
|
// ── HTML entity decoding
|
||||||
|
// ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
Void::Testing::Test html_named_entities()
|
Void::Testing::Test html_named_entities()
|
||||||
{
|
{
|
||||||
Void::Testing::expect_eq(
|
Void::Testing::expect_eq(
|
||||||
Void::Text::html_unescape("a & b < c > d "e""),
|
Void::Text::html_unescape("a & b < c > d "e""),
|
||||||
std::string{"a & b < c > d \"e\""});
|
std::string{"a & b < c > d \"e\""});
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test html_numeric_decimal()
|
Void::Testing::Test html_numeric_decimal()
|
||||||
{
|
{
|
||||||
Void::Testing::expect_eq(Void::Text::html_unescape("ABC"),
|
Void::Testing::expect_eq(Void::Text::html_unescape("ABC"),
|
||||||
std::string{"ABC"});
|
std::string{"ABC"});
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test html_numeric_hex_utf8()
|
Void::Testing::Test html_numeric_hex_utf8()
|
||||||
{
|
{
|
||||||
// U+1F600 grinning face -> 4-byte UTF-8
|
// U+1F600 grinning face -> 4-byte UTF-8
|
||||||
const auto r = Void::Text::html_unescape("😀");
|
const auto r = Void::Text::html_unescape("😀");
|
||||||
Void::Testing::expect_eq(r.size(), std::size_t{4});
|
Void::Testing::expect_eq(r.size(), std::size_t{4});
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test html_unknown_left_verbatim()
|
Void::Testing::Test html_unknown_left_verbatim()
|
||||||
{
|
{
|
||||||
Void::Testing::expect_eq(Void::Text::html_unescape("a &bogus; b"),
|
Void::Testing::expect_eq(Void::Text::html_unescape("a &bogus; b"),
|
||||||
std::string{"a &bogus; b"});
|
std::string{"a &bogus; b"});
|
||||||
Void::Testing::expect_eq(Void::Text::html_unescape("plain & text"),
|
Void::Testing::expect_eq(Void::Text::html_unescape("plain & text"),
|
||||||
std::string{"plain & text"});
|
std::string{"plain & text"});
|
||||||
}
|
}
|
||||||
@@ -4,158 +4,203 @@
|
|||||||
|
|
||||||
#include <string>
|
#include <string>
|
||||||
|
|
||||||
// ── parse ─────────────────────────────────────────────────────────────────────
|
// ── parse
|
||||||
|
// ─────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
Void::Testing::Test semver_parse_simple()
|
Void::Testing::Test semver_parse_simple()
|
||||||
{
|
{
|
||||||
const auto v = Void::Semver::parse("1.2.3");
|
const auto v = Void::Semver::parse("1.2.3");
|
||||||
Void::Testing::expect(v.has_value());
|
Void::Testing::expect(v.has_value());
|
||||||
Void::Testing::expect_eq(v->major, 1u);
|
Void::Testing::expect_eq(v->major, 1u);
|
||||||
Void::Testing::expect_eq(v->minor, 2u);
|
Void::Testing::expect_eq(v->minor, 2u);
|
||||||
Void::Testing::expect_eq(v->patch, 3u);
|
Void::Testing::expect_eq(v->patch, 3u);
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test semver_parse_with_v_prefix()
|
Void::Testing::Test semver_parse_with_v_prefix()
|
||||||
{
|
{
|
||||||
const auto v = Void::Semver::parse("v2.0.0");
|
const auto v = Void::Semver::parse("v2.0.0");
|
||||||
Void::Testing::expect(v.has_value());
|
Void::Testing::expect(v.has_value());
|
||||||
Void::Testing::expect_eq(v->major, 2u);
|
Void::Testing::expect_eq(v->major, 2u);
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test semver_parse_pre_release()
|
Void::Testing::Test semver_parse_pre_release()
|
||||||
{
|
{
|
||||||
const auto v = Void::Semver::parse("1.0.0-alpha.1");
|
const auto v = Void::Semver::parse("1.0.0-alpha.1");
|
||||||
Void::Testing::expect(v.has_value());
|
Void::Testing::expect(v.has_value());
|
||||||
Void::Testing::expect_eq(v->pre_release, std::string{"alpha.1"});
|
Void::Testing::expect_eq(v->pre_release, std::string{"alpha.1"});
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test semver_parse_build_metadata()
|
Void::Testing::Test semver_parse_build_metadata()
|
||||||
{
|
{
|
||||||
const auto v = Void::Semver::parse("1.0.0+build.123");
|
const auto v = Void::Semver::parse("1.0.0+build.123");
|
||||||
Void::Testing::expect(v.has_value());
|
Void::Testing::expect(v.has_value());
|
||||||
Void::Testing::expect_eq(v->build, std::string{"build.123"});
|
Void::Testing::expect_eq(v->build, std::string{"build.123"});
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test semver_parse_full()
|
Void::Testing::Test semver_parse_full()
|
||||||
{
|
{
|
||||||
const auto v = Void::Semver::parse("2.3.4-beta.2+20240101");
|
const auto v = Void::Semver::parse("2.3.4-beta.2+20240101");
|
||||||
Void::Testing::expect(v.has_value());
|
Void::Testing::expect(v.has_value());
|
||||||
Void::Testing::expect_eq(v->major, 2u);
|
Void::Testing::expect_eq(v->major, 2u);
|
||||||
Void::Testing::expect_eq(v->pre_release, std::string{"beta.2"});
|
Void::Testing::expect_eq(v->pre_release, std::string{"beta.2"});
|
||||||
Void::Testing::expect_eq(v->build, std::string{"20240101"});
|
Void::Testing::expect_eq(v->build, std::string{"20240101"});
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test semver_parse_invalid()
|
Void::Testing::Test semver_parse_invalid()
|
||||||
{
|
{
|
||||||
Void::Testing::expect(!Void::Semver::parse("not-a-version").has_value());
|
Void::Testing::expect(!Void::Semver::parse("not-a-version").has_value());
|
||||||
Void::Testing::expect(!Void::Semver::parse("1.2").has_value());
|
Void::Testing::expect(!Void::Semver::parse("1.2").has_value());
|
||||||
|
Void::Testing::expect(!Void::Semver::parse_strict("v1.2.3").has_value());
|
||||||
|
Void::Testing::expect(!Void::Semver::parse("01.2.3").has_value());
|
||||||
|
Void::Testing::expect(!Void::Semver::parse("1.2.3-alpha.01").has_value());
|
||||||
|
Void::Testing::expect(!Void::Semver::parse("1.2.3-alpha..1").has_value());
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── to_string ─────────────────────────────────────────────────────────────────
|
// ── to_string
|
||||||
|
// ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
Void::Testing::Test semver_to_string_simple()
|
Void::Testing::Test semver_to_string_simple()
|
||||||
{
|
{
|
||||||
Void::Semver::Version v{1, 2, 3};
|
Void::Semver::Version v{1, 2, 3};
|
||||||
Void::Testing::expect_eq(v.to_string(), std::string{"1.2.3"});
|
Void::Testing::expect_eq(v.to_string(), std::string{"1.2.3"});
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test semver_to_string_with_pre_release()
|
Void::Testing::Test semver_to_string_with_pre_release()
|
||||||
{
|
{
|
||||||
Void::Semver::Version v{1, 0, 0};
|
Void::Semver::Version v{1, 0, 0};
|
||||||
v.pre_release = "alpha";
|
v.pre_release = "alpha";
|
||||||
Void::Testing::expect_eq(v.to_string(), std::string{"1.0.0-alpha"});
|
Void::Testing::expect_eq(v.to_string(), std::string{"1.0.0-alpha"});
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test semver_round_trip()
|
Void::Testing::Test semver_round_trip()
|
||||||
{
|
{
|
||||||
const auto v = Void::Semver::parse("3.1.4-rc.1+build1");
|
const auto v = Void::Semver::parse("3.1.4-rc.1+build1");
|
||||||
Void::Testing::expect(v.has_value());
|
Void::Testing::expect(v.has_value());
|
||||||
Void::Testing::expect_eq(v->to_string(), std::string{"3.1.4-rc.1+build1"});
|
Void::Testing::expect_eq(v->to_string(), std::string{"3.1.4-rc.1+build1"});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── comparison ───────────────────────────────────────────────────────────────
|
// ── comparison ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
Void::Testing::Test semver_compare_major()
|
Void::Testing::Test semver_compare_major()
|
||||||
{
|
{
|
||||||
const auto a = *Void::Semver::parse("2.0.0");
|
const auto a = *Void::Semver::parse("2.0.0");
|
||||||
const auto b = *Void::Semver::parse("1.9.9");
|
const auto b = *Void::Semver::parse("1.9.9");
|
||||||
Void::Testing::expect(a > b);
|
Void::Testing::expect(a > b);
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test semver_compare_minor()
|
Void::Testing::Test semver_compare_minor()
|
||||||
{
|
{
|
||||||
const auto a = *Void::Semver::parse("1.2.0");
|
const auto a = *Void::Semver::parse("1.2.0");
|
||||||
const auto b = *Void::Semver::parse("1.1.9");
|
const auto b = *Void::Semver::parse("1.1.9");
|
||||||
Void::Testing::expect(a > b);
|
Void::Testing::expect(a > b);
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test semver_compare_patch()
|
Void::Testing::Test semver_compare_patch()
|
||||||
{
|
{
|
||||||
const auto a = *Void::Semver::parse("1.0.1");
|
const auto a = *Void::Semver::parse("1.0.1");
|
||||||
const auto b = *Void::Semver::parse("1.0.0");
|
const auto b = *Void::Semver::parse("1.0.0");
|
||||||
Void::Testing::expect(a > b);
|
Void::Testing::expect(a > b);
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test semver_release_gt_pre_release()
|
Void::Testing::Test semver_release_gt_pre_release()
|
||||||
{
|
{
|
||||||
const auto a = *Void::Semver::parse("1.0.0");
|
const auto a = *Void::Semver::parse("1.0.0");
|
||||||
const auto b = *Void::Semver::parse("1.0.0-alpha");
|
const auto b = *Void::Semver::parse("1.0.0-alpha");
|
||||||
Void::Testing::expect(a > b);
|
Void::Testing::expect(a > b);
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test semver_equal()
|
Void::Testing::Test semver_equal()
|
||||||
{
|
{
|
||||||
const auto a = *Void::Semver::parse("1.2.3");
|
const auto a = *Void::Semver::parse("1.2.3");
|
||||||
const auto b = *Void::Semver::parse("1.2.3");
|
const auto b = *Void::Semver::parse("1.2.3");
|
||||||
Void::Testing::expect(a == b);
|
Void::Testing::expect(a == b);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test semver_prerelease_precedence_is_spec_compliant()
|
||||||
|
{
|
||||||
|
const auto rc2 = *Void::Semver::parse("1.0.0-rc.2");
|
||||||
|
const auto rc10 = *Void::Semver::parse("1.0.0-rc.10");
|
||||||
|
const auto numeric = *Void::Semver::parse("1.0.0-1");
|
||||||
|
const auto alpha = *Void::Semver::parse("1.0.0-alpha");
|
||||||
|
Void::Testing::expect(rc10 > rc2);
|
||||||
|
Void::Testing::expect(numeric < alpha);
|
||||||
|
Void::Testing::expect(*Void::Semver::parse("1.0.0-alpha") <
|
||||||
|
*Void::Semver::parse("1.0.0-alpha.1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test semver_version_ranges()
|
||||||
|
{
|
||||||
|
auto bounded = Void::Semver::parse_range(">=1.2.0 <2.0.0");
|
||||||
|
auto caret = Void::Semver::parse_range("^1.2.3");
|
||||||
|
auto wildcard = Void::Semver::parse_range("1.4.x || 2.0.0");
|
||||||
|
Void::Testing::require(bounded.has_value());
|
||||||
|
Void::Testing::require(caret.has_value());
|
||||||
|
Void::Testing::require(wildcard.has_value());
|
||||||
|
Void::Testing::expect(bounded->contains(*Void::Semver::parse("1.9.9")));
|
||||||
|
Void::Testing::expect(!bounded->contains(*Void::Semver::parse("2.0.0")));
|
||||||
|
Void::Testing::expect(caret->contains(*Void::Semver::parse("1.8.0")));
|
||||||
|
Void::Testing::expect(!caret->contains(*Void::Semver::parse("2.0.0")));
|
||||||
|
Void::Testing::expect(wildcard->contains(*Void::Semver::parse("1.4.9")));
|
||||||
|
Void::Testing::expect(wildcard->contains(*Void::Semver::parse("2.0.0")));
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test semver_version_ranges_reject_overflowing_upper_bounds()
|
||||||
|
{
|
||||||
|
Void::Testing::expect(
|
||||||
|
!Void::Semver::parse_range("^4294967295.0.0").has_value());
|
||||||
|
Void::Testing::expect(
|
||||||
|
!Void::Semver::parse_range("4294967295.x").has_value());
|
||||||
|
Void::Testing::expect(
|
||||||
|
!Void::Semver::parse_range("1.4294967295.x").has_value());
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── bump ─────────────────────────────────────────────────────────────────────
|
// ── bump ─────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
Void::Testing::Test semver_bump_major()
|
Void::Testing::Test semver_bump_major()
|
||||||
{
|
{
|
||||||
const auto v = Void::Semver::Version{1, 2, 3};
|
const auto v = Void::Semver::Version{1, 2, 3};
|
||||||
const auto b = v.bumped_major();
|
const auto b = v.bumped_major();
|
||||||
Void::Testing::expect_eq(b.major, 2u);
|
Void::Testing::expect_eq(b.major, 2u);
|
||||||
Void::Testing::expect_eq(b.minor, 0u);
|
Void::Testing::expect_eq(b.minor, 0u);
|
||||||
Void::Testing::expect_eq(b.patch, 0u);
|
Void::Testing::expect_eq(b.patch, 0u);
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test semver_bump_minor()
|
Void::Testing::Test semver_bump_minor()
|
||||||
{
|
{
|
||||||
const auto v = Void::Semver::Version{1, 2, 3};
|
const auto v = Void::Semver::Version{1, 2, 3};
|
||||||
const auto b = v.bumped_minor();
|
const auto b = v.bumped_minor();
|
||||||
Void::Testing::expect_eq(b.minor, 3u);
|
Void::Testing::expect_eq(b.minor, 3u);
|
||||||
Void::Testing::expect_eq(b.patch, 0u);
|
Void::Testing::expect_eq(b.patch, 0u);
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test semver_bump_patch()
|
Void::Testing::Test semver_bump_patch()
|
||||||
{
|
{
|
||||||
const auto v = Void::Semver::Version{1, 2, 3};
|
const auto v = Void::Semver::Version{1, 2, 3};
|
||||||
Void::Testing::expect_eq(v.bumped_patch().patch, 4u);
|
Void::Testing::expect_eq(v.bumped_patch().patch, 4u);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── compatible_with ───────────────────────────────────────────────────────────
|
// ── compatible_with
|
||||||
|
// ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
Void::Testing::Test semver_compatible_same_major()
|
Void::Testing::Test semver_compatible_same_major()
|
||||||
{
|
{
|
||||||
const auto a = *Void::Semver::parse("1.3.0");
|
const auto a = *Void::Semver::parse("1.3.0");
|
||||||
const auto req = *Void::Semver::parse("1.2.0");
|
const auto req = *Void::Semver::parse("1.2.0");
|
||||||
Void::Testing::expect(a.compatible_with(req));
|
Void::Testing::expect(a.compatible_with(req));
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test semver_incompatible_different_major()
|
Void::Testing::Test semver_incompatible_different_major()
|
||||||
{
|
{
|
||||||
const auto a = *Void::Semver::parse("2.0.0");
|
const auto a = *Void::Semver::parse("2.0.0");
|
||||||
const auto req = *Void::Semver::parse("1.9.9");
|
const auto req = *Void::Semver::parse("1.9.9");
|
||||||
Void::Testing::expect(!a.compatible_with(req));
|
Void::Testing::expect(!a.compatible_with(req));
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Testing::Test semver_is_stable()
|
Void::Testing::Test semver_is_stable()
|
||||||
{
|
{
|
||||||
Void::Testing::expect(Void::Semver::Version{1,0,0}.is_stable());
|
Void::Testing::expect(Void::Semver::Version{1, 0, 0}.is_stable());
|
||||||
Void::Testing::expect(!Void::Semver::Version{0,9,0}.is_stable());
|
Void::Testing::expect(!Void::Semver::Version{0, 9, 0}.is_stable());
|
||||||
Void::Semver::Version pre{1,0,0};
|
Void::Semver::Version pre{1, 0, 0};
|
||||||
pre.pre_release = "alpha";
|
pre.pre_release = "alpha";
|
||||||
Void::Testing::expect(!pre.is_stable());
|
Void::Testing::expect(!pre.is_stable());
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,830 @@
|
|||||||
|
#include <Void/Update/Update.hpp>
|
||||||
|
#include <Void/System/TempDir.hpp>
|
||||||
|
#include <Void/Testing/Assert.hpp>
|
||||||
|
#include <Void/Testing/Test.hpp>
|
||||||
|
#include <Void/Text/Base64.hpp>
|
||||||
|
#include <Void/Text/Hex.hpp>
|
||||||
|
|
||||||
|
#include <array>
|
||||||
|
#include <cstring>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <format>
|
||||||
|
#include <fstream>
|
||||||
|
#include <iterator>
|
||||||
|
#include <memory>
|
||||||
|
|
||||||
|
#include <openssl/evp.h>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
constexpr std::string_view payload = R"json({
|
||||||
|
"schemaVersion": 1,
|
||||||
|
"feedId": "vendor-main",
|
||||||
|
"sequence": 7,
|
||||||
|
"generatedAt": "2026-01-01T00:00:00Z",
|
||||||
|
"expiresAt": "2099-01-01T00:00:00Z",
|
||||||
|
"releases": [{
|
||||||
|
"component": "service",
|
||||||
|
"artifactId": "main",
|
||||||
|
"channel": "stable",
|
||||||
|
"version": "1.2.0",
|
||||||
|
"cohort": "linux-abi-2",
|
||||||
|
"platform": "linux",
|
||||||
|
"arch": "x86_64",
|
||||||
|
"url": "https://updates.example.invalid/service-1.2.0.tar.zst",
|
||||||
|
"size": 1234,
|
||||||
|
"sha256": "1111111111111111111111111111111111111111111111111111111111111111",
|
||||||
|
"packageType": "tar.zst",
|
||||||
|
"compatibility": {
|
||||||
|
"versionContracts": {"host.api": ">=1.0.0 <2.0.0"},
|
||||||
|
"exactContracts": {"plugin.abi": "2"}
|
||||||
|
},
|
||||||
|
"releaseManifestSha256": "2222222222222222222222222222222222222222222222222222222222222222"
|
||||||
|
}]
|
||||||
|
})json";
|
||||||
|
|
||||||
|
std::string sign(std::string_view message)
|
||||||
|
{
|
||||||
|
const auto seedText = Void::Encoding::Hex::decode(
|
||||||
|
"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60");
|
||||||
|
Void::Testing::require(seedText.has_value());
|
||||||
|
using Key = std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)>;
|
||||||
|
using Context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>;
|
||||||
|
Key key{EVP_PKEY_new_raw_private_key(
|
||||||
|
EVP_PKEY_ED25519, nullptr,
|
||||||
|
reinterpret_cast<const unsigned char*>(seedText->data()),
|
||||||
|
seedText->size()),
|
||||||
|
&EVP_PKEY_free};
|
||||||
|
Void::Testing::require(static_cast<bool>(key));
|
||||||
|
Context context{EVP_MD_CTX_new(), &EVP_MD_CTX_free};
|
||||||
|
Void::Testing::require(static_cast<bool>(context));
|
||||||
|
Void::Testing::require(EVP_DigestSignInit(context.get(), nullptr,
|
||||||
|
nullptr, nullptr,
|
||||||
|
key.get()) == 1);
|
||||||
|
std::string signature(64, '\0');
|
||||||
|
std::size_t size = signature.size();
|
||||||
|
Void::Testing::require(
|
||||||
|
EVP_DigestSign(
|
||||||
|
context.get(),
|
||||||
|
reinterpret_cast<unsigned char*>(signature.data()), &size,
|
||||||
|
reinterpret_cast<const unsigned char*>(message.data()),
|
||||||
|
message.size()) == 1);
|
||||||
|
signature.resize(size);
|
||||||
|
return signature;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Update::Keyring keyring()
|
||||||
|
{
|
||||||
|
const auto publicText = Void::Encoding::Hex::decode(
|
||||||
|
"d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a");
|
||||||
|
Void::Testing::require(publicText.has_value());
|
||||||
|
Void::Update::Ed25519PublicKey key{};
|
||||||
|
std::memcpy(key.data(), publicText->data(), key.size());
|
||||||
|
return {{"test-key", key}};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string envelope(std::string signature)
|
||||||
|
{
|
||||||
|
return std::format("{{\"schemaVersion\":1,\"keyId\":\"test-key\","
|
||||||
|
"\"payload\":\"{}\",\"signature\":\"{}\"}}",
|
||||||
|
Void::Encoding::Base64::encode_url(payload),
|
||||||
|
Void::Encoding::Base64::encode_url(signature));
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Testing::Test update_feed_verifies_before_parsing()
|
||||||
|
{
|
||||||
|
auto verified =
|
||||||
|
Void::Update::verifyFeedEnvelope(envelope(sign(payload)), keyring());
|
||||||
|
Void::Testing::require(verified.has_value());
|
||||||
|
Void::Testing::expect_eq(verified->feed.feedId, std::string{"vendor-main"});
|
||||||
|
Void::Testing::expect_eq(verified->feed.sequence, std::uint64_t{7});
|
||||||
|
Void::Testing::expect_eq(verified->feed.releases.size(), std::size_t{1});
|
||||||
|
Void::Testing::expect_eq(verified->signedPayload, std::string{payload});
|
||||||
|
|
||||||
|
auto badSignature = sign(payload);
|
||||||
|
badSignature.front() ^= 1;
|
||||||
|
Void::Testing::expect(!Void::Update::verifyFeedEnvelope(
|
||||||
|
envelope(std::move(badSignature)), keyring())
|
||||||
|
.has_value());
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test update_feed_unsigned_parse_replay_and_selection()
|
||||||
|
{
|
||||||
|
auto parsed = Void::Update::parseFeedPayload(payload);
|
||||||
|
Void::Testing::require(parsed.has_value());
|
||||||
|
Void::Update::VerificationPolicy replay;
|
||||||
|
replay.minimumSequence = 7;
|
||||||
|
Void::Testing::expect(
|
||||||
|
!Void::Update::parseFeedPayload(payload, replay).has_value());
|
||||||
|
|
||||||
|
auto newer = parsed->releases.front();
|
||||||
|
newer.version = *Void::Semver::parse("1.3.0");
|
||||||
|
parsed->releases.push_back(newer);
|
||||||
|
Void::Update::SelectionRequest request{
|
||||||
|
.component = "service",
|
||||||
|
.artifactId = "main",
|
||||||
|
.channel = "stable",
|
||||||
|
.environment = {.versionContracts = {{"host.api",
|
||||||
|
*Void::Semver::parse("1.5.0")}},
|
||||||
|
.exactContracts = {{"plugin.abi", "2"}},
|
||||||
|
.platform = "linux",
|
||||||
|
.architecture = "x86_64"},
|
||||||
|
.currentVersion = *Void::Semver::parse("1.1.0")};
|
||||||
|
auto selected = Void::Update::selectRelease(*parsed, request);
|
||||||
|
Void::Testing::require(selected.has_value());
|
||||||
|
Void::Testing::expect_eq(selected->version.to_string(),
|
||||||
|
std::string{"1.3.0"});
|
||||||
|
request.environment.exactContracts["plugin.abi"] = "3";
|
||||||
|
Void::Testing::expect(
|
||||||
|
!Void::Update::selectRelease(*parsed, request).has_value());
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test update_feed_rejects_empty_fractional_timestamp()
|
||||||
|
{
|
||||||
|
std::string malformed{payload};
|
||||||
|
const auto timestamp = malformed.find("2026-01-01T00:00:00Z");
|
||||||
|
Void::Testing::require(timestamp != std::string::npos);
|
||||||
|
malformed.replace(timestamp,
|
||||||
|
std::string_view{"2026-01-01T00:00:00Z"}.size(),
|
||||||
|
"2026-01-01T00:00:00.Z");
|
||||||
|
Void::Testing::expect(
|
||||||
|
!Void::Update::parseFeedPayload(malformed).has_value());
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test update_feed_rejects_noncanonical_sha256()
|
||||||
|
{
|
||||||
|
std::string uppercaseArtifactHash{payload};
|
||||||
|
const auto artifactHash = uppercaseArtifactHash.find(std::string(64, '1'));
|
||||||
|
Void::Testing::require(artifactHash != std::string::npos);
|
||||||
|
uppercaseArtifactHash[artifactHash] = 'A';
|
||||||
|
Void::Testing::expect(
|
||||||
|
!Void::Update::parseFeedPayload(uppercaseArtifactHash).has_value());
|
||||||
|
|
||||||
|
std::string uppercaseManifestHash{payload};
|
||||||
|
const auto manifestHash = uppercaseManifestHash.find(std::string(64, '2'));
|
||||||
|
Void::Testing::require(manifestHash != std::string::npos);
|
||||||
|
uppercaseManifestHash[manifestHash] = 'B';
|
||||||
|
Void::Testing::expect(
|
||||||
|
!Void::Update::parseFeedPayload(uppercaseManifestHash).has_value());
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test update_feed_accepts_generic_artifact_kinds()
|
||||||
|
{
|
||||||
|
std::string sharedLibrary{payload};
|
||||||
|
constexpr std::string_view packageField{"\"packageType\": \"tar.zst\""};
|
||||||
|
const auto package = sharedLibrary.find(packageField);
|
||||||
|
Void::Testing::require(package != std::string::npos);
|
||||||
|
sharedLibrary.replace(package, packageField.size(),
|
||||||
|
"\"packageType\": \"shared-library\"");
|
||||||
|
const auto manifest = sharedLibrary.find(
|
||||||
|
",\n \"releaseManifestSha256\": "
|
||||||
|
"\"2222222222222222222222222222222222222222222222222222222222222222\"");
|
||||||
|
Void::Testing::require(manifest != std::string::npos);
|
||||||
|
sharedLibrary.erase(manifest,
|
||||||
|
std::string_view{",\n \"releaseManifestSha256\": "
|
||||||
|
"\"22222222222222222222222222222222222"
|
||||||
|
"22222222222222222222222222222\""}
|
||||||
|
.size());
|
||||||
|
|
||||||
|
auto parsed = Void::Update::parseFeedPayload(sharedLibrary);
|
||||||
|
Void::Testing::require(parsed.has_value());
|
||||||
|
Void::Testing::require(parsed->releases.size() == 1);
|
||||||
|
Void::Testing::expect_eq(parsed->releases.front().packageType,
|
||||||
|
std::string{"shared-library"});
|
||||||
|
Void::Testing::expect(
|
||||||
|
parsed->releases.front().releaseManifestSha256.empty());
|
||||||
|
|
||||||
|
const Void::Update::SelectionRequest request{
|
||||||
|
.component = "service",
|
||||||
|
.artifactId = "main",
|
||||||
|
.channel = "stable",
|
||||||
|
.environment = {.versionContracts = {{"host.api",
|
||||||
|
*Void::Semver::parse("1.5.0")}},
|
||||||
|
.exactContracts = {{"plugin.abi", "2"}},
|
||||||
|
.platform = "linux",
|
||||||
|
.architecture = "x86_64"},
|
||||||
|
.currentVersion = std::nullopt,
|
||||||
|
.requiredCohort = std::nullopt,
|
||||||
|
.allowDowngrade = false,
|
||||||
|
.includeCurrent = false};
|
||||||
|
const auto selected = Void::Update::selectRelease(*parsed, request);
|
||||||
|
Void::Testing::require(selected.has_value());
|
||||||
|
Void::Testing::expect_eq(selected->packageType,
|
||||||
|
std::string{"shared-library"});
|
||||||
|
|
||||||
|
const auto packageType = sharedLibrary.find("shared-library");
|
||||||
|
Void::Testing::require(packageType != std::string::npos);
|
||||||
|
sharedLibrary.replace(packageType,
|
||||||
|
std::string_view{"shared-library"}.size(), "file");
|
||||||
|
const auto fileFeed = Void::Update::parseFeedPayload(sharedLibrary);
|
||||||
|
Void::Testing::require(fileFeed.has_value());
|
||||||
|
Void::Testing::expect_eq(fileFeed->releases.front().packageType,
|
||||||
|
std::string{"file"});
|
||||||
|
|
||||||
|
const auto filePackageType = sharedLibrary.find("file");
|
||||||
|
Void::Testing::require(filePackageType != std::string::npos);
|
||||||
|
sharedLibrary.replace(filePackageType, std::string_view{"file"}.size(),
|
||||||
|
"wasm-module");
|
||||||
|
const auto wasmFeed = Void::Update::parseFeedPayload(sharedLibrary);
|
||||||
|
Void::Testing::require(wasmFeed.has_value());
|
||||||
|
Void::Testing::expect_eq(wasmFeed->releases.front().packageType,
|
||||||
|
std::string{"wasm-module"});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test version_store_commits_and_reconciles_activation()
|
||||||
|
{
|
||||||
|
Void::FileSystem::TempDir temporary{"void_versions_"};
|
||||||
|
Void::Update::VersionStore store{temporary.path() / "store"};
|
||||||
|
Void::Testing::require(store.initialize().has_value());
|
||||||
|
const auto version1 = *Void::Semver::parse("1.0.0");
|
||||||
|
const auto version2 = *Void::Semver::parse("2.0.0");
|
||||||
|
auto staging1 = store.prepare(version1);
|
||||||
|
Void::Testing::require(staging1.has_value());
|
||||||
|
std::ofstream{*staging1 / "marker"} << "one";
|
||||||
|
Void::Testing::require(store.publish(version1, *staging1).has_value());
|
||||||
|
Void::Testing::require(store.activate(version1).has_value());
|
||||||
|
Void::Testing::require(store.commit().has_value());
|
||||||
|
|
||||||
|
auto staging2 = store.prepare(version2);
|
||||||
|
Void::Testing::require(staging2.has_value());
|
||||||
|
std::ofstream{*staging2 / "marker"} << "two";
|
||||||
|
Void::Testing::require(store.publish(version2, *staging2).has_value());
|
||||||
|
Void::Testing::require(store.activate(version2).has_value());
|
||||||
|
Void::Testing::expect(!store.recordHealthy(version2).has_value());
|
||||||
|
auto current = store.currentVersion();
|
||||||
|
Void::Testing::require(current.has_value() && current->has_value());
|
||||||
|
Void::Testing::expect_eq((*current)->to_string(), std::string{"2.0.0"});
|
||||||
|
Void::Testing::require(store.reconcile().has_value());
|
||||||
|
current = store.currentVersion();
|
||||||
|
Void::Testing::require(current.has_value() && current->has_value());
|
||||||
|
Void::Testing::expect_eq((*current)->to_string(), std::string{"1.0.0"});
|
||||||
|
Void::Testing::expect(!store.pendingActivation()->has_value());
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test version_store_commit_point_is_unambiguous_and_idempotent()
|
||||||
|
{
|
||||||
|
Void::FileSystem::TempDir temporary{"void_versions_commit_point_"};
|
||||||
|
Void::Update::VersionStore store{temporary.path() / "store"};
|
||||||
|
Void::Testing::require(store.initialize().has_value());
|
||||||
|
const auto version = *Void::Semver::parse("2.1.0");
|
||||||
|
auto staging = store.prepare(version);
|
||||||
|
Void::Testing::require(staging.has_value());
|
||||||
|
std::ofstream{*staging / "marker"} << "candidate";
|
||||||
|
Void::Testing::require(store.publish(version, *staging).has_value());
|
||||||
|
Void::Testing::require(store.activate(version).has_value());
|
||||||
|
|
||||||
|
Void::Testing::require(store.commit().has_value());
|
||||||
|
|
||||||
|
Void::Testing::expect(
|
||||||
|
!std::filesystem::exists(store.root() / "activation.json"));
|
||||||
|
Void::Testing::require(store.commit().has_value());
|
||||||
|
std::ifstream healthInput{store.root() / "health.log"};
|
||||||
|
const std::string healthHistory{std::istreambuf_iterator<char>{healthInput},
|
||||||
|
std::istreambuf_iterator<char>{}};
|
||||||
|
const auto healthyRecord = healthHistory.find("H 2.1.0\n");
|
||||||
|
Void::Testing::require(healthyRecord != std::string::npos);
|
||||||
|
Void::Testing::expect(healthHistory.find("H 2.1.0\n", healthyRecord + 1) ==
|
||||||
|
std::string::npos);
|
||||||
|
Void::Testing::require(store.rollback().has_value());
|
||||||
|
const auto current = store.currentVersion();
|
||||||
|
Void::Testing::require(current.has_value() && current->has_value());
|
||||||
|
Void::Testing::expect_eq((*current)->to_string(), std::string{"2.1.0"});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test version_store_reconciles_durable_commit_marker()
|
||||||
|
{
|
||||||
|
#ifndef _WIN32
|
||||||
|
Void::FileSystem::TempDir temporary{"void_versions_commit_marker_"};
|
||||||
|
Void::Update::VersionStore store{temporary.path() / "store"};
|
||||||
|
Void::Testing::require(store.initialize().has_value());
|
||||||
|
const auto version = *Void::Semver::parse("2.2.0");
|
||||||
|
auto staging = store.prepare(version);
|
||||||
|
Void::Testing::require(staging.has_value());
|
||||||
|
std::ofstream{*staging / "marker"} << "candidate";
|
||||||
|
Void::Testing::require(store.publish(version, *staging).has_value());
|
||||||
|
Void::Testing::require(store.activate(version).has_value());
|
||||||
|
|
||||||
|
std::ifstream healthInput{store.root() / "health.log"};
|
||||||
|
std::string healthHistory{std::istreambuf_iterator<char>{healthInput},
|
||||||
|
std::istreambuf_iterator<char>{}};
|
||||||
|
healthHistory += "H 2.2.0\n";
|
||||||
|
const auto replacement = store.root() / "health.replacement";
|
||||||
|
std::ofstream{replacement, std::ios::binary | std::ios::trunc}
|
||||||
|
<< healthHistory;
|
||||||
|
std::filesystem::rename(replacement, store.root() / "health.log");
|
||||||
|
Void::Testing::expect(
|
||||||
|
std::filesystem::exists(store.root() / "activation.json"));
|
||||||
|
|
||||||
|
const auto healthyRecord = healthHistory.find("H 2.2.0\n");
|
||||||
|
Void::Testing::require(healthyRecord != std::string::npos);
|
||||||
|
Void::Testing::expect(healthHistory.find("H 2.2.0\n", healthyRecord + 1) ==
|
||||||
|
std::string::npos);
|
||||||
|
Void::Testing::require(store.rollback().has_value());
|
||||||
|
const auto committedCurrent = store.currentVersion();
|
||||||
|
Void::Testing::require(committedCurrent.has_value() &&
|
||||||
|
committedCurrent->has_value());
|
||||||
|
Void::Testing::expect_eq((*committedCurrent)->to_string(),
|
||||||
|
std::string{"2.2.0"});
|
||||||
|
Void::Testing::require(store.reconcile().has_value());
|
||||||
|
Void::Testing::expect(
|
||||||
|
!std::filesystem::exists(store.root() / "activation.json"));
|
||||||
|
const auto reconciledCurrent = store.currentVersion();
|
||||||
|
Void::Testing::require(reconciledCurrent.has_value() &&
|
||||||
|
reconciledCurrent->has_value());
|
||||||
|
Void::Testing::expect_eq((*reconciledCurrent)->to_string(),
|
||||||
|
std::string{"2.2.0"});
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test version_store_reactivation_refreshes_health_order()
|
||||||
|
{
|
||||||
|
Void::FileSystem::TempDir temporary{"void_versions_reactivation_"};
|
||||||
|
Void::Update::VersionStore store{temporary.path() / "store"};
|
||||||
|
Void::Testing::require(store.initialize().has_value());
|
||||||
|
for (const std::string_view text : {"1.0.0", "2.0.0", "3.0.0"}) {
|
||||||
|
const auto version = *Void::Semver::parse(text);
|
||||||
|
auto staging = store.prepare(version);
|
||||||
|
Void::Testing::require(staging.has_value());
|
||||||
|
std::ofstream{*staging / "marker"} << text;
|
||||||
|
Void::Testing::require(store.publish(version, *staging).has_value());
|
||||||
|
Void::Testing::require(store.activate(version).has_value());
|
||||||
|
Void::Testing::require(store.commit().has_value());
|
||||||
|
}
|
||||||
|
const auto reactivated = *Void::Semver::parse("1.0.0");
|
||||||
|
Void::Testing::require(store.activate(reactivated).has_value());
|
||||||
|
Void::Testing::require(store.commit().has_value());
|
||||||
|
|
||||||
|
const auto removed = store.prune(1);
|
||||||
|
Void::Testing::require(removed.has_value());
|
||||||
|
Void::Testing::expect_eq(removed->size(), std::size_t{1});
|
||||||
|
Void::Testing::expect_eq(removed->front().to_string(),
|
||||||
|
std::string{"2.0.0"});
|
||||||
|
Void::Testing::expect(
|
||||||
|
std::filesystem::is_directory(store.versionPath(reactivated)));
|
||||||
|
Void::Testing::expect(std::filesystem::is_directory(
|
||||||
|
store.versionPath(*Void::Semver::parse("3.0.0"))));
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test version_store_records_external_lifecycle_without_staging()
|
||||||
|
{
|
||||||
|
Void::FileSystem::TempDir temporary{"void_versions_external_lifecycle_"};
|
||||||
|
Void::Update::VersionStore store{temporary.path() / "store"};
|
||||||
|
std::filesystem::create_directories(store.root() / "versions");
|
||||||
|
for (const std::string_view text :
|
||||||
|
{"1.0.0", "2.0.0", "3.0.0", "4.0.0", "5.0.0"}) {
|
||||||
|
std::filesystem::create_directories(
|
||||||
|
store.versionPath(*Void::Semver::parse(text)));
|
||||||
|
}
|
||||||
|
const auto version1 = *Void::Semver::parse("1.0.0");
|
||||||
|
const auto version2 = *Void::Semver::parse("2.0.0");
|
||||||
|
const auto version3 = *Void::Semver::parse("3.0.0");
|
||||||
|
const auto version4 = *Void::Semver::parse("4.0.0");
|
||||||
|
const auto version5 = *Void::Semver::parse("5.0.0");
|
||||||
|
Void::Testing::require(store.recordHealthy(version1).has_value());
|
||||||
|
Void::Testing::require(store.recordHealthy(version2).has_value());
|
||||||
|
Void::Testing::require(store.recordHealthy(version3).has_value());
|
||||||
|
Void::Testing::require(store.recordHealthy(version1).has_value());
|
||||||
|
Void::Testing::require(store.recordFailed(version2).has_value());
|
||||||
|
Void::Testing::require(store.recordFailed(version4).has_value());
|
||||||
|
Void::Testing::expect(!std::filesystem::exists(store.root() / "staging"));
|
||||||
|
|
||||||
|
std::ifstream healthInput{store.root() / "health.log"};
|
||||||
|
const std::string healthHistory{std::istreambuf_iterator<char>{healthInput},
|
||||||
|
std::istreambuf_iterator<char>{}};
|
||||||
|
Void::Testing::expect(healthHistory.find("F 2.0.0\n") == std::string::npos);
|
||||||
|
Void::Testing::expect(healthHistory.find("F 4.0.0\n") != std::string::npos);
|
||||||
|
|
||||||
|
#ifndef _WIN32
|
||||||
|
const auto external = temporary.path() / "external";
|
||||||
|
std::filesystem::create_directories(external);
|
||||||
|
const auto linkedVersion = *Void::Semver::parse("6.0.0");
|
||||||
|
std::filesystem::create_directory_symlink(external,
|
||||||
|
store.versionPath(linkedVersion));
|
||||||
|
Void::Testing::expect(!store.recordHealthy(linkedVersion).has_value());
|
||||||
|
std::filesystem::create_directory_symlink(
|
||||||
|
std::filesystem::path{"versions"} / version1.to_string(),
|
||||||
|
store.root() / "current");
|
||||||
|
|
||||||
|
const auto removed = store.prune(1);
|
||||||
|
Void::Testing::require(removed.has_value());
|
||||||
|
Void::Testing::expect_eq(removed->size(), std::size_t{2});
|
||||||
|
Void::Testing::expect(
|
||||||
|
!std::filesystem::exists(store.versionPath(version2)));
|
||||||
|
Void::Testing::expect(
|
||||||
|
!std::filesystem::exists(store.versionPath(version4)));
|
||||||
|
Void::Testing::expect(
|
||||||
|
std::filesystem::is_directory(store.versionPath(version1)));
|
||||||
|
Void::Testing::expect(
|
||||||
|
std::filesystem::is_directory(store.versionPath(version3)));
|
||||||
|
Void::Testing::expect(
|
||||||
|
std::filesystem::is_directory(store.versionPath(version5)));
|
||||||
|
Void::Testing::expect(std::filesystem::is_directory(external));
|
||||||
|
Void::Testing::expect(
|
||||||
|
std::filesystem::is_symlink(store.versionPath(linkedVersion)));
|
||||||
|
Void::Testing::expect(!std::filesystem::exists(store.root() / "staging"));
|
||||||
|
#else
|
||||||
|
(void)version5;
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test version_store_prunes_without_an_active_version()
|
||||||
|
{
|
||||||
|
Void::FileSystem::TempDir temporary{"void_versions_no_current_"};
|
||||||
|
Void::Update::VersionStore store{temporary.path() / "store"};
|
||||||
|
std::filesystem::create_directories(store.root() / "versions");
|
||||||
|
for (const std::string_view text : {"1.0.0", "2.0.0", "3.0.0", "4.0.0"}) {
|
||||||
|
std::filesystem::create_directories(
|
||||||
|
store.versionPath(*Void::Semver::parse(text)));
|
||||||
|
}
|
||||||
|
const auto version1 = *Void::Semver::parse("1.0.0");
|
||||||
|
const auto version2 = *Void::Semver::parse("2.0.0");
|
||||||
|
const auto version3 = *Void::Semver::parse("3.0.0");
|
||||||
|
const auto version4 = *Void::Semver::parse("4.0.0");
|
||||||
|
Void::Testing::require(store.recordHealthy(version1).has_value());
|
||||||
|
Void::Testing::require(store.recordHealthy(version2).has_value());
|
||||||
|
Void::Testing::require(store.recordFailed(version3).has_value());
|
||||||
|
|
||||||
|
auto removed = store.prune(1);
|
||||||
|
Void::Testing::require(removed.has_value());
|
||||||
|
Void::Testing::expect_eq(removed->size(), std::size_t{2});
|
||||||
|
Void::Testing::expect(
|
||||||
|
!std::filesystem::exists(store.versionPath(version1)));
|
||||||
|
Void::Testing::expect(
|
||||||
|
std::filesystem::is_directory(store.versionPath(version2)));
|
||||||
|
Void::Testing::expect(
|
||||||
|
!std::filesystem::exists(store.versionPath(version3)));
|
||||||
|
Void::Testing::expect(
|
||||||
|
std::filesystem::is_directory(store.versionPath(version4)));
|
||||||
|
|
||||||
|
// A retired SemVer may be republished by an external lifecycle owner. Its
|
||||||
|
// earlier healthy event belongs to the retired publication, so a failure in
|
||||||
|
// the new publication must still be recorded and prunable.
|
||||||
|
std::filesystem::create_directories(store.versionPath(version1));
|
||||||
|
Void::Testing::require(store.recordFailed(version1).has_value());
|
||||||
|
std::ifstream healthInput{store.root() / "health.log"};
|
||||||
|
const std::string healthHistory{std::istreambuf_iterator<char>{healthInput},
|
||||||
|
std::istreambuf_iterator<char>{}};
|
||||||
|
const auto retired = healthHistory.find("D 1.0.0\n");
|
||||||
|
Void::Testing::require(retired != std::string::npos);
|
||||||
|
Void::Testing::expect(healthHistory.find("F 1.0.0\n", retired) !=
|
||||||
|
std::string::npos);
|
||||||
|
removed = store.prune(1);
|
||||||
|
Void::Testing::require(removed.has_value());
|
||||||
|
Void::Testing::expect_eq(removed->size(), std::size_t{1});
|
||||||
|
Void::Testing::expect(
|
||||||
|
!std::filesystem::exists(store.versionPath(version1)));
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test version_store_reports_healthy_publications_in_event_order()
|
||||||
|
{
|
||||||
|
Void::FileSystem::TempDir temporary{"void_versions_healthy_query_"};
|
||||||
|
Void::Update::VersionStore store{temporary.path() / "store"};
|
||||||
|
std::filesystem::create_directories(store.root() / "versions");
|
||||||
|
const auto version1 = *Void::Semver::parse("1.0.0");
|
||||||
|
const auto version2 = *Void::Semver::parse("2.0.0");
|
||||||
|
const auto version3 = *Void::Semver::parse("3.0.0");
|
||||||
|
const auto version4 = *Void::Semver::parse("4.0.0");
|
||||||
|
const auto version5 = *Void::Semver::parse("5.0.0");
|
||||||
|
for (const auto& version :
|
||||||
|
{version1, version2, version3, version4, version5}) {
|
||||||
|
std::filesystem::create_directories(store.versionPath(version));
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::require(store.recordHealthy(version1).has_value());
|
||||||
|
Void::Testing::require(store.recordHealthy(version2).has_value());
|
||||||
|
Void::Testing::require(store.recordHealthy(version3).has_value());
|
||||||
|
Void::Testing::require(store.recordHealthy(version1).has_value());
|
||||||
|
Void::Testing::require(store.recordFailed(version4).has_value());
|
||||||
|
#ifndef _WIN32
|
||||||
|
const auto readable = std::filesystem::perms::owner_read |
|
||||||
|
std::filesystem::perms::group_read |
|
||||||
|
std::filesystem::perms::others_read;
|
||||||
|
Void::Testing::expect(
|
||||||
|
(std::filesystem::status(store.root() / ".update.lock").permissions() &
|
||||||
|
readable) == readable);
|
||||||
|
Void::Testing::expect(
|
||||||
|
(std::filesystem::status(store.root() / "health.log").permissions() &
|
||||||
|
readable) == readable);
|
||||||
|
#endif
|
||||||
|
auto healthy = store.healthyPublishedVersions();
|
||||||
|
Void::Testing::require(healthy.has_value());
|
||||||
|
Void::Testing::expect_eq(healthy->size(), std::size_t{3});
|
||||||
|
Void::Testing::expect_eq((*healthy)[0].to_string(), std::string{"1.0.0"});
|
||||||
|
Void::Testing::expect_eq((*healthy)[1].to_string(), std::string{"3.0.0"});
|
||||||
|
Void::Testing::expect_eq((*healthy)[2].to_string(), std::string{"2.0.0"});
|
||||||
|
|
||||||
|
// Pruning retires an older healthy lifecycle and excludes failed and
|
||||||
|
// retired publications. Unknown publications remain on disk but are not
|
||||||
|
// reported as rollback candidates.
|
||||||
|
Void::Testing::require(store.prune(2).has_value());
|
||||||
|
healthy = store.healthyPublishedVersions();
|
||||||
|
Void::Testing::require(healthy.has_value());
|
||||||
|
Void::Testing::expect_eq(healthy->size(), std::size_t{2});
|
||||||
|
Void::Testing::expect_eq((*healthy)[0].to_string(), std::string{"1.0.0"});
|
||||||
|
Void::Testing::expect_eq((*healthy)[1].to_string(), std::string{"3.0.0"});
|
||||||
|
Void::Testing::expect(
|
||||||
|
std::filesystem::is_directory(store.versionPath(version5)));
|
||||||
|
|
||||||
|
std::filesystem::create_directories(store.versionPath(version2));
|
||||||
|
Void::Testing::require(store.recordFailed(version2).has_value());
|
||||||
|
healthy = store.healthyPublishedVersions();
|
||||||
|
Void::Testing::require(healthy.has_value());
|
||||||
|
Void::Testing::expect_eq(healthy->size(), std::size_t{2});
|
||||||
|
Void::Testing::require(store.recordHealthy(version2).has_value());
|
||||||
|
healthy = store.healthyPublishedVersions();
|
||||||
|
Void::Testing::require(healthy.has_value());
|
||||||
|
Void::Testing::expect_eq(healthy->size(), std::size_t{3});
|
||||||
|
Void::Testing::expect_eq((*healthy)[0].to_string(), std::string{"2.0.0"});
|
||||||
|
|
||||||
|
std::filesystem::remove_all(store.versionPath(version1));
|
||||||
|
healthy = store.healthyPublishedVersions();
|
||||||
|
Void::Testing::require(healthy.has_value());
|
||||||
|
Void::Testing::expect_eq(healthy->size(), std::size_t{2});
|
||||||
|
Void::Testing::expect_eq((*healthy)[0].to_string(), std::string{"2.0.0"});
|
||||||
|
Void::Testing::expect_eq((*healthy)[1].to_string(), std::string{"3.0.0"});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test version_store_prune_never_synthesizes_health()
|
||||||
|
{
|
||||||
|
#ifndef _WIN32
|
||||||
|
Void::FileSystem::TempDir temporary{"void_versions_prune_health_"};
|
||||||
|
Void::Update::VersionStore store{temporary.path() / "store"};
|
||||||
|
std::filesystem::create_directories(store.root() / "versions");
|
||||||
|
const auto failed = *Void::Semver::parse("1.0.0");
|
||||||
|
const auto healthy = *Void::Semver::parse("2.0.0");
|
||||||
|
std::filesystem::create_directories(store.versionPath(failed));
|
||||||
|
std::filesystem::create_directories(store.versionPath(healthy));
|
||||||
|
Void::Testing::require(store.recordFailed(failed).has_value());
|
||||||
|
Void::Testing::require(store.recordHealthy(healthy).has_value());
|
||||||
|
std::filesystem::create_directory_symlink(
|
||||||
|
std::filesystem::path{"versions"} / failed.to_string(),
|
||||||
|
store.root() / "current");
|
||||||
|
|
||||||
|
Void::Testing::require(store.prune(1).has_value());
|
||||||
|
std::ifstream healthInput{store.root() / "health.log"};
|
||||||
|
const std::string healthHistory{std::istreambuf_iterator<char>{healthInput},
|
||||||
|
std::istreambuf_iterator<char>{}};
|
||||||
|
Void::Testing::expect(healthHistory.find("H 1.0.0\n") == std::string::npos);
|
||||||
|
|
||||||
|
std::filesystem::remove(store.root() / "current");
|
||||||
|
std::filesystem::create_directory_symlink(
|
||||||
|
std::filesystem::path{"versions"} / healthy.to_string(),
|
||||||
|
store.root() / "current");
|
||||||
|
const auto removed = store.prune(0);
|
||||||
|
Void::Testing::require(removed.has_value());
|
||||||
|
Void::Testing::expect_eq(removed->size(), std::size_t{1});
|
||||||
|
Void::Testing::expect(!std::filesystem::exists(store.versionPath(failed)));
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test version_store_compacts_health_history_atomically()
|
||||||
|
{
|
||||||
|
Void::FileSystem::TempDir temporary{"void_versions_health_compaction_"};
|
||||||
|
Void::Update::VersionStore store{temporary.path() / "store"};
|
||||||
|
std::filesystem::create_directories(store.root() / "versions");
|
||||||
|
const auto version1 = *Void::Semver::parse("1.0.0");
|
||||||
|
const auto version2 = *Void::Semver::parse("2.0.0");
|
||||||
|
std::filesystem::create_directories(store.versionPath(version1));
|
||||||
|
std::filesystem::create_directories(store.versionPath(version2));
|
||||||
|
{
|
||||||
|
std::ofstream history{store.root() / "health.log",
|
||||||
|
std::ios::binary | std::ios::trunc};
|
||||||
|
for (std::size_t index = 0; index < 100'000; ++index) {
|
||||||
|
history << "H 1.0.0\n";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Void::Testing::require(store.recordHealthy(version2).has_value());
|
||||||
|
Void::Testing::expect(
|
||||||
|
std::filesystem::file_size(store.root() / "health.log") < 1024);
|
||||||
|
|
||||||
|
const auto removed = store.prune(1);
|
||||||
|
Void::Testing::require(removed.has_value());
|
||||||
|
Void::Testing::expect_eq(removed->size(), std::size_t{1});
|
||||||
|
Void::Testing::expect_eq(removed->front().to_string(),
|
||||||
|
std::string{"1.0.0"});
|
||||||
|
Void::Testing::expect(
|
||||||
|
std::filesystem::is_directory(store.versionPath(version2)));
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test version_store_rejects_unsafe_activation_journal()
|
||||||
|
{
|
||||||
|
#ifndef _WIN32
|
||||||
|
Void::FileSystem::TempDir temporary{"void_versions_journal_safety_"};
|
||||||
|
Void::Update::VersionStore store{temporary.path() / "store"};
|
||||||
|
Void::Testing::require(store.initialize().has_value());
|
||||||
|
const auto external = temporary.path() / "external-activation.json";
|
||||||
|
std::ofstream{external}
|
||||||
|
<< R"({"schemaVersion":1,"previousVersion":null,"candidateVersion":"1.0.0"})";
|
||||||
|
std::filesystem::create_symlink(external, store.root() / "activation.json");
|
||||||
|
Void::Testing::expect(!store.pendingActivation().has_value());
|
||||||
|
Void::Testing::expect(std::filesystem::is_regular_file(external));
|
||||||
|
|
||||||
|
std::filesystem::remove(store.root() / "activation.json");
|
||||||
|
{
|
||||||
|
std::ofstream oversized{store.root() / "activation.json",
|
||||||
|
std::ios::binary | std::ios::trunc};
|
||||||
|
oversized.seekp(128 * 1024);
|
||||||
|
oversized.put('\0');
|
||||||
|
}
|
||||||
|
Void::Testing::expect(!store.pendingActivation().has_value());
|
||||||
|
|
||||||
|
std::filesystem::remove(store.root() / "activation.json");
|
||||||
|
std::ofstream{store.root() / "activation.json"}
|
||||||
|
<< R"({"schemaVersion":1,"previousVersion":null,"candidateVersion":"1.0.0"})";
|
||||||
|
Void::Testing::expect(!store.pendingActivation().has_value());
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test version_store_prunes_only_unprotected_real_versions()
|
||||||
|
{
|
||||||
|
Void::FileSystem::TempDir temporary{"void_versions_prune_"};
|
||||||
|
Void::Update::VersionStore store{temporary.path() / "store"};
|
||||||
|
Void::Testing::require(store.initialize().has_value());
|
||||||
|
|
||||||
|
const std::array versionTexts{"1.0.0", "2.0.0", "3.0.0", "4.0.0"};
|
||||||
|
for (const std::string_view text : versionTexts) {
|
||||||
|
const auto version = *Void::Semver::parse(text);
|
||||||
|
auto staging = store.prepare(version);
|
||||||
|
Void::Testing::require(staging.has_value());
|
||||||
|
std::ofstream{*staging / "marker"} << text;
|
||||||
|
Void::Testing::require(store.publish(version, *staging).has_value());
|
||||||
|
Void::Testing::require(store.activate(version).has_value());
|
||||||
|
Void::Testing::require(store.commit().has_value());
|
||||||
|
}
|
||||||
|
const auto active = *Void::Semver::parse("4.0.0");
|
||||||
|
|
||||||
|
const auto staged = store.prepare(*Void::Semver::parse("8.0.0"));
|
||||||
|
Void::Testing::require(staged.has_value());
|
||||||
|
std::ofstream{*staged / "keep"} << "staging";
|
||||||
|
const auto uncommitted = *Void::Semver::parse("7.0.0");
|
||||||
|
auto uncommittedStaging = store.prepare(uncommitted);
|
||||||
|
Void::Testing::require(uncommittedStaging.has_value());
|
||||||
|
std::ofstream{*uncommittedStaging / "marker"} << "uncommitted";
|
||||||
|
Void::Testing::require(
|
||||||
|
store.publish(uncommitted, *uncommittedStaging).has_value());
|
||||||
|
|
||||||
|
#ifndef _WIN32
|
||||||
|
const auto external = temporary.path() / "external";
|
||||||
|
std::filesystem::create_directories(external);
|
||||||
|
std::ofstream{external / "keep"} << "outside";
|
||||||
|
std::filesystem::create_directory_symlink(
|
||||||
|
external, store.versionPath(*Void::Semver::parse("1.0.0")) / "linked");
|
||||||
|
std::filesystem::create_directory_symlink(
|
||||||
|
external, store.versionPath(*Void::Semver::parse("9.0.0")));
|
||||||
|
const auto orphanedQuarantine = store.root() / "versions" / ".prune.orphan";
|
||||||
|
std::filesystem::create_directories(orphanedQuarantine);
|
||||||
|
std::filesystem::create_directory_symlink(external,
|
||||||
|
orphanedQuarantine / "linked");
|
||||||
|
#endif
|
||||||
|
|
||||||
|
auto removed = store.prune(2);
|
||||||
|
Void::Testing::require(removed.has_value());
|
||||||
|
Void::Testing::expect_eq(removed->size(), std::size_t{1});
|
||||||
|
Void::Testing::expect_eq(removed->front().to_string(),
|
||||||
|
std::string{"1.0.0"});
|
||||||
|
Void::Testing::expect(!std::filesystem::exists(
|
||||||
|
store.versionPath(*Void::Semver::parse("1.0.0"))));
|
||||||
|
for (const std::string_view text : {"2.0.0", "3.0.0", "4.0.0"}) {
|
||||||
|
Void::Testing::expect(std::filesystem::is_directory(
|
||||||
|
store.versionPath(*Void::Semver::parse(text))));
|
||||||
|
}
|
||||||
|
Void::Testing::expect(std::filesystem::exists(*staged / "keep"));
|
||||||
|
Void::Testing::expect(
|
||||||
|
std::filesystem::is_directory(store.versionPath(uncommitted)));
|
||||||
|
#ifndef _WIN32
|
||||||
|
Void::Testing::expect(std::filesystem::exists(external / "keep"));
|
||||||
|
Void::Testing::expect(!std::filesystem::exists(orphanedQuarantine));
|
||||||
|
Void::Testing::expect(std::filesystem::is_symlink(
|
||||||
|
store.versionPath(*Void::Semver::parse("9.0.0"))));
|
||||||
|
#endif
|
||||||
|
|
||||||
|
const auto candidate = *Void::Semver::parse("5.0.0");
|
||||||
|
auto candidateStaging = store.prepare(candidate);
|
||||||
|
Void::Testing::require(candidateStaging.has_value());
|
||||||
|
std::ofstream{*candidateStaging / "marker"} << "candidate";
|
||||||
|
Void::Testing::require(
|
||||||
|
store.publish(candidate, *candidateStaging).has_value());
|
||||||
|
Void::Testing::require(store.activate(candidate).has_value());
|
||||||
|
removed = store.prune(0);
|
||||||
|
Void::Testing::require(removed.has_value());
|
||||||
|
Void::Testing::expect_eq(removed->size(), std::size_t{2});
|
||||||
|
Void::Testing::expect(
|
||||||
|
std::filesystem::is_directory(store.versionPath(candidate)));
|
||||||
|
Void::Testing::expect(
|
||||||
|
std::filesystem::is_directory(store.versionPath(active)));
|
||||||
|
Void::Testing::expect(std::filesystem::exists(*staged / "keep"));
|
||||||
|
Void::Testing::expect(
|
||||||
|
std::filesystem::is_directory(store.versionPath(uncommitted)));
|
||||||
|
Void::Testing::require(store.rollback().has_value());
|
||||||
|
const auto current = store.currentVersion();
|
||||||
|
Void::Testing::require(current.has_value() && current->has_value());
|
||||||
|
Void::Testing::expect_eq((*current)->to_string(), std::string{"4.0.0"});
|
||||||
|
removed = store.prune(0);
|
||||||
|
Void::Testing::require(removed.has_value());
|
||||||
|
Void::Testing::expect_eq(removed->size(), std::size_t{1});
|
||||||
|
Void::Testing::expect_eq(removed->front().to_string(),
|
||||||
|
std::string{"5.0.0"});
|
||||||
|
Void::Testing::expect(
|
||||||
|
!std::filesystem::exists(store.versionPath(candidate)));
|
||||||
|
Void::Testing::expect(
|
||||||
|
std::filesystem::is_directory(store.versionPath(uncommitted)));
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test version_store_rejects_symlink_layout()
|
||||||
|
{
|
||||||
|
#ifndef _WIN32
|
||||||
|
Void::FileSystem::TempDir temporary{"void_versions_links_"};
|
||||||
|
const auto target = temporary.path() / "target";
|
||||||
|
std::filesystem::create_directories(target);
|
||||||
|
|
||||||
|
const auto linkedRoot = temporary.path() / "linked-store";
|
||||||
|
std::filesystem::create_directory_symlink(target, linkedRoot);
|
||||||
|
Void::Update::VersionStore rootStore{linkedRoot};
|
||||||
|
Void::Testing::expect(!rootStore.initialize().has_value());
|
||||||
|
|
||||||
|
const auto versionsRoot = temporary.path() / "versions-store";
|
||||||
|
std::filesystem::create_directories(versionsRoot / "staging");
|
||||||
|
std::filesystem::create_directory_symlink(target,
|
||||||
|
versionsRoot / "versions");
|
||||||
|
Void::Update::VersionStore versionsStore{versionsRoot};
|
||||||
|
Void::Testing::expect(!versionsStore.initialize().has_value());
|
||||||
|
|
||||||
|
const auto stagingRoot = temporary.path() / "staging-store";
|
||||||
|
std::filesystem::create_directories(stagingRoot / "versions");
|
||||||
|
std::filesystem::create_directory_symlink(target, stagingRoot / "staging");
|
||||||
|
Void::Update::VersionStore stagingStore{stagingRoot};
|
||||||
|
Void::Testing::expect(!stagingStore.initialize().has_value());
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test version_store_publish_requires_immediate_real_child()
|
||||||
|
{
|
||||||
|
Void::FileSystem::TempDir temporary{"void_versions_publish_"};
|
||||||
|
Void::Update::VersionStore store{temporary.path() / "store"};
|
||||||
|
Void::Testing::require(store.initialize().has_value());
|
||||||
|
|
||||||
|
const auto nested = store.root() / "staging" / "nested" / "candidate";
|
||||||
|
std::filesystem::create_directories(nested);
|
||||||
|
const auto version1 = *Void::Semver::parse("3.0.0");
|
||||||
|
Void::Testing::expect(!store.publish(version1, nested).has_value());
|
||||||
|
|
||||||
|
#ifndef _WIN32
|
||||||
|
const auto external = temporary.path() / "external-candidate";
|
||||||
|
std::filesystem::create_directories(external);
|
||||||
|
const auto linked = store.root() / "staging" / "linked-candidate";
|
||||||
|
std::filesystem::create_directory_symlink(external, linked);
|
||||||
|
const auto version2 = *Void::Semver::parse("3.1.0");
|
||||||
|
Void::Testing::expect(!store.publish(version2, linked).has_value());
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test version_store_activate_rejects_symlink_version()
|
||||||
|
{
|
||||||
|
#ifndef _WIN32
|
||||||
|
Void::FileSystem::TempDir temporary{"void_versions_activate_"};
|
||||||
|
Void::Update::VersionStore store{temporary.path() / "store"};
|
||||||
|
Void::Testing::require(store.initialize().has_value());
|
||||||
|
const auto external = temporary.path() / "external-version";
|
||||||
|
std::filesystem::create_directories(external);
|
||||||
|
const auto version = *Void::Semver::parse("4.0.0");
|
||||||
|
std::filesystem::create_directory_symlink(external,
|
||||||
|
store.versionPath(version));
|
||||||
|
Void::Testing::expect(!store.activate(version).has_value());
|
||||||
|
Void::Testing::expect(
|
||||||
|
!std::filesystem::exists(store.root() / "activation.json"));
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test version_store_rollback_revalidates_previous_version()
|
||||||
|
{
|
||||||
|
#ifndef _WIN32
|
||||||
|
Void::FileSystem::TempDir temporary{"void_versions_rollback_links_"};
|
||||||
|
Void::Update::VersionStore store{temporary.path() / "store"};
|
||||||
|
Void::Testing::require(store.initialize().has_value());
|
||||||
|
const auto version1 = *Void::Semver::parse("1.0.0");
|
||||||
|
const auto version2 = *Void::Semver::parse("2.0.0");
|
||||||
|
for (const auto& version : {version1, version2}) {
|
||||||
|
auto staging = store.prepare(version);
|
||||||
|
Void::Testing::require(staging.has_value());
|
||||||
|
std::ofstream{*staging / "marker"} << version.to_string();
|
||||||
|
Void::Testing::require(store.publish(version, *staging).has_value());
|
||||||
|
}
|
||||||
|
Void::Testing::require(store.activate(version1).has_value());
|
||||||
|
Void::Testing::require(store.commit().has_value());
|
||||||
|
Void::Testing::require(store.activate(version2).has_value());
|
||||||
|
|
||||||
|
const auto external = temporary.path() / "external-previous";
|
||||||
|
std::filesystem::create_directories(external);
|
||||||
|
std::filesystem::remove_all(store.versionPath(version1));
|
||||||
|
std::filesystem::create_directory_symlink(external,
|
||||||
|
store.versionPath(version1));
|
||||||
|
Void::Testing::expect(!store.rollback().has_value());
|
||||||
|
Void::Testing::expect(
|
||||||
|
std::filesystem::exists(store.root() / "activation.json"));
|
||||||
|
const auto current = store.currentVersion();
|
||||||
|
Void::Testing::require(current.has_value() && current->has_value());
|
||||||
|
Void::Testing::expect_eq((*current)->to_string(), std::string{"2.0.0"});
|
||||||
|
Void::Testing::expect(std::filesystem::is_directory(external));
|
||||||
|
#endif
|
||||||
|
}
|
||||||
Reference in new issue
Block a user