From 3851aeb7036f87d136073eccc5e0b726405b64bb Mon Sep 17 00:00:00 2001 From: faumaray Date: Mon, 20 Jul 2026 01:18:53 +0300 Subject: [PATCH] Update Signed-off-by: faumaray --- CMakeLists.txt | 17 +- cmake/Dependencies.cmake | 7 + cmake/Module.cmake | 23 +- cmake/VoidConfig.cmake.in | 71 +- include/Void/Archive/Archive.hpp | 32 + include/Void/Binary/Reader.hpp | 156 ++ include/Void/Crypto/Crypto.hpp | 78 + include/Void/Plugin/Loader.hpp | 145 +- include/Void/Plugin/Manager.hpp | 19 +- include/Void/System/SignalWatcher.hpp | 44 + include/Void/Text/Base64.hpp | 307 ++-- include/Void/Text/Hex.hpp | 140 +- include/Void/Text/Semver.hpp | 672 ++++++-- include/Void/Update/Feed.hpp | 111 ++ include/Void/Update/Update.hpp | 4 + include/Void/Update/VersionStore.hpp | 102 ++ src/Archive/Archive.cpp | 652 ++++++++ src/Archive/module.cmake | 4 + src/Binary/module.cmake | 3 + src/Crypto/Crypto.cpp | 257 +++ src/Crypto/module.cmake | 4 + src/Plugin/Loader.cpp | 471 +++--- src/Plugin/Manager.cpp | 109 +- src/System/SignalWatcher.cpp | 146 ++ src/System/module.cmake | 1 + src/Update/Feed.cpp | 488 ++++++ src/Update/VersionStore.cpp | 1826 +++++++++++++++++++++ src/Update/module.cmake | 3 + tests/CMakeLists.txt | 13 + tests/package/Audited/CMakeLists.txt | 24 + tests/package/Audited/main.cpp | 28 + tests/package/Binary/CMakeLists.txt | 10 + tests/package/Binary/main.cpp | 14 + tests/package/InstalledComponents.cmake | 56 + tests/standalone/Archive/Archive.cpp | 253 +++ tests/standalone/Binary/Reader.cpp | 31 + tests/standalone/Crypto/Crypto.cpp | 77 + tests/standalone/Plugin/Manager.cpp | 34 + tests/standalone/System/SignalWatcher.cpp | 22 + tests/standalone/Text/Encoding.cpp | 240 +-- tests/standalone/Text/Semver.cpp | 183 ++- tests/standalone/Update/Update.cpp | 830 ++++++++++ 42 files changed, 6948 insertions(+), 759 deletions(-) create mode 100644 include/Void/Archive/Archive.hpp create mode 100644 include/Void/Binary/Reader.hpp create mode 100644 include/Void/Crypto/Crypto.hpp create mode 100644 include/Void/System/SignalWatcher.hpp create mode 100644 include/Void/Update/Feed.hpp create mode 100644 include/Void/Update/Update.hpp create mode 100644 include/Void/Update/VersionStore.hpp create mode 100644 src/Archive/Archive.cpp create mode 100644 src/Archive/module.cmake create mode 100644 src/Binary/module.cmake create mode 100644 src/Crypto/Crypto.cpp create mode 100644 src/Crypto/module.cmake create mode 100644 src/System/SignalWatcher.cpp create mode 100644 src/Update/Feed.cpp create mode 100644 src/Update/VersionStore.cpp create mode 100644 src/Update/module.cmake create mode 100644 tests/package/Audited/CMakeLists.txt create mode 100644 tests/package/Audited/main.cpp create mode 100644 tests/package/Binary/CMakeLists.txt create mode 100644 tests/package/Binary/main.cpp create mode 100644 tests/package/InstalledComponents.cmake create mode 100644 tests/standalone/Archive/Archive.cpp create mode 100644 tests/standalone/Binary/Reader.cpp create mode 100644 tests/standalone/Crypto/Crypto.cpp create mode 100644 tests/standalone/System/SignalWatcher.cpp create mode 100644 tests/standalone/Update/Update.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 1fbceca..b46e8d7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,12 @@ cmake_minimum_required(VERSION 4.0.0) 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_WARNINGS_AS_ERRORS "Treat compiler warnings as errors" OFF) option(VOID_ENABLE_ASAN "Enable AddressSanitizer (Clang/GCC)" OFF) @@ -41,13 +48,11 @@ if(VOID_ENABLE_TESTING) endif() 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) - list(REMOVE_DUPLICATES ALL_EXTERNAL_DEPS) -endif() - -set(VOID_EXTERNAL_DEPS_LIST "${ALL_EXTERNAL_DEPS}") +set(VOID_MODULES_LIST "${ALL_DISCOVERED_MODULES}") +set(VOID_MODULE_DEPENDENCY_RECORDS "${ALL_MODULE_DEPENDENCY_RECORDS}") write_basic_package_version_file( "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake" diff --git a/cmake/Dependencies.cmake b/cmake/Dependencies.cmake index 0d5ddc3..102c6b1 100644 --- a/cmake/Dependencies.cmake +++ b/cmake/Dependencies.cmake @@ -64,6 +64,13 @@ function(void_fetch_dependency DEP_NAME) INTERFACE_LINK_LIBRARIES PkgConfig::SODIUM) return() endif() + + if(DEP_NAME STREQUAL "LibArchive") + if(NOT TARGET LibArchive::LibArchive) + find_package(LibArchive REQUIRED) + endif() + return() + endif() # FIXME: Add if needed external # if(DEP_NAME STREQUAL "glaze") # if(NOT glaze_POPULATED) diff --git a/cmake/Module.cmake b/cmake/Module.cmake index 0a8081a..3c7ffef 100644 --- a/cmake/Module.cmake +++ b/cmake/Module.cmake @@ -1,5 +1,5 @@ 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 "") function(void_add_module MODULE_NAME) @@ -38,13 +38,32 @@ function(void_add_module MODULE_NAME) add_library(${ALIAS} ALIAS ${TGT}) set_property(GLOBAL APPEND PROPERTY VOID_MODULES ${MODULE_NAME}) + set(_module_external_deps "") foreach(ext_dep IN LISTS ARG_EXTERNAL_DEPS) 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) void_fetch_dependency(${BASE_DEP}) 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) target_link_libraries(${TGT} ${SCOPE} ${PROJECT_NAME}::${int_dep}) endforeach() diff --git a/cmake/VoidConfig.cmake.in b/cmake/VoidConfig.cmake.in index 9d03cfd..40550f9 100644 --- a/cmake/VoidConfig.cmake.in +++ b/cmake/VoidConfig.cmake.in @@ -2,7 +2,66 @@ 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) if(dep STREQUAL "Boost") 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 INTERFACE_LINK_LIBRARIES PkgConfig::SODIUM) endif() + elseif(dep STREQUAL "LibArchive") + find_dependency(LibArchive REQUIRED) elseif(NOT TARGET ${dep}) find_dependency(${dep}) endif() @@ -21,6 +82,14 @@ endforeach() 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-scan sweep just by find_package(Void). if(EXISTS "${CMAKE_CURRENT_LIST_DIR}/VoidTesting.cmake") diff --git a/include/Void/Archive/Archive.hpp b/include/Void/Archive/Archive.hpp new file mode 100644 index 0000000..f708045 --- /dev/null +++ b/include/Void/Archive/Archive.hpp @@ -0,0 +1,32 @@ +#pragma once + +#include +#include + +#include +#include +#include + +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 + extract(const std::filesystem::path& archivePath, + const std::filesystem::path& destination, + const ExtractionOptions& options = {}); +} // namespace Void::Archive diff --git a/include/Void/Binary/Reader.hpp b/include/Void/Binary/Reader.hpp new file mode 100644 index 0000000..0d749b0 --- /dev/null +++ b/include/Void/Binary/Reader.hpp @@ -0,0 +1,156 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Binary +{ + /// Bounds-checked, non-owning reader for binary formats. + class Reader + { + public: + + explicit constexpr Reader(std::span 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 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 skip(std::size_t count) + { + if (count > remaining()) { + return truncated("skip", count); + } + m_position += count; + return {}; + } + + [[nodiscard]] Void::Result::Result> + 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> + peekBytes(std::size_t count) const + { + if (count > remaining()) { + return std::unexpected{truncatedError("peekBytes", count)}; + } + return m_bytes.subspan(m_position, count); + } + + template + requires(!std::same_as) + [[nodiscard]] Void::Result::Result + read(std::endian byteOrder = std::endian::native) + { + auto bytes = readBytes(sizeof(T)); + if (!bytes) { + return std::unexpected{bytes.error()}; + } + std::array storage{}; + std::ranges::copy(*bytes, storage.begin()); + T value = std::bit_cast(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 + readString(std::size_t count) + { + auto bytes = readBytes(count); + if (!bytes) { + return std::unexpected{bytes.error()}; + } + return std::string{reinterpret_cast(bytes->data()), + bytes->size()}; + } + + [[nodiscard]] Void::Result::Result + subreader(std::size_t count) + { + auto bytes = readBytes(count); + if (!bytes) { + return std::unexpected{bytes.error()}; + } + return Reader{*bytes}; + } + + private: + + std::span 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 + truncated(std::string_view operation, + std::size_t requested) const + { + return std::unexpected{truncatedError(operation, requested)}; + } + }; +} // namespace Void::Binary diff --git a/include/Void/Crypto/Crypto.hpp b/include/Void/Crypto/Crypto.hpp new file mode 100644 index 0000000..9fa0658 --- /dev/null +++ b/include/Void/Crypto/Crypto.hpp @@ -0,0 +1,78 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace Void::Crypto +{ + enum class HashAlgorithm { Sha1, Sha256, Sha512 }; + using Digest = std::vector; + + class Hasher + { + public: + + [[nodiscard]] static Void::Result::Result + create(HashAlgorithm algorithm); + ~Hasher(); + Hasher(Hasher&&) noexcept; + Hasher& operator=(Hasher&&) noexcept; + Hasher(const Hasher&) = delete; + Hasher& operator=(const Hasher&) = delete; + + [[nodiscard]] Void::Result::Result + update(std::span data); + [[nodiscard]] Void::Result::Result + update(std::string_view data); + /// Finalize this hash. Calling finalize or update again is an + /// error. + [[nodiscard]] Void::Result::Result finalize(); + + private: + + struct Impl; + std::unique_ptr m_impl; + explicit Hasher(std::unique_ptr impl) noexcept; + }; + + [[nodiscard]] Void::Result::Result + hash(HashAlgorithm algorithm, std::span data); + [[nodiscard]] Void::Result::Result hash(HashAlgorithm algorithm, + std::string_view data); + [[nodiscard]] Void::Result::Result + hashFile(HashAlgorithm algorithm, const std::filesystem::path& path); + + [[nodiscard]] Void::Result::Result + sha1(std::span data); + [[nodiscard]] Void::Result::Result sha1(std::string_view data); + [[nodiscard]] Void::Result::Result + sha256(std::span data); + [[nodiscard]] Void::Result::Result sha256(std::string_view data); + [[nodiscard]] Void::Result::Result + sha512(std::span data); + [[nodiscard]] Void::Result::Result sha512(std::string_view data); + [[nodiscard]] Void::Result::Result + sha1File(const std::filesystem::path& path); + [[nodiscard]] Void::Result::Result + sha256File(const std::filesystem::path& path); + [[nodiscard]] Void::Result::Result + 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 + verifyEd25519(std::span message, + std::span signature, + std::span publicKey); +} // namespace Void::Crypto diff --git a/include/Void/Plugin/Loader.hpp b/include/Void/Plugin/Loader.hpp index 77e4806..ca161de 100644 --- a/include/Void/Plugin/Loader.hpp +++ b/include/Void/Plugin/Loader.hpp @@ -9,82 +9,97 @@ namespace Void::Plugin { -enum class LoadError { - FileNotFound, - DlopenFailed, - SymbolMissing, - AbiMismatch, - CreateFailed, - NotSupported, // platform does not support dlopen - StateRejected, // new instance refused the serialized state - ActivationFailed, // on_load threw or readiness validation failed - UnknownPlugin, // PluginManager: no plugin registered under that name -}; + enum class LoadError { + FileNotFound, + DlopenFailed, + SymbolMissing, + AbiMismatch, + CreateFailed, + NotSupported, // platform does not support dlopen + StateRejected, // new instance refused the serialized state + ActivationFailed, // on_load threw or readiness validation failed + 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 ────────────────────────────────────────────────────────────── -// 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 -// dlopen gets a fresh inode even if the path was already cached. -// 2. New instance is created and optional transfer_state() called (both -// 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. + // ── PluginLoader + // ────────────────────────────────────────────────────────────── 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 + // dlopen gets a fresh inode even if the path was already cached. + // 2. New instance is created and optional transfer_state() called (both + // 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. -class PluginLoader { -public: - [[nodiscard]] static std::expected - load(std::filesystem::path path); + class PluginLoader + { + public: - ~PluginLoader(); - PluginLoader(PluginLoader&&) noexcept; - PluginLoader& operator=(PluginLoader&&) noexcept; - PluginLoader(const PluginLoader&) = delete; - PluginLoader& operator=(const PluginLoader&) = delete; + [[nodiscard]] static std::expected + load(std::filesystem::path path); - [[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; } + ~PluginLoader(); + PluginLoader(PluginLoader&&) noexcept; + PluginLoader& operator=(PluginLoader&&) noexcept; + 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 - // 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 reload(); + IPlugin* operator->() noexcept { return plugin_; } -private: - PluginLoader() = default; + // Hot-reload: copies current .so to a temp file (fresh inode), + // 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 reload(); - // Moves plugin state old -> new during a reload (v2 serialize/ - // deserialize, else transfer_state). Returns false only if the new - // instance rejects the state. - friend bool transfer_plugin_state(const PluginLoader& from, - PluginLoader& to); + private: - 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_; + PluginLoader() = default; - [[nodiscard]] std::expected - load_from(const std::filesystem::path& path); + // Moves plugin state old -> new during a reload (v2 serialize/ + // 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 + load_from(const std::filesystem::path& path); + + void destroy_current() noexcept; + }; } // namespace Void::Plugin diff --git a/include/Void/Plugin/Manager.hpp b/include/Void/Plugin/Manager.hpp index cb9ac42..51486bb 100644 --- a/include/Void/Plugin/Manager.hpp +++ b/include/Void/Plugin/Manager.hpp @@ -87,7 +87,8 @@ namespace Void::Plugin std::function config_provider; // 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 instance_validator; }; @@ -140,6 +141,16 @@ namespace Void::Plugin /// it alive until they drop. std::expected 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 + replace(std::string_view name, + const std::filesystem::path& newPath); + /// Begin watching the plugin's file; reload automatically when /// it changes (debounced). Reload failures are logged and the /// old instance is kept. @@ -191,11 +202,13 @@ namespace Void::Plugin struct Entry { std::filesystem::path path; std::atomic> current; + bool watched{false}; }; Entry* find(std::string_view name) const; - std::expected reload_locked(Entry& entry, - std::string_view name); + std::expected + reload_locked(Entry& entry, std::string_view name, + const std::filesystem::path& sourcePath); std::vector> reload_callbacks_locked() const; diff --git a/include/Void/System/SignalWatcher.hpp b/include/Void/System/SignalWatcher.hpp new file mode 100644 index 0000000..7bd3cd0 --- /dev/null +++ b/include/Void/System/SignalWatcher.hpp @@ -0,0 +1,44 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include + +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 + create(std::vector 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> + wait(std::chrono::milliseconds timeout = + std::chrono::milliseconds::max()); + + [[nodiscard]] Void::Result::Result> poll(); + + private: + + struct Impl; + std::unique_ptr m_impl; + explicit SignalWatcher(std::unique_ptr impl) noexcept; + }; +} // namespace Void::Process diff --git a/include/Void/Text/Base64.hpp b/include/Void/Text/Base64.hpp index 15c37b7..78de09b 100644 --- a/include/Void/Text/Base64.hpp +++ b/include/Void/Text/Base64.hpp @@ -6,121 +6,216 @@ #include #include #include +#include namespace Void::Encoding::Base64 { -namespace Detail -{ -constexpr std::string_view alphabet = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + namespace Detail + { + constexpr std::string_view alphabet = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -constexpr std::string_view alphabet_url = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + constexpr std::string_view alphabet_url = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; -[[nodiscard]] constexpr std::array - make_decode_table(std::string_view alpha) noexcept -{ - std::array t{}; - t.fill(-1); - for (std::size_t i = 0; i < 64; ++i) { - t[static_cast(alpha[i])] = static_cast(i); - } - t[static_cast('=')] = -2; // padding sentinel - return t; -} -} // namespace Detail + [[nodiscard]] constexpr std::array + make_decode_table(std::string_view alpha) noexcept + { + std::array t{}; + t.fill(-1); + for (std::size_t i = 0; i < 64; ++i) { + t[static_cast(alpha[i])] = + static_cast(i); + } + t[static_cast('=')] = -2; // padding sentinel + return t; + } + } // namespace Detail -/// Encode bytes to standard Base64 (with padding). -[[nodiscard]] inline std::string encode(std::span data) -{ - const auto& alpha = Detail::alphabet; - 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(data[i]); - const auto b = static_cast(data[i + 1]); - const auto c = static_cast(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(data[i]); - const auto b = static_cast(data[i + 1]); - out += alpha[a >> 2]; - out += alpha[((a & 3) << 4) | (b >> 4)]; - out += alpha[(b & 15) << 2]; - out += '='; - } else if (data.size() - i == 1) { - const auto a = static_cast(data[i]); - out += alpha[a >> 2]; - out += alpha[(a & 3) << 4]; - out += '='; - out += '='; - } - return out; -} + /// Encode bytes to standard Base64 (with padding). + [[nodiscard]] inline std::string encode(std::span data) + { + const auto& alpha = Detail::alphabet; + 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(data[i]); + const auto b = static_cast(data[i + 1]); + const auto c = static_cast(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(data[i]); + const auto b = static_cast(data[i + 1]); + out += alpha[a >> 2]; + out += alpha[((a & 3) << 4) | (b >> 4)]; + out += alpha[(b & 15) << 2]; + out += '='; + } else if (data.size() - i == 1) { + const auto a = static_cast(data[i]); + out += alpha[a >> 2]; + out += alpha[(a & 3) << 4]; + out += '='; + out += '='; + } + return out; + } -/// Encode a string_view to standard Base64. -[[nodiscard]] inline std::string encode(std::string_view s) -{ - return encode(std::as_bytes(std::span{s.data(), s.size()})); -} + /// Encode an unsigned-byte view without forcing callers to reinterpret + /// their binary buffers as text. + [[nodiscard]] inline std::string encode(std::span data) + { + return encode(std::as_bytes(data)); + } -/// Encode to URL-safe Base64 (no padding). -[[nodiscard]] inline std::string encode_url(std::string_view s) -{ - const auto& alpha = Detail::alphabet_url; - 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(data[i]); - const auto b = static_cast(data[i + 1]); - const auto c = static_cast(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(data[i]); - const auto b = static_cast(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(data[i]); - out += alpha[a >> 2]; - out += alpha[(a & 3) << 4]; - } - return out; -} + /// Encode a string_view to standard Base64. + [[nodiscard]] inline std::string encode(std::string_view s) + { + return encode(std::as_bytes(std::span{s.data(), s.size()})); + } -/// Decode standard Base64 (with or without padding). Returns nullopt on error. -[[nodiscard]] inline std::optional decode(std::string_view s) -{ - static constexpr auto table = Detail::make_decode_table(Detail::alphabet); - std::string out; - out.reserve((s.size() / 4) * 3); - int buf = 0, bits = 0; - for (unsigned char c : s) { - if (c == ' ' || c == '\n' || c == '\r' || c == '\t') continue; - const std::int8_t v = table[c]; - if (v == -2) break; // padding - if (v == -1) return std::nullopt; - buf = (buf << 6) | v; - bits += 6; - if (bits >= 8) { - bits -= 8; - out += static_cast((buf >> bits) & 0xFF); - } - } - return out; -} + /// Encode to URL-safe Base64 (no padding). + [[nodiscard]] inline std::string encode_url(std::string_view s) + { + const auto& alpha = Detail::alphabet_url; + 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(data[i]); + const auto b = static_cast(data[i + 1]); + const auto c = static_cast(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(data[i]); + const auto b = static_cast(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(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 + 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(encoded); + const std::int8_t value = table[character]; + if (value < 0) { + return std::nullopt; + } + buffer = (buffer << 6) | static_cast(value); + bits += 6; + if (bits >= 8) { + bits -= 8; + out += static_cast((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 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(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(value); + ++symbols; + bits += 6; + if (bits >= 8) { + bits -= 8; + out += static_cast((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> + 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{bytes.begin(), bytes.end()}; + } } // namespace Void::Encoding::Base64 diff --git a/include/Void/Text/Hex.hpp b/include/Void/Text/Hex.hpp index e9e190e..ee8205b 100644 --- a/include/Void/Text/Hex.hpp +++ b/include/Void/Text/Hex.hpp @@ -5,67 +5,99 @@ #include #include #include +#include namespace Void::Encoding::Hex { -/// Encode bytes to lowercase hex string. -[[nodiscard]] inline std::string encode(std::span data) -{ - constexpr std::string_view digits = "0123456789abcdef"; - std::string out; - out.reserve(data.size() * 2); - for (auto b : data) { - const auto v = static_cast(b); - out += digits[v >> 4]; - out += digits[v & 0xF]; - } - return out; -} + /// Encode bytes to lowercase hex string. + [[nodiscard]] inline std::string encode(std::span data) + { + constexpr std::string_view digits = "0123456789abcdef"; + std::string out; + out.reserve(data.size() * 2); + for (auto b : data) { + const auto v = static_cast(b); + out += digits[v >> 4]; + out += digits[v & 0xF]; + } + return out; + } -[[nodiscard]] inline std::string encode(std::string_view s) -{ - return encode(std::as_bytes(std::span{s.data(), s.size()})); -} + /// Encode an unsigned-byte view without treating binary data as text. + [[nodiscard]] inline std::string encode(std::span data) + { + return encode(std::as_bytes(data)); + } -/// Decode hex string to bytes. Returns nullopt on invalid input. -[[nodiscard]] inline std::optional decode(std::string_view s) -{ - if (s.size() % 2 != 0) return std::nullopt; - auto hex_val = [](char c) -> std::optional { - if (c >= '0' && c <= '9') return static_cast(c - '0'); - if (c >= 'a' && c <= 'f') return static_cast(c - 'a' + 10); - if (c >= 'A' && c <= 'F') return static_cast(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((*hi << 4) | *lo); - } - return out; -} + [[nodiscard]] inline std::string encode(std::string_view s) + { + return encode(std::as_bytes(std::span{s.data(), s.size()})); + } -/// Uppercase hex encoding. -[[nodiscard]] inline std::string encode_upper(std::span data) -{ - constexpr std::string_view digits = "0123456789ABCDEF"; - std::string out; - out.reserve(data.size() * 2); - for (auto b : data) { - const auto v = static_cast(b); - out += digits[v >> 4]; - out += digits[v & 0xF]; - } - return out; -} + /// Decode hex string to bytes. Returns nullopt on invalid input. + [[nodiscard]] inline std::optional decode(std::string_view s) + { + if (s.size() % 2 != 0) { + return std::nullopt; + } + auto hex_val = [](char c) -> std::optional { + if (c >= '0' && c <= '9') { + return static_cast(c - '0'); + } + if (c >= 'a' && c <= 'f') { + return static_cast(c - 'a' + 10); + } + if (c >= 'A' && c <= 'F') { + return static_cast(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((*hi << 4) | *lo); + } + return out; + } -[[nodiscard]] inline std::string encode_upper(std::string_view s) -{ - return encode_upper(std::as_bytes(std::span{s.data(), s.size()})); -} + /// Decode hexadecimal text into an explicitly binary buffer. + [[nodiscard]] inline std::optional> + 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{bytes.begin(), bytes.end()}; + } + + /// Uppercase hex encoding. + [[nodiscard]] inline std::string + encode_upper(std::span data) + { + constexpr std::string_view digits = "0123456789ABCDEF"; + std::string out; + out.reserve(data.size() * 2); + for (auto b : data) { + const auto v = static_cast(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 diff --git a/include/Void/Text/Semver.hpp b/include/Void/Text/Semver.hpp index af74290..fd4862d 100644 --- a/include/Void/Text/Semver.hpp +++ b/include/Void/Text/Semver.hpp @@ -1,132 +1,602 @@ #pragma once +#include #include -#include #include +#include #include #include #include +#include namespace Void::Semver { -// ── Version ─────────────────────────────────────────────────────────────────── + namespace Detail + { + [[nodiscard]] constexpr bool is_digit(char value) noexcept + { + return value >= '0' && value <= '9'; + } -struct Version -{ - unsigned major{0}; - unsigned minor{0}; - unsigned patch{0}; - std::string pre_release; // e.g. "alpha.1" - std::string build; // e.g. "20240101" + [[nodiscard]] constexpr bool + is_identifier_character(char value) noexcept + { + return is_digit(value) || (value >= 'A' && value <= 'Z') || + (value >= 'a' && value <= 'z') || value == '-'; + } - [[nodiscard]] std::string to_string() const - { - std::string s = std::format("{}.{}.{}", major, minor, patch); - if (!pre_release.empty()) { s += '-'; s += pre_release; } - if (!build.empty()) { s += '+'; s += build; } - return s; - } + [[nodiscard]] inline bool + is_numeric(std::string_view identifier) noexcept + { + if (identifier.empty()) { + return false; + } + for (const char value : identifier) { + if (!is_digit(value)) { + return false; + } + } + return true; + } - // Precedence comparison per semver spec (build metadata ignored). - [[nodiscard]] std::strong_ordering - operator<=>(const Version& o) const noexcept - { - if (auto c = major <=> o.major; c != 0) return c; - if (auto c = minor <=> o.minor; c != 0) return c; - if (auto c = patch <=> o.patch; c != 0) return c; - // No pre-release > has pre-release - const bool l_pre = !pre_release.empty(); - const bool r_pre = !o.pre_release.empty(); - if (!l_pre && r_pre) return std::strong_ordering::greater; - if (l_pre && !r_pre) return std::strong_ordering::less; - // Both have pre-release — lexicographic (simplified) - if (auto c = pre_release <=> o.pre_release; c != 0) { - return c < 0 ? std::strong_ordering::less - : std::strong_ordering::greater; - } - return std::strong_ordering::equal; - } + [[nodiscard]] inline std::strong_ordering + compare_identifier(std::string_view left, + std::string_view right) noexcept + { + const bool left_numeric = is_numeric(left); + const bool right_numeric = is_numeric(right); + if (left_numeric && right_numeric) { + if (left.size() != right.size()) { + return left.size() < right.size() + ? std::strong_ordering::less + : std::strong_ordering::greater; + } + return left <=> right; + } + if (left_numeric != right_numeric) { + return left_numeric ? std::strong_ordering::less + : std::strong_ordering::greater; + } + return left <=> right; + } - [[nodiscard]] bool operator==(const Version& o) const noexcept - { - return major == o.major && minor == o.minor && patch == o.patch && - pre_release == o.pre_release; - } + [[nodiscard]] inline std::strong_ordering + compare_prerelease(std::string_view left, + std::string_view right) noexcept + { + 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]] bool compatible_with(const Version& required) const noexcept - { - if (major != required.major) return false; - return (*this <=> required) >= 0; - } + [[nodiscard]] inline bool + valid_identifiers(std::string_view value, + bool reject_numeric_leading_zero) noexcept + { + 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 - { - return major >= 1 && pre_release.empty(); - } + [[nodiscard]] inline bool parse_component(std::string_view value, + unsigned& output) noexcept + { + 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::max()) { + return false; + } + output = static_cast(parsed); + return true; + } - [[nodiscard]] Version bumped_major() const noexcept - { - return {major + 1, 0, 0}; - } + [[nodiscard]] constexpr std::string_view + trim(std::string_view value) noexcept + { + 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 - { - return {major, minor + 1, 0}; - } + struct Version { + unsigned major{0}; + unsigned minor{0}; + unsigned patch{0}; + std::string pre_release; + std::string build; - [[nodiscard]] Version bumped_patch() const noexcept - { - return {major, minor, patch + 1}; - } -}; + [[nodiscard]] std::string to_string() const + { + 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 parse(std::string_view s) -{ - Version v; + [[nodiscard]] bool operator==(const Version& other) const noexcept + { + 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 { - if (sv.empty()) return false; - out = 0; - for (char c : sv) { - if (c < '0' || c > '9') return false; - out = out * 10 + static_cast(c - '0'); - } - return true; - }; + [[nodiscard]] bool + compatible_with(const Version& required) const noexcept + { + return major == required.major && (*this <=> required) >= 0; + } - // Optional leading 'v' - if (!s.empty() && (s[0] == 'v' || s[0] == 'V')) s.remove_prefix(1); + [[nodiscard]] bool is_stable() const noexcept + { + return major >= 1 && pre_release.empty(); + } - // Split build metadata first - const auto plus = s.find('+'); - if (plus != std::string_view::npos) { - v.build = std::string{s.substr(plus + 1)}; - s = s.substr(0, plus); - } + [[nodiscard]] Version bumped_major() const noexcept + { + return Version{.major = major + 1, + .minor = 0, + .patch = 0, + .pre_release = {}, + .build = {}}; + } - // Split pre-release - const auto dash = s.find('-'); - if (dash != std::string_view::npos) { - v.pre_release = std::string{s.substr(dash + 1)}; - s = s.substr(0, dash); - } + [[nodiscard]] Version bumped_minor() const noexcept + { + return Version{.major = major, + .minor = minor + 1, + .patch = 0, + .pre_release = {}, + .build = {}}; + } - // Major.minor.patch - const auto d1 = s.find('.'); - if (d1 == std::string_view::npos) return std::nullopt; - if (!parse_uint(s.substr(0, d1), v.major)) return std::nullopt; - s = s.substr(d1 + 1); + [[nodiscard]] Version bumped_patch() const noexcept + { + return Version{.major = major, + .minor = minor, + .patch = patch + 1, + .pre_release = {}, + .build = {}}; + } + }; - const auto d2 = s.find('.'); - if (d2 == std::string_view::npos) return std::nullopt; - if (!parse_uint(s.substr(0, d2), v.minor)) return std::nullopt; - if (!parse_uint(s.substr(d2 + 1), v.patch)) return std::nullopt; + namespace Detail + { + [[nodiscard]] inline std::optional + 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 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 + parse_strict(std::string_view value) + { + return Detail::parse_version(value, false); + } + + class VersionRange + { + public: + + [[nodiscard]] static std::optional + 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; + std::vector 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::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::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::max()) { + return false; + } + upper = Version{.major = 0, + .minor = lower->minor + 1, + .patch = 0, + .pre_release = {}, + .build = {}}; + } else { + if (lower->patch == + std::numeric_limits::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::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::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 + parse_range(std::string_view expression) + { + return VersionRange::parse(expression); + } } // namespace Void::Semver diff --git a/include/Void/Update/Feed.hpp b/include/Void/Update/Feed.hpp new file mode 100644 index 0000000..64ac0c9 --- /dev/null +++ b/include/Void/Update/Feed.hpp @@ -0,0 +1,111 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Update +{ + struct Compatibility { + std::unordered_map + versionContracts; + std::unordered_map 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 releases; + }; + + struct FeedEnvelope { + std::uint32_t schemaVersion{1}; + std::string keyId; + std::string payload; + Crypto::Digest signature; + }; + + using Ed25519PublicKey = + std::array; + using Keyring = std::unordered_map; + + struct VerificationPolicy { + std::size_t maxEnvelopeBytes{5 * 1024 * 1024}; + std::size_t maxPayloadBytes{4 * 1024 * 1024}; + std::size_t maxReleases{10'000}; + std::optional 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 versionContracts; + std::unordered_map exactContracts; + std::string platform; + std::string architecture; + }; + + struct SelectionRequest { + std::string component; + std::string artifactId; + std::string channel; + Environment environment; + std::optional currentVersion; + std::optional 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 + parseFeedPayload(std::string_view payload, + const VerificationPolicy& policy = {}); + + /// Verify the envelope signature before parsing the signed payload. + [[nodiscard]] Void::Result::Result + verifyFeedEnvelope(std::string_view envelopeJson, const Keyring& keys, + const VerificationPolicy& policy = {}); + + /// Select the greatest compatible version, independent of feed order. + [[nodiscard]] std::optional + selectRelease(const Feed& feed, const SelectionRequest& request); +} // namespace Void::Update diff --git a/include/Void/Update/Update.hpp b/include/Void/Update/Update.hpp new file mode 100644 index 0000000..a495265 --- /dev/null +++ b/include/Void/Update/Update.hpp @@ -0,0 +1,4 @@ +#pragma once + +#include +#include diff --git a/include/Void/Update/VersionStore.hpp b/include/Void/Update/VersionStore.hpp new file mode 100644 index 0000000..cef46f2 --- /dev/null +++ b/include/Void/Update/VersionStore.hpp @@ -0,0 +1,102 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace Void::Update +{ + struct PendingActivation { + std::optional 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 initialize(); + [[nodiscard]] Void::Result::Result + prepare(const Semver::Version& version); + [[nodiscard]] Void::Result::Result + publish(const Semver::Version& version, + const std::filesystem::path& stagingDirectory); + [[nodiscard]] Void::Result::Result + 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 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 rollback(); + [[nodiscard]] Void::Result::Result 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 + 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 + 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> + 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> + prune(std::size_t retainedPreviousVersions); + + [[nodiscard]] Void::Result::Result> + currentVersion() const; + [[nodiscard]] Void::Result::Result> + 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 diff --git a/src/Archive/Archive.cpp b/src/Archive/Archive.cpp new file mode 100644 index 0000000..db8ac61 --- /dev/null +++ b/src/Archive/Archive.cpp @@ -0,0 +1,652 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#ifndef _WIN32 +#include +#include +#include +#else +#include +#endif + +namespace Void::Archive +{ + namespace + { + using ArchiveHandle = + std::unique_ptr; + + [[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 + 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 temporaryCounter{0}; + + [[nodiscard]] Void::Result::Result + 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 + 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 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 + 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(::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 { + removeTemporary(); + return Void::Result::fail(std::move(message)); + }; + + std::array 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(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(count)) { + const auto result = ::write( + descriptor.get(), + reinterpret_cast(buffer.data()) + written, + static_cast(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(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 + 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 + 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 + 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 { + output.close(); + std::error_code removeError; + std::filesystem::remove(path, removeError); + return Void::Result::fail(std::move(message)); + }; + + std::array 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(count); + if (amount > options.maxFileBytes - fileBytes || + amount > + options.maxTotalBytes - alreadyExtracted - fileBytes) { + return fail( + "Archive::extract: extracted size exceeds policy"); + } + output.write(reinterpret_cast(buffer.data()), + count); + if (!output) { + return fail("Archive::extract: write failed"); + } + fileBytes += amount; + } + return fileBytes; + } +#endif + } // namespace + + Void::Result::Result + 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 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(declared) > options.maxFileBytes || + static_cast(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 diff --git a/src/Archive/module.cmake b/src/Archive/module.cmake new file mode 100644 index 0000000..b2b2c52 --- /dev/null +++ b/src/Archive/module.cmake @@ -0,0 +1,4 @@ +void_add_module(Archive + INTERNAL_DEPS Functional + EXTERNAL_DEPS LibArchive::LibArchive +) diff --git a/src/Binary/module.cmake b/src/Binary/module.cmake new file mode 100644 index 0000000..a7d9cca --- /dev/null +++ b/src/Binary/module.cmake @@ -0,0 +1,3 @@ +void_add_module(Binary + INTERNAL_DEPS Functional +) diff --git a/src/Crypto/Crypto.cpp b/src/Crypto/Crypto.cpp new file mode 100644 index 0000000..cbbb3b6 --- /dev/null +++ b/src/Crypto/Crypto.cpp @@ -0,0 +1,257 @@ +#include + +#include +#include +#include +#include + +#include +#include + +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 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) noexcept + : m_impl(std::move(impl)) + { + } + Hasher::~Hasher() = default; + Hasher::Hasher(Hasher&&) noexcept = default; + Hasher& Hasher::operator=(Hasher&&) noexcept = default; + + Void::Result::Result Hasher::create(HashAlgorithm algorithm) + { + auto impl = std::make_unique(); + 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 Hasher::update(std::span 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 Hasher::update(std::string_view data) + { + return update(std::as_bytes(std::span{data.data(), data.size()})); + } + + Void::Result::Result 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(digest_size)); + unsigned int written = 0; + if (EVP_DigestFinal_ex(m_impl->context, + reinterpret_cast(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 data) + -> Void::Result::Result + { + 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 + { + return hash(algorithm, + std::as_bytes(std::span{data.data(), data.size()})); + } + + auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path) + -> Void::Result::Result + { + 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 buffer{}; + while (input) { + input.read(buffer.data(), + static_cast(buffer.size())); + const auto count = input.gcount(); + if (count > 0) { + const auto bytes = std::as_bytes( + std::span{buffer.data(), static_cast(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 sha1(std::span data) + { + return hash(HashAlgorithm::Sha1, data); + } + Void::Result::Result sha1(std::string_view data) + { + return hash(HashAlgorithm::Sha1, data); + } + Void::Result::Result sha256(std::span data) + { + return hash(HashAlgorithm::Sha256, data); + } + Void::Result::Result sha256(std::string_view data) + { + return hash(HashAlgorithm::Sha256, data); + } + Void::Result::Result sha512(std::span data) + { + return hash(HashAlgorithm::Sha512, data); + } + Void::Result::Result sha512(std::string_view data) + { + return hash(HashAlgorithm::Sha512, data); + } + Void::Result::Result sha1File(const std::filesystem::path& path) + { + return hashFile(HashAlgorithm::Sha1, path); + } + Void::Result::Result sha256File(const std::filesystem::path& path) + { + return hashFile(HashAlgorithm::Sha256, path); + } + Void::Result::Result sha512File(const std::filesystem::path& path) + { + return hashFile(HashAlgorithm::Sha512, path); + } + + Void::Result::Result verifyEd25519(std::span message, + std::span + signature, + std::span + 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; + using Context = std::unique_ptr; + Key key{EVP_PKEY_new_raw_public_key( + EVP_PKEY_ED25519, nullptr, + reinterpret_cast(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(signature.data()), + signature.size(), + reinterpret_cast(message.data()), + message.size()); + if (result < 0) { + return Void::Result::fail( + openssl_error("Crypto::verifyEd25519 failed")); + } + return result == 1; + } +} // namespace Void::Crypto diff --git a/src/Crypto/module.cmake b/src/Crypto/module.cmake new file mode 100644 index 0000000..200a64f --- /dev/null +++ b/src/Crypto/module.cmake @@ -0,0 +1,4 @@ +void_add_module(Crypto + INTERNAL_DEPS Functional + EXTERNAL_DEPS OpenSSL::Crypto +) diff --git a/src/Plugin/Loader.cpp b/src/Plugin/Loader.cpp index e2765bc..18f8f4a 100644 --- a/src/Plugin/Loader.cpp +++ b/src/Plugin/Loader.cpp @@ -1,9 +1,9 @@ -#include #include +#include #if defined(__unix__) || defined(__APPLE__) -# include -# define VOID_HAS_DLOPEN 1 +#include +#define VOID_HAS_DLOPEN 1 #endif #include @@ -13,258 +13,281 @@ namespace Void::Plugin { -std::string_view to_string(LoadError e) noexcept -{ - switch (e) { - case LoadError::FileNotFound: return "file not found"; - case LoadError::DlopenFailed: return "dlopen failed"; - case LoadError::SymbolMissing: return "required symbol missing"; - case LoadError::AbiMismatch: return "ABI version mismatch"; - case LoadError::CreateFailed: return "plugin create() returned null"; - 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"; - } - return "unknown"; -} + std::string_view to_string(LoadError e) noexcept + { + switch (e) { + case LoadError::FileNotFound: + return "file not found"; + case LoadError::DlopenFailed: + return "dlopen failed"; + case LoadError::SymbolMissing: + return "required symbol missing"; + case LoadError::AbiMismatch: + return "ABI version mismatch"; + case LoadError::CreateFailed: + return "plugin create() returned null"; + 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 - if (plugin_) { - plugin_->on_unload(); - if (destroy_) destroy_(plugin_); - plugin_ = nullptr; - } - if (handle_) { - dlclose(handle_); - handle_ = nullptr; - } - destroy_ = nullptr; - transfer_ = nullptr; - ready_ = nullptr; - state_version_ = nullptr; - serialize_ = nullptr; - free_string_ = nullptr; - deserialize_ = nullptr; + if (plugin_) { + plugin_->on_unload(); + if (destroy_) { + destroy_(plugin_); + } + plugin_ = nullptr; + } + if (handle_) { + dlclose(handle_); + handle_ = nullptr; + } + destroy_ = nullptr; + transfer_ = nullptr; + ready_ = nullptr; + state_version_ = nullptr; + serialize_ = nullptr; + free_string_ = nullptr; + deserialize_ = nullptr; #endif -} + } -// Move plugin state old -> new across a reload. Prefers the v2 -// serialize/deserialize protocol (survives layout changes between -// versions); falls back to the raw transfer_state hook; else no-op. -// Returns false only when the new instance actively rejects the state. -bool transfer_plugin_state(const PluginLoader& from, PluginLoader& to) -{ - if (!from.plugin_ || !to.plugin_) { - return true; - } - if (from.serialize_ && to.deserialize_) { - const std::uint32_t from_version = - from.state_version_ ? from.state_version_() : 0; - const char* json = from.serialize_(from.plugin_); - if (json != nullptr) { - const int rc = to.deserialize_(to.plugin_, json, from_version); - if (from.free_string_) { - from.free_string_(json); - } - if (rc != 0) { - Void::Log::warn("Plugin", - "deserialize_state rejected state " - "(from v{}, rc={})", - from_version, rc); - return false; - } - Void::Log::debug("Plugin", - "state transferred via v2 protocol (v{})", - from_version); - return true; - } - } - if (to.transfer_) { - to.transfer_(from.plugin_, to.plugin_); - Void::Log::debug("Plugin", "state transferred via transfer_state"); - } - return true; -} + // Move plugin state old -> new across a reload. Prefers the v2 + // serialize/deserialize protocol (survives layout changes between + // versions); falls back to the raw transfer_state hook; else no-op. + // Returns false only when the new instance actively rejects the state. + bool transfer_plugin_state(const PluginLoader& from, PluginLoader& to) + { + if (!from.plugin_ || !to.plugin_) { + return true; + } + if (from.serialize_ && to.deserialize_) { + const std::uint32_t from_version = + from.state_version_ ? from.state_version_() : 0; + const char* json = from.serialize_(from.plugin_); + if (json != nullptr) { + const int rc = to.deserialize_(to.plugin_, json, from_version); + if (from.free_string_) { + from.free_string_(json); + } + if (rc != 0) { + Void::Log::warn("Plugin", + "deserialize_state rejected state " + "(from v{}, rc={})", + from_version, rc); + return false; + } + Void::Log::debug("Plugin", + "state transferred via v2 protocol (v{})", + from_version); + return true; + } + } + if (to.transfer_) { + to.transfer_(from.plugin_, to.plugin_); + Void::Log::debug("Plugin", "state transferred via transfer_state"); + } + return true; + } -std::expected -PluginLoader::load_from(const std::filesystem::path& path) -{ + std::expected + PluginLoader::load_from(const std::filesystem::path& path) + { #ifdef VOID_HAS_DLOPEN - void* h = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); - if (!h) return std::unexpected{LoadError::DlopenFailed}; + void* h = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + if (!h) { + return std::unexpected{LoadError::DlopenFailed}; + } - const auto sym_info = reinterpret_cast (dlsym(h, kInfoSymbol)); - const auto sym_create = reinterpret_cast (dlsym(h, kCreateSymbol)); - const auto sym_destroy = reinterpret_cast(dlsym(h, kDestroySymbol)); + const auto sym_info = reinterpret_cast(dlsym(h, kInfoSymbol)); + const auto sym_create = + reinterpret_cast(dlsym(h, kCreateSymbol)); + const auto sym_destroy = + reinterpret_cast(dlsym(h, kDestroySymbol)); - if (!sym_info || !sym_create || !sym_destroy) { - dlclose(h); - return std::unexpected{LoadError::SymbolMissing}; - } + if (!sym_info || !sym_create || !sym_destroy) { + dlclose(h); + return std::unexpected{LoadError::SymbolMissing}; + } - const PluginInfo info = sym_info(); - if (info.abi_version != ABI_VERSION) { - dlclose(h); - return std::unexpected{LoadError::AbiMismatch}; - } + const PluginInfo info = sym_info(); + if (info.abi_version != ABI_VERSION) { + dlclose(h); + return std::unexpected{LoadError::AbiMismatch}; + } - void* raw = sym_create(); - if (!raw) { - dlclose(h); - return std::unexpected{LoadError::CreateFailed}; - } + void* raw = sym_create(); + if (!raw) { + dlclose(h); + return std::unexpected{LoadError::CreateFailed}; + } - handle_ = h; - plugin_ = static_cast(raw); - destroy_ = sym_destroy; - transfer_ = reinterpret_cast(dlsym(h, kTransferSymbol)); - ready_ = reinterpret_cast(dlsym(h, kReadySymbol)); - state_version_ = reinterpret_cast( - dlsym(h, kStateVersionSymbol)); - serialize_ = reinterpret_cast(dlsym(h, kSerializeSymbol)); - free_string_ = reinterpret_cast( - dlsym(h, kFreeStringSymbol)); - deserialize_ = reinterpret_cast( - dlsym(h, kDeserializeSymbol)); - info_ = info; - return {}; + handle_ = h; + plugin_ = static_cast(raw); + destroy_ = sym_destroy; + transfer_ = reinterpret_cast(dlsym(h, kTransferSymbol)); + ready_ = reinterpret_cast(dlsym(h, kReadySymbol)); + state_version_ = + reinterpret_cast(dlsym(h, kStateVersionSymbol)); + serialize_ = reinterpret_cast(dlsym(h, kSerializeSymbol)); + free_string_ = + reinterpret_cast(dlsym(h, kFreeStringSymbol)); + deserialize_ = + reinterpret_cast(dlsym(h, kDeserializeSymbol)); + info_ = info; + return {}; #else - (void)path; - return std::unexpected{LoadError::NotSupported}; + (void)path; + return std::unexpected{LoadError::NotSupported}; #endif -} + } -// ── public API ──────────────────────────────────────────────────────────────── + // ── public API + // ──────────────────────────────────────────────────────────────── -std::expected -PluginLoader::load(std::filesystem::path path) -{ - if (!std::filesystem::exists(path)) - return std::unexpected{LoadError::FileNotFound}; + std::expected + PluginLoader::load(std::filesystem::path path) + { + if (!std::filesystem::exists(path)) { + return std::unexpected{LoadError::FileNotFound}; + } - PluginLoader ldr; - ldr.path_ = path; + PluginLoader ldr; + ldr.path_ = path; - if (auto r = ldr.load_from(path); !r) { - Void::Log::warn("Plugin", "load '{}' failed: {}", path.string(), - to_string(r.error())); - return std::unexpected{r.error()}; - } + if (auto r = ldr.load_from(path); !r) { + Void::Log::warn("Plugin", "load '{}' failed: {}", path.string(), + to_string(r.error())); + return std::unexpected{r.error()}; + } - try { - ldr.plugin_->on_load(); - } catch (...) { - return std::unexpected{LoadError::ActivationFailed}; - } - if (ldr.ready_ && ldr.ready_(ldr.plugin_) != 0) { - return std::unexpected{LoadError::ActivationFailed}; - } - Void::Log::info("Plugin", "loaded '{}' ({} v{})", path.string(), - ldr.info_.name, ldr.info_.plugin_version); - return ldr; -} + try { + ldr.plugin_->on_load(); + } catch (...) { + return std::unexpected{LoadError::ActivationFailed}; + } + if (ldr.ready_ && ldr.ready_(ldr.plugin_) != 0) { + return std::unexpected{LoadError::ActivationFailed}; + } + Void::Log::info("Plugin", "loaded '{}' ({} v{})", path.string(), + ldr.info_.name, ldr.info_.plugin_version); + return ldr; + } -PluginLoader::~PluginLoader() { destroy_current(); } + PluginLoader::~PluginLoader() { destroy_current(); } -PluginLoader::PluginLoader(PluginLoader&& o) noexcept - : handle_ {std::exchange(o.handle_, nullptr)} - , plugin_ {std::exchange(o.plugin_, nullptr)} - , destroy_ {std::exchange(o.destroy_, nullptr)} - , transfer_ {std::exchange(o.transfer_, nullptr)} - , ready_ {std::exchange(o.ready_, nullptr)} - , state_version_{std::exchange(o.state_version_, nullptr)} - , serialize_ {std::exchange(o.serialize_, nullptr)} - , free_string_ {std::exchange(o.free_string_, nullptr)} - , deserialize_ {std::exchange(o.deserialize_, nullptr)} - , info_ {o.info_} - , path_ {std::move(o.path_)} -{} + PluginLoader::PluginLoader(PluginLoader&& o) noexcept + : handle_{std::exchange(o.handle_, nullptr)}, + plugin_{std::exchange(o.plugin_, nullptr)}, + destroy_{std::exchange(o.destroy_, nullptr)}, + transfer_{std::exchange(o.transfer_, nullptr)}, + ready_{std::exchange(o.ready_, nullptr)}, + state_version_{std::exchange(o.state_version_, nullptr)}, + serialize_{std::exchange(o.serialize_, nullptr)}, + free_string_{std::exchange(o.free_string_, nullptr)}, + deserialize_{std::exchange(o.deserialize_, nullptr)}, info_{o.info_}, + path_{std::move(o.path_)} + { + } -PluginLoader& PluginLoader::operator=(PluginLoader&& o) noexcept -{ - if (this != &o) { - destroy_current(); - handle_ = std::exchange(o.handle_, nullptr); - plugin_ = std::exchange(o.plugin_, nullptr); - destroy_ = std::exchange(o.destroy_, nullptr); - transfer_ = std::exchange(o.transfer_, nullptr); - ready_ = std::exchange(o.ready_, nullptr); - state_version_ = std::exchange(o.state_version_, nullptr); - serialize_ = std::exchange(o.serialize_, nullptr); - free_string_ = std::exchange(o.free_string_, nullptr); - deserialize_ = std::exchange(o.deserialize_, nullptr); - info_ = o.info_; - path_ = std::move(o.path_); - } - return *this; -} + PluginLoader& PluginLoader::operator=(PluginLoader&& o) noexcept + { + if (this != &o) { + destroy_current(); + handle_ = std::exchange(o.handle_, nullptr); + plugin_ = std::exchange(o.plugin_, nullptr); + destroy_ = std::exchange(o.destroy_, nullptr); + transfer_ = std::exchange(o.transfer_, nullptr); + ready_ = std::exchange(o.ready_, nullptr); + state_version_ = std::exchange(o.state_version_, nullptr); + serialize_ = std::exchange(o.serialize_, nullptr); + free_string_ = std::exchange(o.free_string_, nullptr); + deserialize_ = std::exchange(o.deserialize_, nullptr); + info_ = o.info_; + path_ = std::move(o.path_); + } + return *this; + } -std::expected PluginLoader::reload() -{ + std::expected PluginLoader::reload() + { #ifdef VOID_HAS_DLOPEN - // 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. - const auto tmp = path_.parent_path() - / (path_.filename().string() + ".void_hotswap"); + // 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. + const auto tmp = + path_.parent_path() / (path_.filename().string() + ".void_hotswap"); - { - std::error_code ec; - std::filesystem::copy_file(path_, tmp, - std::filesystem::copy_options::overwrite_existing, ec); - if (ec) return std::unexpected{LoadError::FileNotFound}; - } + { + std::error_code ec; + std::filesystem::copy_file( + path_, tmp, std::filesystem::copy_options::overwrite_existing, + ec); + if (ec) { + return std::unexpected{LoadError::FileNotFound}; + } + } - // Load new instance while old is still alive (for state transfer). - PluginLoader next; - next.path_ = path_; - if (auto r = next.load_from(tmp); !r) { - std::error_code ec; - std::filesystem::remove(tmp, ec); - Void::Log::warn("Plugin", "reload '{}' failed: {}; keeping old", - path_.string(), to_string(r.error())); - return r; - } + // Load new instance while old is still alive (for state transfer). + PluginLoader next; + next.path_ = path_; + if (auto r = next.load_from(tmp); !r) { + std::error_code ec; + std::filesystem::remove(tmp, ec); + Void::Log::warn("Plugin", "reload '{}' failed: {}; keeping old", + path_.string(), to_string(r.error())); + return r; + } - // Transfer state with both instances alive. A rejection aborts the - // reload and keeps the old instance. - if (!transfer_plugin_state(*this, next)) { - std::error_code ec; - std::filesystem::remove(tmp, ec); - Void::Log::warn("Plugin", "reload '{}' aborted: state rejected", - path_.string()); - return std::unexpected{LoadError::StateRejected}; - } + // Transfer state with both instances alive. A rejection aborts the + // reload and keeps the old instance. + if (!transfer_plugin_state(*this, next)) { + std::error_code ec; + std::filesystem::remove(tmp, ec); + Void::Log::warn("Plugin", "reload '{}' aborted: state rejected", + path_.string()); + return std::unexpected{LoadError::StateRejected}; + } - try { - next.plugin_->on_load(); - } catch (...) { - std::error_code ec; - std::filesystem::remove(tmp, ec); - return std::unexpected{LoadError::ActivationFailed}; - } - if (next.ready_ && next.ready_(next.plugin_) != 0) { - std::error_code ec; - std::filesystem::remove(tmp, ec); - return std::unexpected{LoadError::ActivationFailed}; - } + try { + next.plugin_->on_load(); + } catch (...) { + std::error_code ec; + std::filesystem::remove(tmp, ec); + return std::unexpected{LoadError::ActivationFailed}; + } + if (next.ready_ && next.ready_(next.plugin_) != 0) { + std::error_code ec; + std::filesystem::remove(tmp, ec); + return std::unexpected{LoadError::ActivationFailed}; + } - // Activation succeeded; only now destroy old and install new. - destroy_current(); - *this = std::move(next); - Void::Log::info("Plugin", "reloaded '{}' ({} v{})", path_.string(), - info_.name, info_.plugin_version); + // Activation succeeded; only now destroy old and install new. + destroy_current(); + *this = std::move(next); + Void::Log::info("Plugin", "reloaded '{}' ({} v{})", path_.string(), + info_.name, info_.plugin_version); - std::error_code ec; - std::filesystem::remove(tmp, ec); - return {}; + std::error_code ec; + std::filesystem::remove(tmp, ec); + return {}; #else - return std::unexpected{LoadError::NotSupported}; + return std::unexpected{LoadError::NotSupported}; #endif -} + } } // namespace Void::Plugin diff --git a/src/Plugin/Manager.cpp b/src/Plugin/Manager.cpp index 58fb5a3..58adfe9 100644 --- a/src/Plugin/Manager.cpp +++ b/src/Plugin/Manager.cpp @@ -122,8 +122,7 @@ namespace Void::Plugin reinterpret_cast(dlsym(h, kTransferSymbol)); inst->configure = reinterpret_cast(dlsym(h, kConfigureSymbol)); - inst->ready = - reinterpret_cast(dlsym(h, kReadySymbol)); + inst->ready = reinterpret_cast(dlsym(h, kReadySymbol)); inst->state_version = reinterpret_cast( dlsym(h, kStateVersionSymbol)); inst->serialize = @@ -183,10 +182,10 @@ namespace Void::Plugin hotswap_copy(const std::filesystem::path& path) { static std::atomic counter{0}; - const auto tmp = - path.parent_path() / - (path.filename().string() + ".void_hotswap." + - std::to_string(counter.fetch_add(1, std::memory_order_relaxed))); + const auto tmp = path.parent_path() / + (path.filename().string() + ".void_hotswap." + + std::to_string(counter.fetch_add( + 1, std::memory_order_relaxed))); std::error_code ec; std::filesystem::copy_file( path, tmp, std::filesystem::copy_options::overwrite_existing, @@ -251,8 +250,7 @@ namespace Void::Plugin } catch (...) { return std::unexpected{LoadError::ActivationFailed}; } - if ((*inst)->ready != nullptr && - (*inst)->ready((*inst)->plugin) != 0) { + if ((*inst)->ready != nullptr && (*inst)->ready((*inst)->plugin) != 0) { return std::unexpected{LoadError::ActivationFailed}; } if (m_options.instance_validator && @@ -338,7 +336,7 @@ namespace Void::Plugin if (entry == nullptr) { return std::unexpected{LoadError::UnknownPlugin}; } - auto result = reload_locked(*entry, name); + auto result = reload_locked(*entry, name, entry->path); if (!result.has_value()) { return result; } @@ -351,14 +349,51 @@ namespace Void::Plugin } std::expected - PluginManager::reload_locked(Entry& entry, std::string_view name) + PluginManager::replace(std::string_view name, + const std::filesystem::path& newPath) + { + std::vector> 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 + 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 // returning the still-open handle for this path. The caller must // have installed the new file via atomic rename (a fresh inode of // its own) — overwriting the mapped file in place corrupts the // running instance's mapping (SIGBUS). - auto tmp = hotswap_copy(entry.path); + auto tmp = hotswap_copy(sourcePath); if (!tmp.has_value()) { return std::unexpected{tmp.error()}; } @@ -371,6 +406,12 @@ namespace Void::Plugin to_string(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) { const std::string config = m_options.config_provider(name); @@ -392,16 +433,16 @@ namespace Void::Plugin } catch (...) { return std::unexpected{LoadError::ActivationFailed}; } - if ((*next)->ready != nullptr && - (*next)->ready((*next)->plugin) != 0) { + if ((*next)->ready != nullptr && (*next)->ready((*next)->plugin) != 0) { Void::Log::warn("Plugin.Manager", - "reload '{}' aborted: activation failed", name); + "reload '{}' aborted: activation failed", name); return std::unexpected{LoadError::ActivationFailed}; } if (m_options.instance_validator && !m_options.instance_validator(*(*next)->plugin, (*next)->info)) { Void::Log::warn("Plugin.Manager", - "reload '{}' aborted: host validation failed", name); + "reload '{}' aborted: host validation failed", + name); return std::unexpected{LoadError::ActivationFailed}; } // Atomic swap. The old instance keeps living while any acquired @@ -421,29 +462,30 @@ namespace Void::Plugin return; } path = entry->path; + entry->watched = true; } const std::string name_str{name}; - m_watcher.watch( - path, [this, name_str](const FileSystem::FileWatcher::Event& e) { - if (!e.exists) { + m_watcher.watch(path, [this, name_str]( + const FileSystem::FileWatcher::Event& e) { + if (!e.exists) { + return; + } + std::vector> callbacks; + { + std::lock_guard lock(m_mutex); + auto* entry = find(name_str); + if (entry == nullptr) { return; } - std::vector> callbacks; - { - 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(); + if (!reload_locked(*entry, name_str, entry->path).has_value()) { + return; } - for (const auto& cb : callbacks) { - cb(name_str); - } - }); + callbacks = reload_callbacks_locked(); + } + for (const auto& cb : callbacks) { + cb(name_str); + } + }); } void PluginManager::unwatch(std::string_view name) @@ -452,6 +494,7 @@ namespace Void::Plugin auto* entry = find(name); if (entry != nullptr) { m_watcher.unwatch(entry->path); + entry->watched = false; } } diff --git a/src/System/SignalWatcher.cpp b/src/System/SignalWatcher.cpp new file mode 100644 index 0000000..ddfa71b --- /dev/null +++ b/src/System/SignalWatcher.cpp @@ -0,0 +1,146 @@ +#include + +#include +#include +#include +#include +#include +#include +#include + +#ifdef __linux__ +#include +#include +#include +#include +#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) noexcept + : m_impl(std::move(impl)) + { + } + + SignalWatcher::~SignalWatcher() = default; + SignalWatcher::SignalWatcher(SignalWatcher&&) noexcept = default; + SignalWatcher& SignalWatcher::operator=(SignalWatcher&&) noexcept = default; + + Void::Result::Result + SignalWatcher::create(std::vector 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->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> + 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(std::clamp( + 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{}; + } + 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(sizeof(info))) { + return Void::Result::fail( + std::format("Process::SignalWatcher::wait: read failed: {}", + std::strerror(errno))); + } + return std::optional{static_cast(info.ssi_signo)}; +#else + (void)timeout; + return Void::Result::fail( + "Process::SignalWatcher is currently supported only on Linux"); +#endif + } + + Void::Result::Result> SignalWatcher::poll() + { + return wait(std::chrono::milliseconds{0}); + } +} // namespace Void::Process diff --git a/src/System/module.cmake b/src/System/module.cmake index 2c60c13..a1b6ee8 100644 --- a/src/System/module.cmake +++ b/src/System/module.cmake @@ -1,3 +1,4 @@ void_add_module(System INTERNAL_DEPS Functional + EXTERNAL_DEPS Threads::Threads ) diff --git a/src/Update/Feed.cpp b/src/Update/Feed.cpp new file mode 100644 index 0000000..9f1eb54 --- /dev/null +++ b/src/Update/Feed.cpp @@ -0,0 +1,488 @@ +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Update +{ + namespace + { + using JsonResult = Void::Result::Result; + + [[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 + [[nodiscard]] Void::Result::Result + 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(std::numeric_limits::max())) { + return Void::Result::fail(std::format( + "Update feed: '{}' is outside its integer range", name)); + } + return static_cast(number); + } + + [[nodiscard]] Void::Result::Result + 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 + 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 + 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(*month)}, + std::chrono::day{static_cast(*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 + 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 + 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(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 + 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(*document, "schemaVersion"); + auto feedId = string_member(*document, "feedId"); + auto sequence = + unsigned_number(*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> + 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 + 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 + 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(*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 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 diff --git a/src/Update/VersionStore.cpp b/src/Update/VersionStore.cpp new file mode 100644 index 0000000..fe67952 --- /dev/null +++ b/src/Update/VersionStore.cpp @@ -0,0 +1,1826 @@ +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef _WIN32 +#include +#include +#include +#include +#include +#include +#include +#endif + +namespace Void::Update +{ + namespace + { + [[nodiscard]] Void::Result::Error + filesystem_error(std::string_view operation, + const std::filesystem::path& path, + const std::error_code& error) + { + return Void::Result::Error{std::format("VersionStore: {} '{}': {}", + operation, path.string(), + error.message())}; + } + + [[nodiscard]] Void::Result::Result + require_real_directory(const std::filesystem::path& path) + { + std::error_code error; + const auto status = std::filesystem::symlink_status(path, error); + if (error) { + return std::unexpected{ + filesystem_error("inspect directory", path, error)}; + } + if (std::filesystem::is_symlink(status) || + !std::filesystem::is_directory(status)) { + return Void::Result::fail( + std::format("VersionStore: '{}' must be a real directory", + path.string())); + } + return {}; + } + + [[nodiscard]] Void::Result::Result + ensure_real_directory(const std::filesystem::path& path) + { + std::error_code error; + const auto status = std::filesystem::symlink_status(path, error); + if (!error && std::filesystem::exists(status)) { + return require_real_directory(path); + } + if (error != std::errc::no_such_file_or_directory && error) { + return std::unexpected{ + filesystem_error("inspect directory", path, error)}; + } + error.clear(); + std::filesystem::create_directories(path, error); + if (error) { + return std::unexpected{ + filesystem_error("create directory", path, error)}; + } + return require_real_directory(path); + } + + constexpr std::uintmax_t maximumActivationJournalSize = 64 * 1024; + +#ifdef _WIN32 + [[nodiscard]] Void::Result::Result + read_file(const std::filesystem::path& path) + { + std::ifstream input{path, std::ios::binary}; + if (!input.is_open()) { + return Void::Result::fail(std::format( + "VersionStore: cannot read '{}'", path.string())); + } + std::string data{std::istreambuf_iterator{input}, {}}; + if (input.bad()) { + return Void::Result::fail(std::format( + "VersionStore: I/O error reading '{}'", path.string())); + } + return data; + } +#endif + +#ifndef _WIN32 + class FileDescriptor + { + public: + + explicit FileDescriptor(int descriptor = -1) noexcept + : m_descriptor(descriptor) + { + } + ~FileDescriptor() + { + if (m_descriptor >= 0) { + (void)::close(m_descriptor); + } + } + FileDescriptor(FileDescriptor&& other) noexcept + : m_descriptor(std::exchange(other.m_descriptor, -1)) + { + } + FileDescriptor& operator=(FileDescriptor&& other) noexcept + { + if (this != &other) { + if (m_descriptor >= 0) { + (void)::close(m_descriptor); + } + m_descriptor = 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; } + + private: + + int m_descriptor{-1}; + }; + + class FileLock + { + public: + + [[nodiscard]] static Void::Result::Result + acquire(const std::filesystem::path& path) + { + const int descriptor = + ::open(path.c_str(), + O_RDWR | O_CREAT | O_CLOEXEC | O_NOFOLLOW, 0600); + if (descriptor < 0) { + return Void::Result::fail( + std::format("VersionStore: open lock '{}': {}", + path.string(), std::strerror(errno))); + } + // The lock contains no data. Read permission lets an + // unprivileged runtime take a shared lock while a + // privileged updater remains the only writer. + if (::fchmod(descriptor, 0644) != 0) { + const auto message = + std::format("VersionStore: set lock mode '{}': {}", + path.string(), std::strerror(errno)); + ::close(descriptor); + return Void::Result::fail(message); + } + if (::flock(descriptor, LOCK_EX) != 0) { + const auto message = + std::format("VersionStore: lock '{}': {}", + path.string(), std::strerror(errno)); + ::close(descriptor); + return Void::Result::fail(message); + } + return FileLock{descriptor}; + } + + [[nodiscard]] static Void::Result::Result + acquireShared(const std::filesystem::path& path) + { + const int descriptor = + ::open(path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW); + if (descriptor < 0) { + return Void::Result::fail( + std::format("VersionStore: open lock '{}': {}", + path.string(), std::strerror(errno))); + } + if (::flock(descriptor, LOCK_SH) != 0) { + const auto message = + std::format("VersionStore: lock '{}': {}", + path.string(), std::strerror(errno)); + ::close(descriptor); + return Void::Result::fail(message); + } + return FileLock{descriptor}; + } + + ~FileLock() + { + if (m_descriptor >= 0) { + (void)::flock(m_descriptor, LOCK_UN); + (void)::close(m_descriptor); + } + } + FileLock(FileLock&& other) noexcept + : m_descriptor(std::exchange(other.m_descriptor, -1)) + { + } + FileLock& operator=(FileLock&& other) noexcept + { + if (this != &other) { + if (m_descriptor >= 0) { + (void)::flock(m_descriptor, LOCK_UN); + (void)::close(m_descriptor); + } + m_descriptor = std::exchange(other.m_descriptor, -1); + } + return *this; + } + FileLock(const FileLock&) = delete; + FileLock& operator=(const FileLock&) = delete; + + private: + + explicit FileLock(int descriptor) noexcept + : m_descriptor(descriptor) + { + } + int m_descriptor{-1}; + }; + + [[nodiscard]] Void::Result::Result + sync_directory(const std::filesystem::path& path) + { + const int descriptor = ::open( + path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW); + if (descriptor < 0) { + return Void::Result::fail( + std::format("VersionStore: open directory '{}': {}", + path.string(), std::strerror(errno))); + } + const int result = ::fsync(descriptor); + const int error = errno; + (void)::close(descriptor); + if (result != 0) { + return Void::Result::fail( + std::format("VersionStore: fsync directory '{}': {}", + path.string(), std::strerror(error))); + } + return {}; + } + + [[nodiscard]] std::filesystem::path + temporary_sibling(const std::filesystem::path& path) + { + static std::atomic counter{0}; + return path.parent_path() / + std::format(".{}.{}.{}", path.filename().string(), + static_cast(::getpid()), + counter.fetch_add(1, std::memory_order_relaxed)); + } + + [[nodiscard]] Void::Result::Result + durable_write(const std::filesystem::path& path, + std::string_view data, + const bool readableByOthers = false) + { + const auto temporary = temporary_sibling(path); + const mode_t mode = readableByOthers ? 0644 : 0600; + const int descriptor = + ::open(temporary.c_str(), + O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, mode); + if (descriptor < 0) { + return Void::Result::fail( + std::format("VersionStore: create '{}': {}", + temporary.string(), std::strerror(errno))); + } + if (::fchmod(descriptor, mode) != 0) { + const auto message = + std::format("VersionStore: set mode '{}': {}", + temporary.string(), std::strerror(errno)); + (void)::close(descriptor); + (void)::unlink(temporary.c_str()); + return Void::Result::fail(message); + } + std::size_t written = 0; + while (written < data.size()) { + const auto count = ::write(descriptor, data.data() + written, + data.size() - written); + if (count < 0 && errno == EINTR) { + continue; + } + if (count <= 0) { + const auto message = + std::format("VersionStore: write '{}': {}", + temporary.string(), std::strerror(errno)); + (void)::close(descriptor); + (void)::unlink(temporary.c_str()); + return Void::Result::fail(message); + } + written += static_cast(count); + } + if (::fsync(descriptor) != 0) { + const auto message = + std::format("VersionStore: fsync '{}': {}", + temporary.string(), std::strerror(errno)); + (void)::close(descriptor); + (void)::unlink(temporary.c_str()); + return Void::Result::fail(message); + } + if (::close(descriptor) != 0) { + (void)::unlink(temporary.c_str()); + return Void::Result::fail( + std::format("VersionStore: close '{}': {}", + temporary.string(), std::strerror(errno))); + } + if (::rename(temporary.c_str(), path.c_str()) != 0) { + const auto message = std::format( + "VersionStore: rename '{}' to '{}': {}", temporary.string(), + path.string(), std::strerror(errno)); + (void)::unlink(temporary.c_str()); + return Void::Result::fail(message); + } + return sync_directory(path.parent_path()); + } + + [[nodiscard]] Void::Result::Result + atomic_link(const std::filesystem::path& path, + const std::filesystem::path& target) + { + const auto temporary = temporary_sibling(path); + if (::symlink(target.c_str(), temporary.c_str()) != 0) { + return Void::Result::fail( + std::format("VersionStore: create symlink '{}': {}", + temporary.string(), std::strerror(errno))); + } + if (::rename(temporary.c_str(), path.c_str()) != 0) { + const auto message = + std::format("VersionStore: activate symlink '{}': {}", + path.string(), std::strerror(errno)); + (void)::unlink(temporary.c_str()); + return Void::Result::fail(message); + } + return sync_directory(path.parent_path()); + } + + [[nodiscard]] Void::Result::Result + open_real_directory(const std::filesystem::path& path) + { + const int descriptor = ::open( + path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW); + if (descriptor < 0) { + return Void::Result::fail( + std::format("VersionStore: open directory '{}': {}", + path.string(), std::strerror(errno))); + } + return FileDescriptor{descriptor}; + } + + [[nodiscard]] + Void::Result::Result> + read_activation_journal(const std::filesystem::path& root) + { + const int directoryFlags = O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW +#ifdef O_PATH + | O_PATH +#else + | O_RDONLY +#endif + ; + FileDescriptor directory{::open(root.c_str(), directoryFlags)}; + if (directory.get() < 0) { + return Void::Result::fail( + std::format("VersionStore: open directory '{}': {}", + root.string(), std::strerror(errno))); + } + FileDescriptor descriptor{ + ::openat(directory.get(), "activation.json", + O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)}; + if (descriptor.get() < 0) { + if (errno == ENOENT) { + return std::optional{}; + } + return Void::Result::fail(std::format( + "VersionStore: open activation journal '{}': {}", + (root / "activation.json").string(), std::strerror(errno))); + } + + struct stat status{}; + if (::fstat(descriptor.get(), &status) != 0) { + return Void::Result::fail(std::format( + "VersionStore: inspect activation journal '{}': {}", + (root / "activation.json").string(), std::strerror(errno))); + } + if (!S_ISREG(status.st_mode) || status.st_nlink != 1 || + status.st_size < 0 || + static_cast(status.st_size) > + maximumActivationJournalSize) { + return Void::Result::fail( + "VersionStore: activation journal must be a bounded " + "regular file"); + } + + std::string data(static_cast(status.st_size), '\0'); + std::size_t read = 0; + while (read < data.size()) { + const auto count = ::read(descriptor.get(), data.data() + read, + data.size() - read); + if (count < 0 && errno == EINTR) { + continue; + } + if (count <= 0) { + return Void::Result::fail(std::format( + "VersionStore: read activation journal '{}': {}", + (root / "activation.json").string(), + count == 0 ? "unexpected end of file" + : std::strerror(errno))); + } + read += static_cast(count); + } + struct stat finalStatus{}; + if (::fstat(descriptor.get(), &finalStatus) != 0 || + finalStatus.st_size != status.st_size) { + return Void::Result::fail( + "VersionStore: activation journal changed while reading"); + } + return std::optional{std::move(data)}; + } + + [[nodiscard]] Void::Result::Result + require_published_real_directory(const std::filesystem::path& root, + std::string_view versionName) + { + auto versions = open_real_directory(root / "versions"); + if (!versions) { + return std::unexpected{versions.error()}; + } + const std::string name{versionName}; + struct stat status{}; + if (::fstatat(versions->get(), name.c_str(), &status, + AT_SYMLINK_NOFOLLOW) != 0 || + !S_ISDIR(status.st_mode)) { + return Void::Result::fail( + std::format("VersionStore: version '{}' is not a real " + "published directory", + versionName)); + } + FileDescriptor opened{ + ::openat(versions->get(), name.c_str(), + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)}; + if (opened.get() < 0) { + return Void::Result::fail( + std::format("VersionStore: open published version '{}': {}", + versionName, std::strerror(errno))); + } + struct stat openedStatus{}; + if (::fstat(opened.get(), &openedStatus) != 0 || + openedStatus.st_dev != status.st_dev || + openedStatus.st_ino != status.st_ino) { + return Void::Result::fail( + std::format("VersionStore: published version '{}' changed " + "while validating", + versionName)); + } + return {}; + } + + [[nodiscard]] Void::Result::Result> + directory_entries(int descriptor, + const std::filesystem::path& displayPath) + { + const int duplicate = + ::openat(descriptor, ".", + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW); + if (duplicate < 0) { + return Void::Result::fail( + std::format("VersionStore: duplicate directory '{}': {}", + displayPath.string(), std::strerror(errno))); + } + DIR* stream = ::fdopendir(duplicate); + if (stream == nullptr) { + const int error = errno; + (void)::close(duplicate); + return Void::Result::fail( + std::format("VersionStore: enumerate directory '{}': {}", + displayPath.string(), std::strerror(error))); + } + + std::vector entries; + errno = 0; + while (const auto* entry = ::readdir(stream)) { + const std::string_view name{entry->d_name}; + if (name != "." && name != "..") { + entries.emplace_back(name); + } + errno = 0; + } + const int error = errno; + (void)::closedir(stream); + if (error != 0) { + return Void::Result::fail( + std::format("VersionStore: enumerate directory '{}': {}", + displayPath.string(), std::strerror(error))); + } + return entries; + } + + constexpr std::size_t maximumRemovalDepth = 128; + constexpr int maximumRemovalPasses = 16; + + [[nodiscard]] Void::Result::Result + remove_entry_no_follow(int parentDescriptor, std::string_view name, + const std::filesystem::path& displayPath, + std::size_t depth = 0) + { + if (depth > maximumRemovalDepth) { + return Void::Result::fail( + std::format("VersionStore: removal depth exceeded at '{}'", + displayPath.string())); + } + const std::string entryName{name}; + for (int attempt = 0; attempt < maximumRemovalPasses; ++attempt) { + struct stat status{}; + if (::fstatat(parentDescriptor, entryName.c_str(), &status, + AT_SYMLINK_NOFOLLOW) != 0) { + if (errno == ENOENT) { + return {}; + } + return Void::Result::fail(std::format( + "VersionStore: inspect removal entry '{}': {}", + displayPath.string(), std::strerror(errno))); + } + + if (!S_ISDIR(status.st_mode)) { + if (::unlinkat(parentDescriptor, entryName.c_str(), 0) == + 0 || + errno == ENOENT) { + return {}; + } + if (errno == EISDIR) { + continue; + } + return Void::Result::fail(std::format( + "VersionStore: remove entry '{}': {}", + displayPath.string(), std::strerror(errno))); + } + + FileDescriptor child{ + ::openat(parentDescriptor, entryName.c_str(), + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)}; + if (child.get() < 0) { + if (errno == ENOENT) { + return {}; + } + if (errno == ELOOP || errno == ENOTDIR) { + continue; + } + return Void::Result::fail(std::format( + "VersionStore: open removal directory '{}': {}", + displayPath.string(), std::strerror(errno))); + } + struct stat openedStatus{}; + if (::fstat(child.get(), &openedStatus) != 0) { + return Void::Result::fail(std::format( + "VersionStore: inspect opened directory '{}': {}", + displayPath.string(), std::strerror(errno))); + } + if (openedStatus.st_dev != status.st_dev || + openedStatus.st_ino != status.st_ino) { + continue; + } + + auto entries = directory_entries(child.get(), displayPath); + if (!entries) { + return std::unexpected{entries.error()}; + } + for (const auto& childName : *entries) { + if (auto removed = remove_entry_no_follow( + child.get(), childName, displayPath / childName, + depth + 1); + !removed) { + return removed; + } + } + + if (::unlinkat(parentDescriptor, entryName.c_str(), + AT_REMOVEDIR) == 0 || + errno == ENOENT) { + return {}; + } + if (errno != ENOTEMPTY && errno != EEXIST && errno != ENOTDIR) { + return Void::Result::fail(std::format( + "VersionStore: remove directory '{}': {}", + displayPath.string(), std::strerror(errno))); + } + } + return Void::Result::fail(std::format( + "VersionStore: directory '{}' changed while pruning", + displayPath.string())); + } +#else + struct FileLock { + [[nodiscard]] static Void::Result::Result + acquire(const std::filesystem::path&) + { + return FileLock{}; + } + [[nodiscard]] static Void::Result::Result + acquireShared(const std::filesystem::path&) + { + return FileLock{}; + } + }; + [[nodiscard]] Void::Result::Result + sync_directory(const std::filesystem::path&) + { + return {}; + } + [[nodiscard]] Void::Result::Result + durable_write(const std::filesystem::path& path, + std::string_view data, + const bool readableByOthers = false) + { + (void)readableByOthers; + std::ofstream output{path.string() + ".tmp", + std::ios::binary | std::ios::trunc}; + if (!output) { + return Void::Result::fail( + "VersionStore: create journal failed"); + } + output.write(data.data(), + static_cast(data.size())); + output.close(); + std::error_code error; + std::filesystem::rename(path.string() + ".tmp", path, error); + if (error) { + return std::unexpected{filesystem_error("rename", path, error)}; + } + return {}; + } + [[nodiscard]] Void::Result::Result + atomic_link(const std::filesystem::path& path, + const std::filesystem::path& target) + { + std::error_code error; + std::filesystem::remove(path, error); + error.clear(); + std::filesystem::create_directory_symlink(target, path, error); + if (error) { + return std::unexpected{ + filesystem_error("create symlink", path, error)}; + } + return {}; + } + + [[nodiscard]] + Void::Result::Result> + read_activation_journal(const std::filesystem::path& root) + { + const auto path = root / "activation.json"; + std::error_code error; + const auto status = std::filesystem::symlink_status(path, error); + if (error == std::errc::no_such_file_or_directory || + status.type() == std::filesystem::file_type::not_found) { + return std::optional{}; + } + if (error || std::filesystem::is_symlink(status) || + !std::filesystem::is_regular_file(status)) { + return Void::Result::fail( + "VersionStore: activation journal must be a regular file"); + } + const auto size = std::filesystem::file_size(path, error); + if (error || size > maximumActivationJournalSize) { + return Void::Result::fail( + "VersionStore: activation journal exceeds its size limit"); + } + auto data = read_file(path); + if (!data) { + return std::unexpected{data.error()}; + } + return std::optional{std::move(*data)}; + } + + [[nodiscard]] Void::Result::Result + require_published_real_directory(const std::filesystem::path& root, + std::string_view versionName) + { + const auto path = root / "versions" / std::string{versionName}; + std::error_code error; + const auto status = std::filesystem::symlink_status(path, error); + if (error || std::filesystem::is_symlink(status) || + !std::filesystem::is_directory(status)) { + return Void::Result::fail( + std::format("VersionStore: version '{}' is not a real " + "published directory", + versionName)); + } + return {}; + } +#endif + + [[nodiscard]] Void::Result::Result> + published_versions(const std::filesystem::path& versionsRoot) + { + std::vector versions; +#ifndef _WIN32 + auto directory = open_real_directory(versionsRoot); + if (!directory) { + return std::unexpected{directory.error()}; + } + auto entries = directory_entries(directory->get(), versionsRoot); + if (!entries) { + return std::unexpected{entries.error()}; + } + for (const auto& name : *entries) { + struct stat status{}; + if (::fstatat(directory->get(), name.c_str(), &status, + AT_SYMLINK_NOFOLLOW) != 0 || + !S_ISDIR(status.st_mode)) { + continue; + } + auto version = Semver::parse_strict(name); + if (version && version->to_string() == name) { + versions.push_back(std::move(*version)); + } + } +#else + std::error_code error; + for (std::filesystem::directory_iterator + iterator{versionsRoot, error}, + end; + !error && iterator != end; + iterator.increment(error)) { + const auto status = iterator->symlink_status(error); + if (error || std::filesystem::is_symlink(status) || + !std::filesystem::is_directory(status)) { + error.clear(); + continue; + } + const auto name = iterator->path().filename().string(); + auto version = Semver::parse_strict(name); + if (version && version->to_string() == name) { + versions.push_back(std::move(*version)); + } + } + if (error) { + return std::unexpected{filesystem_error( + "enumerate published versions", versionsRoot, error)}; + } +#endif + return versions; + } + + [[nodiscard]] Void::Result::Result + quarantine_and_remove(const std::filesystem::path& versionsRoot, + std::string_view versionName) + { + static std::atomic counter{0}; + const auto quarantineName = + std::format(".prune.{}.{}", versionName, + counter.fetch_add(1, std::memory_order_relaxed)); +#ifndef _WIN32 + auto directory = open_real_directory(versionsRoot); + if (!directory) { + return std::unexpected{directory.error()}; + } + const std::string sourceName{versionName}; + if (::renameat(directory->get(), sourceName.c_str(), + directory->get(), quarantineName.c_str()) != 0) { + return Void::Result::fail( + std::format("VersionStore: quarantine version '{}': {}", + versionName, std::strerror(errno))); + } + if (auto removed = + remove_entry_no_follow(directory->get(), quarantineName, + versionsRoot / quarantineName); + !removed) { + return removed; + } +#else + const auto source = versionsRoot / versionName; + const auto quarantine = versionsRoot / quarantineName; + std::error_code error; + const auto status = std::filesystem::symlink_status(source, error); + if (error || std::filesystem::is_symlink(status) || + !std::filesystem::is_directory(status)) { + return Void::Result::fail(std::format( + "VersionStore: version '{}' changed while pruning", + versionName)); + } + std::filesystem::rename(source, quarantine, error); + if (error) { + return std::unexpected{ + filesystem_error("quarantine version", source, error)}; + } + std::filesystem::remove_all(quarantine, error); + if (error) { + return std::unexpected{filesystem_error( + "remove quarantined version", quarantine, error)}; + } +#endif + (void)sync_directory(versionsRoot); + return {}; + } + + [[nodiscard]] Void::Result::Result + cleanup_pruning_entries(const std::filesystem::path& versionsRoot) + { +#ifndef _WIN32 + auto directory = open_real_directory(versionsRoot); + if (!directory) { + return std::unexpected{directory.error()}; + } + auto entries = directory_entries(directory->get(), versionsRoot); + if (!entries) { + return std::unexpected{entries.error()}; + } + for (const auto& name : *entries) { + if (!name.starts_with(".prune.")) { + continue; + } + if (auto removed = remove_entry_no_follow( + directory->get(), name, versionsRoot / name); + !removed) { + return removed; + } + } +#else + std::error_code error; + for (std::filesystem::directory_iterator + iterator{versionsRoot, error}, + end; + !error && iterator != end; + iterator.increment(error)) { + if (!iterator->path().filename().string().starts_with( + ".prune.")) { + continue; + } + const auto status = iterator->symlink_status(error); + if (error) { + break; + } + if (std::filesystem::is_symlink(status)) { + std::filesystem::remove(iterator->path(), error); + } else { + std::filesystem::remove_all(iterator->path(), error); + } + if (error) { + break; + } + } + if (error) { + return std::unexpected{filesystem_error( + "clean pruning quarantine", versionsRoot, error)}; + } +#endif + (void)sync_directory(versionsRoot); + return {}; + } + + enum class HealthState : std::uint8_t { + published, + healthy, + failed, + retired, + }; + + struct HealthHistory { + std::map> states; + std::vector committedOrder; + std::map> + lastHealthyGeneration; + std::uint64_t generation{0}; + }; + + constexpr std::uintmax_t maximumHealthHistorySize = 1024 * 1024; + constexpr std::uintmax_t healthHistoryCompactionThreshold = + (maximumHealthHistorySize * 3) / 4; + + [[nodiscard]] Void::Result::Result> + read_health_log(const std::filesystem::path& path) + { +#ifndef _WIN32 + FileDescriptor descriptor{::open( + path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)}; + if (descriptor.get() < 0) { + if (errno == ENOENT) { + return std::optional{}; + } + return Void::Result::fail( + std::format("VersionStore: open health history '{}': {}", + path.string(), std::strerror(errno))); + } + struct stat status{}; + if (::fstat(descriptor.get(), &status) != 0) { + return Void::Result::fail( + std::format("VersionStore: inspect health history '{}': {}", + path.string(), std::strerror(errno))); + } + if (!S_ISREG(status.st_mode) || status.st_nlink != 1 || + status.st_size < 0 || + static_cast(status.st_size) > + maximumHealthHistorySize) { + return Void::Result::fail("VersionStore: health history must " + "be a bounded regular file"); + } + std::string data(static_cast(status.st_size), '\0'); + std::size_t read = 0; + while (read < data.size()) { + const auto count = ::read(descriptor.get(), data.data() + read, + data.size() - read); + if (count < 0 && errno == EINTR) { + continue; + } + if (count <= 0) { + return Void::Result::fail(std::format( + "VersionStore: read health history '{}': {}", + path.string(), + count == 0 ? "unexpected end of file" + : std::strerror(errno))); + } + read += static_cast(count); + } + return std::optional{std::move(data)}; +#else + std::error_code error; + const auto status = std::filesystem::symlink_status(path, error); + if (error == std::errc::no_such_file_or_directory || + status.type() == std::filesystem::file_type::not_found) { + return std::optional{}; + } + if (error || std::filesystem::is_symlink(status) || + !std::filesystem::is_regular_file(status)) { + return Void::Result::fail( + "VersionStore: health history must be a regular file"); + } + const auto size = std::filesystem::file_size(path, error); + if (error || size > maximumHealthHistorySize) { + return Void::Result::fail( + "VersionStore: health history exceeds its size limit"); + } + auto data = read_file(path); + if (!data) { + return std::unexpected{data.error()}; + } + return std::optional{std::move(*data)}; +#endif + } + + [[nodiscard]] Void::Result::Result + read_health_history(const std::filesystem::path& root) + { + auto data = read_health_log(root / "health.log"); + if (!data) { + return std::unexpected{data.error()}; + } + HealthHistory history; + if (!*data) { + return history; + } + + std::size_t offset = 0; + while (offset < (*data)->size()) { + const auto end = (*data)->find('\n', offset); + if (end == std::string::npos) { + return Void::Result::fail( + "VersionStore: health history has a partial record"); + } + const std::string_view line{(*data)->data() + offset, + end - offset}; + offset = end + 1; + if (line.size() < 3 || line[1] != ' ') { + return Void::Result::fail( + "VersionStore: health history record is invalid"); + } + const auto versionText = line.substr(2); + auto version = Semver::parse_strict(versionText); + if (!version || version->to_string() != versionText) { + return Void::Result::fail( + "VersionStore: health history version is invalid"); + } + const auto name = version->to_string(); + ++history.generation; + switch (line.front()) { + case 'P': + history.states[name] = HealthState::published; + std::erase(history.committedOrder, name); + break; + case 'H': + history.states[name] = HealthState::healthy; + std::erase(history.committedOrder, name); + history.committedOrder.push_back(name); + history.lastHealthyGeneration[name] = + history.generation; + break; + case 'F': + if (history.states[name] != HealthState::healthy) { + history.states[name] = HealthState::failed; + } + break; + case 'D': + history.states[name] = HealthState::retired; + std::erase(history.committedOrder, name); + break; + default: + return Void::Result::fail( + "VersionStore: health history event is invalid"); + } + } + return history; + } + + [[nodiscard]] Void::Result::Result + compacted_health_snapshot(const std::filesystem::path& root, + const HealthHistory& history) + { + auto published = published_versions(root / "versions"); + if (!published) { + return std::unexpected{published.error()}; + } + std::sort(published->begin(), published->end()); + std::set> publishedNames; + for (const auto& version : *published) { + publishedNames.insert(version.to_string()); + } + + std::string snapshot; + std::set> emittedHealthy; + for (const auto& name : history.committedOrder) { + const auto state = history.states.find(name); + if (!publishedNames.contains(name) || + state == history.states.end() || + state->second != HealthState::healthy) { + continue; + } + snapshot += std::format("H {}\n", name); + emittedHealthy.insert(name); + } + for (const auto& version : *published) { + const auto name = version.to_string(); + const auto state = history.states.find(name); + if (state == history.states.end()) { + continue; + } + char event = '\0'; + switch (state->second) { + case HealthState::published: + event = 'P'; + break; + case HealthState::healthy: + if (!emittedHealthy.contains(name)) { + event = 'H'; + } + break; + case HealthState::failed: + event = 'F'; + break; + case HealthState::retired: + event = 'D'; + break; + } + if (event != '\0') { + snapshot += std::format("{} {}\n", event, name); + } + } + if (snapshot.size() > maximumHealthHistorySize) { + return Void::Result::fail("VersionStore: compacted health " + "history exceeds its size limit"); + } + return snapshot; + } + + [[nodiscard]] Void::Result::Result + compact_health_history_if_needed(const std::filesystem::path& root) + { + auto data = read_health_log(root / "health.log"); + if (!data) { + return std::unexpected{data.error()}; + } + if (!*data || (*data)->size() <= healthHistoryCompactionThreshold) { + return {}; + } + auto pending = read_activation_journal(root); + if (!pending) { + return std::unexpected{pending.error()}; + } + if (*pending) { + return {}; + } + auto history = read_health_history(root); + if (!history) { + return std::unexpected{history.error()}; + } + auto snapshot = compacted_health_snapshot(root, *history); + if (!snapshot) { + return std::unexpected{snapshot.error()}; + } + return durable_write(root / "health.log", *snapshot, true); + } + + [[nodiscard]] Void::Result::Result + append_health_event(const std::filesystem::path& root, char event, + std::string_view versionName) + { + if (event != 'P' && event != 'H' && event != 'F' && event != 'D') { + return Void::Result::fail( + "VersionStore: invalid health history event"); + } + const auto parsed = Semver::parse_strict(versionName); + if (!parsed || parsed->to_string() != versionName) { + return Void::Result::fail( + "VersionStore: invalid health history version"); + } + if (auto compacted = compact_health_history_if_needed(root); + !compacted) { + return compacted; + } + auto data = read_health_log(root / "health.log"); + if (!data) { + return std::unexpected{data.error()}; + } + const auto line = std::format("{} {}\n", event, versionName); + std::string snapshot = *data ? std::move(**data) : std::string{}; + if (snapshot.size() + line.size() > maximumHealthHistorySize) { + return Void::Result::fail( + "VersionStore: health history is not appendable"); + } + snapshot += line; + return durable_write(root / "health.log", snapshot, true); + } + + [[nodiscard]] Void::Result::Result + mark_healthy(const std::filesystem::path& root, + const Semver::Version& version) + { + auto history = read_health_history(root); + if (!history) { + return std::unexpected{history.error()}; + } + const auto name = version.to_string(); + if (const auto found = history->states.find(name); + found != history->states.end() && + found->second == HealthState::healthy) { + return {}; + } + return append_health_event(root, 'H', name); + } + + [[nodiscard]] Void::Result::Result + activation_commit_recorded(const std::filesystem::path& root, + const PendingActivation& pending) + { + // A snapshot rename that was visible after an earlier + // directory-fsync failure is not yet a durable marker. Successfully + // syncing the store directory here makes the currently visible + // snapshot durable before it is allowed to decide the activation. + if (auto synced = sync_directory(root); !synced) { + return std::unexpected{synced.error()}; + } + auto history = read_health_history(root); + if (!history) { + return std::unexpected{history.error()}; + } + const auto found = history->lastHealthyGeneration.find( + pending.candidateVersion.to_string()); + return found != history->lastHealthyGeneration.end() && + found->second > pending.healthGeneration; + } + + void mark_failed_if_unhealthy(const std::filesystem::path& root, + const Semver::Version& version) + { + auto history = read_health_history(root); + if (!history) { + return; + } + const auto name = version.to_string(); + if (const auto found = history->states.find(name); + found != history->states.end() && + found->second == HealthState::healthy) { + return; + } + (void)append_health_event(root, 'F', name); + } + + /// Remove the activation journal at the logical transition commit + /// point. Once unlink succeeds (or the journal is already absent), + /// callers must observe the operation as complete. Returning a later + /// directory-fsync error would invite an opposite transition even + /// though its compensation record no longer exists. A best-effort fsync + /// still narrows the crash window without making the live result + /// ambiguous. + [[nodiscard]] Void::Result::Result + finish_activation_transition(const std::filesystem::path& root) + { + const auto journal = root / "activation.json"; + std::error_code error; + (void)std::filesystem::remove(journal, error); + if (error) { + return std::unexpected{filesystem_error( + "remove activation journal", journal, error)}; + } + (void)sync_directory(root); + return {}; + } + + [[nodiscard]] Void::Result::Result + version_name(const Semver::Version& version) + { + const auto name = version.to_string(); + const auto parsed = Semver::parse_strict(name); + if (!parsed || parsed->to_string() != name) { + return Void::Result::fail( + "VersionStore: invalid semantic version"); + } + return name; + } + + } // namespace + + VersionStore::VersionStore(std::filesystem::path root) + : m_root(std::move(root)) + { + } + + Void::Result::Result VersionStore::initialize() + { + if (auto created = ensure_real_directory(m_root); !created) { + return created; + } + if (auto created = ensure_real_directory(m_root / "versions"); + !created) { + return created; + } + if (auto created = ensure_real_directory(m_root / "staging"); + !created) { + return created; + } + auto lock = FileLock::acquire(m_root / ".update.lock"); + if (!lock) { + return std::unexpected{lock.error()}; + } + return sync_directory(m_root); + } + + Void::Result::Result + VersionStore::prepare(const Semver::Version& version) + { + if (auto initialized = initialize(); !initialized) { + return std::unexpected{initialized.error()}; + } + auto name = version_name(version); + if (!name) { + return std::unexpected{name.error()}; + } + auto lock = FileLock::acquire(m_root / ".update.lock"); + if (!lock) { + return std::unexpected{lock.error()}; + } + static std::atomic counter{0}; + for (int attempt = 0; attempt < 32; ++attempt) { + const auto nonce = + static_cast(std::chrono::steady_clock::now() + .time_since_epoch() + .count()) ^ + counter.fetch_add(1, std::memory_order_relaxed); + const auto candidate = + m_root / "staging" / + std::format("{}.stage.{:016x}", *name, nonce); + std::error_code error; + if (std::filesystem::create_directory(candidate, error)) { + if (auto synced = sync_directory(m_root / "staging"); !synced) { + return std::unexpected{synced.error()}; + } + return candidate; + } + if (error && error != std::errc::file_exists) { + return std::unexpected{filesystem_error( + "create staging directory", candidate, error)}; + } + } + return Void::Result::fail( + "VersionStore: could not allocate a staging directory"); + } + + Void::Result::Result + VersionStore::publish(const Semver::Version& version, + const std::filesystem::path& stagingDirectory) + { + auto name = version_name(version); + if (!name) { + return std::unexpected{name.error()}; + } + for (const auto& path : + {m_root, m_root / "staging", m_root / "versions"}) { + if (auto checked = require_real_directory(path); !checked) { + return checked; + } + } + auto lock = FileLock::acquire(m_root / ".update.lock"); + if (!lock) { + return std::unexpected{lock.error()}; + } + std::error_code error; + const auto stagingStatus = + std::filesystem::symlink_status(stagingDirectory, error); + if (error || std::filesystem::is_symlink(stagingStatus) || + !std::filesystem::is_directory(stagingStatus)) { + return Void::Result::fail( + "VersionStore: staging path must be a real directory"); + } + const auto canonicalStaging = + std::filesystem::canonical(stagingDirectory, error); + if (error) { + return std::unexpected{filesystem_error("resolve staging directory", + stagingDirectory, error)}; + } + const auto canonicalStagingRoot = + std::filesystem::canonical(m_root / "staging", error); + if (error || canonicalStaging.parent_path() != canonicalStagingRoot) { + return Void::Result::fail( + "VersionStore: staging directory must be an immediate child of " + "the store staging directory"); + } + const auto destination = versionPath(version); + const bool destinationExists = + std::filesystem::exists(destination, error); + if (error) { + return std::unexpected{filesystem_error("inspect published version", + destination, error)}; + } + if (destinationExists) { + return Void::Result::fail(std::format( + "VersionStore: version '{}' is already published", *name)); + } + if (auto recorded = append_health_event(m_root, 'P', *name); + !recorded) { + return recorded; + } + std::filesystem::rename(canonicalStaging, destination, error); + if (error) { + return std::unexpected{ + filesystem_error("publish version", destination, error)}; + } + return sync_directory(m_root / "versions"); + } + + Void::Result::Result + VersionStore::activate(const Semver::Version& version) + { + auto name = version_name(version); + if (!name) { + return std::unexpected{name.error()}; + } + for (const auto& path : {m_root, m_root / "versions"}) { + if (auto checked = require_real_directory(path); !checked) { + return checked; + } + } + auto lock = FileLock::acquire(m_root / ".update.lock"); + if (!lock) { + return std::unexpected{lock.error()}; + } + if (auto checked = require_published_real_directory(m_root, *name); + !checked) { + return checked; + } + auto existingActivation = pendingActivation(); + if (!existingActivation) { + return std::unexpected{existingActivation.error()}; + } + if (*existingActivation) { + return Void::Result::fail( + "VersionStore: another activation is pending"); + } + if (auto compacted = compact_health_history_if_needed(m_root); + !compacted) { + return compacted; + } + auto previous = currentVersion(); + if (!previous) { + return std::unexpected{previous.error()}; + } + auto health = read_health_history(m_root); + if (!health) { + return std::unexpected{health.error()}; + } + std::string previousJson = "null"; + if (*previous) { + previousJson = std::format("\"{}\"", (*previous)->to_string()); + } + const auto journal = + std::format("{{\"schemaVersion\":1,\"previousVersion\":{}," + "\"candidateVersion\":\"{}\"," + "\"healthGeneration\":\"{}\"}}", + previousJson, *name, health->generation); + if (auto written = durable_write(m_root / "activation.json", journal); + !written) { + return written; + } + return atomic_link(m_root / "current", + std::filesystem::path{"versions"} / *name); + } + + Void::Result::Result VersionStore::commit() + { + auto lock = FileLock::acquire(m_root / ".update.lock"); + if (!lock) { + return std::unexpected{lock.error()}; + } + auto pending = pendingActivation(); + if (!pending) { + return std::unexpected{pending.error()}; + } + if (!*pending) { + auto current = currentVersion(); + if (!current) { + return std::unexpected{current.error()}; + } + if (*current) { + return mark_healthy(m_root, **current); + } + return {}; + } + auto current = currentVersion(); + if (!current) { + return std::unexpected{current.error()}; + } + if (!*current || **current != (*pending)->candidateVersion) { + return Void::Result::fail("VersionStore: active version does not " + "match pending candidate"); + } + auto alreadyCommitted = activation_commit_recorded(m_root, **pending); + if (!alreadyCommitted) { + return std::unexpected{alreadyCommitted.error()}; + } + if (*alreadyCommitted) { + (void)finish_activation_transition(m_root); + return {}; + } + const auto candidateName = (*pending)->candidateVersion.to_string(); + if (auto recorded = append_health_event(m_root, 'H', candidateName); + !recorded) { + // A write or fsync may fail after the complete marker became + // visible. Re-read it before declaring the activation reversible. + auto visible = activation_commit_recorded(m_root, **pending); + if (!visible || !*visible) { + return std::unexpected{recorded.error()}; + } + } + // The healthy event above is the durable commit point. Journal cleanup + // can be retried idempotently and cannot turn the operation back into a + // rollback-safe failure. + (void)finish_activation_transition(m_root); + return {}; + } + + Void::Result::Result VersionStore::rollback() + { + auto lock = FileLock::acquire(m_root / ".update.lock"); + if (!lock) { + return std::unexpected{lock.error()}; + } + auto pending = pendingActivation(); + if (!pending) { + return std::unexpected{pending.error()}; + } + if (!*pending) { + return {}; + } + auto committed = activation_commit_recorded(m_root, **pending); + if (!committed) { + return std::unexpected{committed.error()}; + } + if (*committed) { + auto current = currentVersion(); + if (!current) { + return std::unexpected{current.error()}; + } + if (!*current || **current != (*pending)->candidateVersion) { + return Void::Result::fail("VersionStore: committed activation " + "does not match current"); + } + (void)finish_activation_transition(m_root); + return {}; + } + if ((*pending)->previousVersion) { + const auto previousName = (*pending)->previousVersion->to_string(); + if (auto checked = + require_published_real_directory(m_root, previousName); + !checked) { + return checked; + } + if (auto linked = atomic_link(m_root / "current", + std::filesystem::path{"versions"} / + previousName); + !linked) { + return linked; + } + } else { + std::error_code error; + std::filesystem::remove(m_root / "current", error); + if (error) { + return std::unexpected{filesystem_error( + "remove current link", m_root / "current", error)}; + } + if (auto synced = sync_directory(m_root); !synced) { + return synced; + } + } + if (auto transitioned = finish_activation_transition(m_root); + !transitioned) { + return transitioned; + } + mark_failed_if_unhealthy(m_root, (*pending)->candidateVersion); + return {}; + } + + Void::Result::Result VersionStore::reconcile() { return rollback(); } + + Void::Result::Result + VersionStore::recordHealthy(const Semver::Version& version) + { + auto name = version_name(version); + if (!name) { + return std::unexpected{name.error()}; + } + for (const auto& path : {m_root, m_root / "versions"}) { + if (auto checked = require_real_directory(path); !checked) { + return checked; + } + } + auto lock = FileLock::acquire(m_root / ".update.lock"); + if (!lock) { + return std::unexpected{lock.error()}; + } + auto pending = pendingActivation(); + if (!pending) { + return std::unexpected{pending.error()}; + } + if (*pending) { + return Void::Result::fail("VersionStore: recordHealthy cannot " + "commit an internal activation"); + } + if (auto checked = require_published_real_directory(m_root, *name); + !checked) { + return checked; + } + return append_health_event(m_root, 'H', *name); + } + + Void::Result::Result + VersionStore::recordFailed(const Semver::Version& version) + { + auto name = version_name(version); + if (!name) { + return std::unexpected{name.error()}; + } + for (const auto& path : {m_root, m_root / "versions"}) { + if (auto checked = require_real_directory(path); !checked) { + return checked; + } + } + auto lock = FileLock::acquire(m_root / ".update.lock"); + if (!lock) { + return std::unexpected{lock.error()}; + } + if (auto checked = require_published_real_directory(m_root, *name); + !checked) { + return checked; + } + auto history = read_health_history(m_root); + if (!history) { + return std::unexpected{history.error()}; + } + if (const auto found = history->states.find(*name); + found != history->states.end() && + found->second == HealthState::healthy) { + return {}; + } + return append_health_event(m_root, 'F', *name); + } + + Void::Result::Result> + VersionStore::healthyPublishedVersions() const + { + for (const auto& path : {m_root, m_root / "versions"}) { + if (auto checked = require_real_directory(path); !checked) { + return std::unexpected{checked.error()}; + } + } + auto lock = FileLock::acquireShared(m_root / ".update.lock"); + if (!lock) { + return std::unexpected{lock.error()}; + } + auto history = read_health_history(m_root); + if (!history) { + return std::unexpected{history.error()}; + } + auto published = published_versions(m_root / "versions"); + if (!published) { + return std::unexpected{published.error()}; + } + + std::set> publishedNames; + for (const auto& version : *published) { + publishedNames.insert(version.to_string()); + } + std::vector healthy; + for (auto iterator = history->committedOrder.rbegin(); + iterator != history->committedOrder.rend(); + ++iterator) { + const auto state = history->states.find(*iterator); + if (!publishedNames.contains(*iterator) || + state == history->states.end() || + state->second != HealthState::healthy) { + continue; + } + auto version = Semver::parse_strict(*iterator); + if (!version) { + return Void::Result::fail( + "VersionStore: healthy history version is invalid"); + } + healthy.push_back(std::move(*version)); + } + return healthy; + } + + Void::Result::Result> + VersionStore::prune(std::size_t retainedPreviousVersions) + { + for (const auto& path : {m_root, m_root / "versions"}) { + if (auto checked = require_real_directory(path); !checked) { + return std::unexpected{checked.error()}; + } + } + auto lock = FileLock::acquire(m_root / ".update.lock"); + if (!lock) { + return std::unexpected{lock.error()}; + } + if (auto cleaned = cleanup_pruning_entries(m_root / "versions"); + !cleaned) { + return std::unexpected{cleaned.error()}; + } + + auto current = currentVersion(); + if (!current) { + return std::unexpected{current.error()}; + } + auto pending = pendingActivation(); + if (!pending) { + return std::unexpected{pending.error()}; + } + auto history = read_health_history(m_root); + if (!history) { + return std::unexpected{history.error()}; + } + auto published = published_versions(m_root / "versions"); + if (!published) { + return std::unexpected{published.error()}; + } + + std::sort(published->begin(), published->end(), + std::greater{}); + std::set> publishedNames; + for (const auto& version : *published) { + publishedNames.insert(version.to_string()); + } + std::set> retained; + std::optional currentName; + if (*current) { + currentName = (**current).to_string(); + retained.insert(*currentName); + } + if (*pending) { + retained.insert((*pending)->candidateVersion.to_string()); + if ((*pending)->previousVersion) { + retained.insert((*pending)->previousVersion->to_string()); + } + } + + std::size_t retainedPrevious = 0; + for (auto iterator = history->committedOrder.rbegin(); + iterator != history->committedOrder.rend() && + retainedPrevious < retainedPreviousVersions; + ++iterator) { + const auto state = history->states.find(*iterator); + if (publishedNames.contains(*iterator) && + state != history->states.end() && + state->second == HealthState::healthy && + (!currentName || *iterator != *currentName) && + !retained.contains(*iterator)) { + retained.insert(*iterator); + ++retainedPrevious; + } + } + + std::vector removed; + for (const auto& version : *published) { + const auto name = version.to_string(); + if (retained.contains(name)) { + continue; + } + const auto state = history->states.find(name); + if (state == history->states.end() || + (state->second != HealthState::healthy && + state->second != HealthState::failed && + state->second != HealthState::retired)) { + continue; + } + if (state->second != HealthState::retired) { + if (auto recorded = append_health_event(m_root, 'D', name); + !recorded) { + return std::unexpected{recorded.error()}; + } + } + if (auto pruned = quarantine_and_remove(m_root / "versions", name); + !pruned) { + return std::unexpected{pruned.error()}; + } + removed.push_back(version); + } + return removed; + } + + Void::Result::Result> + VersionStore::currentVersion() const + { + std::error_code error; + const auto status = + std::filesystem::symlink_status(m_root / "current", error); + if (error == std::errc::no_such_file_or_directory || + status.type() == std::filesystem::file_type::not_found) { + return std::optional{}; + } + if (error || !std::filesystem::is_symlink(status)) { + return Void::Result::fail( + "VersionStore: current is not a valid symlink"); + } + const auto target = + std::filesystem::read_symlink(m_root / "current", error); + if (error || target.parent_path() != "versions") { + return Void::Result::fail( + "VersionStore: current symlink target is invalid"); + } + auto version = Semver::parse_strict(target.filename().string()); + if (!version) { + return Void::Result::fail( + "VersionStore: current target is not SemVer"); + } + if (auto checked = + require_published_real_directory(m_root, version->to_string()); + !checked) { + return std::unexpected{checked.error()}; + } + return std::optional{std::move(*version)}; + } + + Void::Result::Result> + VersionStore::pendingActivation() const + { + auto data = read_activation_journal(m_root); + if (!data) { + return std::unexpected{data.error()}; + } + if (!*data) { + return std::optional{}; + } + auto document = Json::parse(**data); + if (!document || !document->is_object() || + document->get_num("schemaVersion") != 1) { + return Void::Result::fail( + "VersionStore: activation journal is invalid"); + } + const auto* candidateValue = document->find("candidateVersion"); + if (!candidateValue || !candidateValue->is_string()) { + return Void::Result::fail( + "VersionStore: activation candidate is missing"); + } + auto candidate = Semver::parse_strict(candidateValue->as_string()); + if (!candidate) { + return Void::Result::fail( + "VersionStore: activation candidate is invalid"); + } + PendingActivation pending{.candidateVersion = std::move(*candidate)}; + const auto* generationValue = document->find("healthGeneration"); + if (generationValue == nullptr || !generationValue->is_string()) { + return Void::Result::fail( + "VersionStore: activation health generation is required"); + } + const auto generationText = generationValue->as_string(); + std::uint64_t generation = 0; + const auto [end, parseError] = std::from_chars( + generationText.data(), + generationText.data() + generationText.size(), generation); + if (parseError != std::errc{} || + end != generationText.data() + generationText.size()) { + return Void::Result::fail( + "VersionStore: activation health generation is invalid"); + } + pending.healthGeneration = generation; + if (const auto* previousValue = document->find("previousVersion"); + previousValue && !previousValue->is_null()) { + if (!previousValue->is_string()) { + return Void::Result::fail( + "VersionStore: previous version is invalid"); + } + auto previous = Semver::parse_strict(previousValue->as_string()); + if (!previous) { + return Void::Result::fail( + "VersionStore: previous version is invalid"); + } + pending.previousVersion = std::move(*previous); + } + return std::optional{std::move(pending)}; + } + + const std::filesystem::path& VersionStore::root() const noexcept + { + return m_root; + } + + std::filesystem::path + VersionStore::versionPath(const Semver::Version& version) const + { + return m_root / "versions" / version.to_string(); + } +} // namespace Void::Update diff --git a/src/Update/module.cmake b/src/Update/module.cmake new file mode 100644 index 0000000..0fac0c3 --- /dev/null +++ b/src/Update/module.cmake @@ -0,0 +1,3 @@ +void_add_module(Update + INTERNAL_DEPS Crypto Data Functional System Text +) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 8b28b3d..f3b86a4 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -81,6 +81,19 @@ if(_all_generated) endforeach() 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=$ + -P ${CMAKE_CURRENT_SOURCE_DIR}/package/InstalledComponents.cmake + ) + set_tests_properties(VoidInstalledComponentConsumers PROPERTIES + DEPENDS VoidTests) endif() # ── Test-support libraries ──────────────────────────────────────────────────── diff --git a/tests/package/Audited/CMakeLists.txt b/tests/package/Audited/CMakeLists.txt new file mode 100644 index 0000000..420bece --- /dev/null +++ b/tests/package/Audited/CMakeLists.txt @@ -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) diff --git a/tests/package/Audited/main.cpp b/tests/package/Audited/main.cpp new file mode 100644 index 0000000..9768e47 --- /dev/null +++ b/tests/package/Audited/main.cpp @@ -0,0 +1,28 @@ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +int main() +{ + const std::array bytes{std::byte{0x01}, std::byte{0x02}}; + Void::Binary::Reader reader{bytes}; + const auto value = reader.read(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; +} diff --git a/tests/package/Binary/CMakeLists.txt b/tests/package/Binary/CMakeLists.txt new file mode 100644 index 0000000..ab8feb8 --- /dev/null +++ b/tests/package/Binary/CMakeLists.txt @@ -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) diff --git a/tests/package/Binary/main.cpp b/tests/package/Binary/main.cpp new file mode 100644 index 0000000..b862cba --- /dev/null +++ b/tests/package/Binary/main.cpp @@ -0,0 +1,14 @@ +#include + +#include +#include +#include +#include + +int main() +{ + const std::array bytes{std::byte{0x01}, std::byte{0x02}}; + Void::Binary::Reader reader{bytes}; + const auto value = reader.read(std::endian::big); + return value && *value == 0x0102 ? 0 : 1; +} diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake new file mode 100644 index 0000000..a42b8bd --- /dev/null +++ b/tests/package/InstalledComponents.cmake @@ -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) diff --git a/tests/standalone/Archive/Archive.cpp b/tests/standalone/Archive/Archive.cpp new file mode 100644 index 0000000..bbfd108 --- /dev/null +++ b/tests/standalone/Archive/Archive.cpp @@ -0,0 +1,253 @@ +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +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 + entries) + { + using Writer = std::unique_ptr; + using Entry = + std::unique_ptr; + Writer writer{archive_write_new(), &archive_write_free}; + Void::Testing::require(static_cast(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(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(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")); +} diff --git a/tests/standalone/Binary/Reader.cpp b/tests/standalone/Binary/Reader.cpp new file mode 100644 index 0000000..c18d9fc --- /dev/null +++ b/tests/standalone/Binary/Reader.cpp @@ -0,0 +1,31 @@ +#include +#include +#include + +#include + +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::endian::big); + Void::Testing::require(value.has_value()); + Void::Testing::expect_eq(*value, static_cast(0x1234)); + Void::Testing::expect_eq(reader.position(), static_cast(2)); + auto overflow = reader.read(std::endian::big); + Void::Testing::expect(!overflow.has_value()); + Void::Testing::expect_eq(reader.position(), static_cast(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(1)); +} diff --git a/tests/standalone/Crypto/Crypto.cpp b/tests/standalone/Crypto/Crypto.cpp new file mode 100644 index 0000000..7e0b353 --- /dev/null +++ b/tests/standalone/Crypto/Crypto.cpp @@ -0,0 +1,77 @@ +#include +#include +#include +#include +#include + +#include +#include + +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); +} diff --git a/tests/standalone/Plugin/Manager.cpp b/tests/standalone/Plugin/Manager.cpp index fa7c0c0..6e7c253 100644 --- a/tests/standalone/Plugin/Manager.cpp +++ b/tests/standalone/Plugin/Manager.cpp @@ -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::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::FileSystem::TempDir tmp{"void_mgr"}; diff --git a/tests/standalone/System/SignalWatcher.cpp b/tests/standalone/System/SignalWatcher.cpp new file mode 100644 index 0000000..8168b50 --- /dev/null +++ b/tests/standalone/System/SignalWatcher.cpp @@ -0,0 +1,22 @@ +#include +#include +#include + +#include +#include + +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 +} diff --git a/tests/standalone/Text/Encoding.cpp b/tests/standalone/Text/Encoding.cpp index 2cbc2cc..89f5ba0 100644 --- a/tests/standalone/Text/Encoding.cpp +++ b/tests/standalone/Text/Encoding.cpp @@ -1,240 +1,290 @@ +#include +#include #include #include #include #include -#include -#include -// ── Base64 encode ───────────────────────────────────────────────────────────── +#include +#include +#include +#include + +// ── Base64 encode +// ───────────────────────────────────────────────────────────── 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::expect_eq(Void::Encoding::Base64::encode("Man"), - std::string{"TWFu"}); + Void::Testing::expect_eq(Void::Encoding::Base64::encode("Man"), + std::string{"TWFu"}); } Void::Testing::Test base64_encode_ma() { - Void::Testing::expect_eq(Void::Encoding::Base64::encode("Ma"), - std::string{"TWE="}); + Void::Testing::expect_eq(Void::Encoding::Base64::encode("Ma"), + std::string{"TWE="}); } Void::Testing::Test base64_encode_m() { - Void::Testing::expect_eq(Void::Encoding::Base64::encode("M"), - std::string{"TQ=="}); + Void::Testing::expect_eq(Void::Encoding::Base64::encode("M"), + std::string{"TQ=="}); } Void::Testing::Test base64_encode_hello_world() { - Void::Testing::expect_eq(Void::Encoding::Base64::encode("Hello, World!"), - std::string{"SGVsbG8sIFdvcmxkIQ=="}); + Void::Testing::expect_eq(Void::Encoding::Base64::encode("Hello, World!"), + std::string{"SGVsbG8sIFdvcmxkIQ=="}); } -// ── Base64 decode ───────────────────────────────────────────────────────────── +// ── Base64 decode +// ───────────────────────────────────────────────────────────── Void::Testing::Test base64_decode_empty() { - const auto r = Void::Encoding::Base64::decode(""); - Void::Testing::expect(r.has_value()); - Void::Testing::expect(r->empty()); + const auto r = Void::Encoding::Base64::decode(""); + Void::Testing::expect(r.has_value()); + Void::Testing::expect(r->empty()); } Void::Testing::Test base64_decode_man() { - const auto r = Void::Encoding::Base64::decode("TWFu"); - Void::Testing::expect(r.has_value()); - Void::Testing::expect_eq(*r, std::string{"Man"}); + const auto r = Void::Encoding::Base64::decode("TWFu"); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(*r, std::string{"Man"}); } Void::Testing::Test base64_decode_with_padding() { - const auto r = Void::Encoding::Base64::decode("SGVsbG8sIFdvcmxkIQ=="); - Void::Testing::expect(r.has_value()); - Void::Testing::expect_eq(*r, std::string{"Hello, World!"}); + const auto r = Void::Encoding::Base64::decode("SGVsbG8sIFdvcmxkIQ=="); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(*r, std::string{"Hello, World!"}); } Void::Testing::Test base64_decode_invalid_returns_nullopt() { - const auto r = Void::Encoding::Base64::decode("!!"); - Void::Testing::expect(!r.has_value()); + const auto r = Void::Encoding::Base64::decode("!!"); + 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() { - const std::string original = "The quick brown fox jumps over the lazy dog"; - const auto encoded = Void::Encoding::Base64::encode(original); - const auto decoded = Void::Encoding::Base64::decode(encoded); - Void::Testing::expect(decoded.has_value()); - Void::Testing::expect_eq(*decoded, original); + const std::string original = "The quick brown fox jumps over the lazy dog"; + const auto encoded = Void::Encoding::Base64::encode(original); + const auto decoded = Void::Encoding::Base64::decode(encoded); + Void::Testing::expect(decoded.has_value()); + Void::Testing::expect_eq(*decoded, original); } -// ── Base64 URL ──────────────────────────────────────────────────────────────── +Void::Testing::Test base64_byte_buffer_round_trip() +{ + const std::array original{0x00, 0x7F, 0x80, 0xFE, 0xFF}; + const auto encoded = + Void::Encoding::Base64::encode(std::span{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((*decoded)[i]), + original[i]); + } +} + +// ── Base64 URL +// ──────────────────────────────────────────────────────────────── Void::Testing::Test base64url_no_padding() { - const auto s = Void::Encoding::Base64::encode_url("Man"); - Void::Testing::expect_eq(s, std::string{"TWFu"}); - Void::Testing::expect(s.find('=') == std::string::npos); + const auto s = Void::Encoding::Base64::encode_url("Man"); + Void::Testing::expect_eq(s, std::string{"TWFu"}); + Void::Testing::expect(s.find('=') == std::string::npos); } Void::Testing::Test base64url_no_plus_or_slash() { - // encode something that would produce + or / in standard base64 - const std::string tricky = "\xfb\xff\xfe"; - 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); + // encode something that would produce + or / in standard base64 + const std::string tricky = "\xfb\xff\xfe"; + 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); } // ── Hex encode ─────────────────────────────────────────────────────────────── 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::expect_eq(Void::Encoding::Hex::encode("Hi"), - std::string{"4869"}); + Void::Testing::expect_eq(Void::Encoding::Hex::encode("Hi"), + std::string{"4869"}); } Void::Testing::Test hex_encode_binary() { - const std::string bin{'\x00', '\xff', '\xab'}; - Void::Testing::expect_eq(Void::Encoding::Hex::encode(bin), - std::string{"00ffab"}); + const std::string bin{'\x00', '\xff', '\xab'}; + Void::Testing::expect_eq(Void::Encoding::Hex::encode(bin), + std::string{"00ffab"}); } Void::Testing::Test hex_encode_upper() { - Void::Testing::expect_eq(Void::Encoding::Hex::encode_upper("Hi"), - std::string{"4869"}); + Void::Testing::expect_eq(Void::Encoding::Hex::encode_upper("Hi"), + std::string{"4869"}); } // ── Hex decode ─────────────────────────────────────────────────────────────── Void::Testing::Test hex_decode_empty() { - const auto r = Void::Encoding::Hex::decode(""); - Void::Testing::expect(r.has_value()); - Void::Testing::expect(r->empty()); + const auto r = Void::Encoding::Hex::decode(""); + Void::Testing::expect(r.has_value()); + Void::Testing::expect(r->empty()); } Void::Testing::Test hex_decode_hello() { - const auto r = Void::Encoding::Hex::decode("4869"); - Void::Testing::expect(r.has_value()); - Void::Testing::expect_eq(*r, std::string{"Hi"}); + const auto r = Void::Encoding::Hex::decode("4869"); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(*r, std::string{"Hi"}); } Void::Testing::Test hex_decode_uppercase() { - const auto r = Void::Encoding::Hex::decode("4869"); - Void::Testing::expect(r.has_value()); - Void::Testing::expect_eq(*r, std::string{"Hi"}); + const auto r = Void::Encoding::Hex::decode("4869"); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(*r, std::string{"Hi"}); } 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::expect(!Void::Encoding::Hex::decode("zz").has_value()); + Void::Testing::expect(!Void::Encoding::Hex::decode("zz").has_value()); } Void::Testing::Test hex_round_trip() { - const std::string original = "binary\x00\x01\x02\xff"; - const auto encoded = Void::Encoding::Hex::encode(original); - const auto decoded = Void::Encoding::Hex::decode(encoded); - Void::Testing::expect(decoded.has_value()); - Void::Testing::expect_eq(*decoded, original); + const std::string original = "binary\x00\x01\x02\xff"; + const auto encoded = Void::Encoding::Hex::encode(original); + const auto decoded = Void::Encoding::Hex::decode(encoded); + Void::Testing::expect(decoded.has_value()); + Void::Testing::expect_eq(*decoded, original); } -// ── URL / percent encoding ───────────────────────────────────────────────────── +Void::Testing::Test hex_byte_buffer_round_trip() +{ + const std::array original{0x00, 0x7F, 0x80, 0xFE, 0xFF}; + const auto encoded = + Void::Encoding::Hex::encode(std::span{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((*decoded)[i]), + original[i]); + } +} + +// ── URL / percent encoding +// ───────────────────────────────────────────────────── Void::Testing::Test url_encode_unreserved_passthrough() { - Void::Testing::expect_eq(Void::Encoding::Url::encode("AZaz09-._~"), - std::string{"AZaz09-._~"}); + Void::Testing::expect_eq(Void::Encoding::Url::encode("AZaz09-._~"), + std::string{"AZaz09-._~"}); } Void::Testing::Test url_encode_reserved() { - Void::Testing::expect_eq(Void::Encoding::Url::encode("a b/c?d=e&f"), - std::string{"a%20b%2Fc%3Fd%3De%26f"}); + Void::Testing::expect_eq(Void::Encoding::Url::encode("a b/c?d=e&f"), + std::string{"a%20b%2Fc%3Fd%3De%26f"}); } Void::Testing::Test url_query_encode_space_as_plus() { - Void::Testing::expect_eq(Void::Encoding::Url::query_encode("a b c"), - std::string{"a+b+c"}); + Void::Testing::expect_eq(Void::Encoding::Url::query_encode("a b c"), + std::string{"a+b+c"}); } Void::Testing::Test url_decode_basic() { - const auto r = Void::Encoding::Url::decode("a%20b%2Fc"); - Void::Testing::expect(r.has_value()); - Void::Testing::expect_eq(*r, std::string{"a b/c"}); + const auto r = Void::Encoding::Url::decode("a%20b%2Fc"); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(*r, std::string{"a b/c"}); } Void::Testing::Test url_decode_plus_as_space() { - const auto r = Void::Encoding::Url::decode("a+b", /*plus_as_space=*/true); - Void::Testing::expect(r.has_value()); - Void::Testing::expect_eq(*r, std::string{"a b"}); + const auto r = Void::Encoding::Url::decode("a+b", /*plus_as_space=*/true); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(*r, std::string{"a b"}); } 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%zz").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::Test url_round_trip_utf8() { - const std::string original = "café/naïve?x=1 2"; - const auto enc = Void::Encoding::Url::encode(original); - const auto dec = Void::Encoding::Url::decode(enc); - Void::Testing::expect(dec.has_value()); - Void::Testing::expect_eq(*dec, original); + const std::string original = "café/naïve?x=1 2"; + const auto enc = Void::Encoding::Url::encode(original); + const auto dec = Void::Encoding::Url::decode(enc); + Void::Testing::expect(dec.has_value()); + Void::Testing::expect_eq(*dec, original); } -// ── HTML entity decoding ─────────────────────────────────────────────────────── +// ── HTML entity decoding +// ─────────────────────────────────────────────────────── Void::Testing::Test html_named_entities() { - Void::Testing::expect_eq( - Void::Text::html_unescape("a & b < c > d "e""), - std::string{"a & b < c > d \"e\""}); + Void::Testing::expect_eq( + Void::Text::html_unescape("a & b < c > d "e""), + std::string{"a & b < c > d \"e\""}); } Void::Testing::Test html_numeric_decimal() { - Void::Testing::expect_eq(Void::Text::html_unescape("ABC"), - std::string{"ABC"}); + Void::Testing::expect_eq(Void::Text::html_unescape("ABC"), + std::string{"ABC"}); } Void::Testing::Test html_numeric_hex_utf8() { - // U+1F600 grinning face -> 4-byte UTF-8 - const auto r = Void::Text::html_unescape("😀"); - Void::Testing::expect_eq(r.size(), std::size_t{4}); + // U+1F600 grinning face -> 4-byte UTF-8 + const auto r = Void::Text::html_unescape("😀"); + Void::Testing::expect_eq(r.size(), std::size_t{4}); } Void::Testing::Test html_unknown_left_verbatim() { - Void::Testing::expect_eq(Void::Text::html_unescape("a &bogus; b"), - std::string{"a &bogus; b"}); - Void::Testing::expect_eq(Void::Text::html_unescape("plain & text"), - std::string{"plain & text"}); + Void::Testing::expect_eq(Void::Text::html_unescape("a &bogus; b"), + std::string{"a &bogus; b"}); + Void::Testing::expect_eq(Void::Text::html_unescape("plain & text"), + std::string{"plain & text"}); } diff --git a/tests/standalone/Text/Semver.cpp b/tests/standalone/Text/Semver.cpp index b445d14..c0f4d3c 100644 --- a/tests/standalone/Text/Semver.cpp +++ b/tests/standalone/Text/Semver.cpp @@ -4,158 +4,203 @@ #include -// ── parse ───────────────────────────────────────────────────────────────────── +// ── parse +// ───────────────────────────────────────────────────────────────────── Void::Testing::Test semver_parse_simple() { - const auto v = Void::Semver::parse("1.2.3"); - Void::Testing::expect(v.has_value()); - Void::Testing::expect_eq(v->major, 1u); - Void::Testing::expect_eq(v->minor, 2u); - Void::Testing::expect_eq(v->patch, 3u); + const auto v = Void::Semver::parse("1.2.3"); + Void::Testing::expect(v.has_value()); + Void::Testing::expect_eq(v->major, 1u); + Void::Testing::expect_eq(v->minor, 2u); + Void::Testing::expect_eq(v->patch, 3u); } Void::Testing::Test semver_parse_with_v_prefix() { - const auto v = Void::Semver::parse("v2.0.0"); - Void::Testing::expect(v.has_value()); - Void::Testing::expect_eq(v->major, 2u); + const auto v = Void::Semver::parse("v2.0.0"); + Void::Testing::expect(v.has_value()); + Void::Testing::expect_eq(v->major, 2u); } Void::Testing::Test semver_parse_pre_release() { - const auto v = Void::Semver::parse("1.0.0-alpha.1"); - Void::Testing::expect(v.has_value()); - Void::Testing::expect_eq(v->pre_release, std::string{"alpha.1"}); + const auto v = Void::Semver::parse("1.0.0-alpha.1"); + Void::Testing::expect(v.has_value()); + Void::Testing::expect_eq(v->pre_release, std::string{"alpha.1"}); } Void::Testing::Test semver_parse_build_metadata() { - const auto v = Void::Semver::parse("1.0.0+build.123"); - Void::Testing::expect(v.has_value()); - Void::Testing::expect_eq(v->build, std::string{"build.123"}); + const auto v = Void::Semver::parse("1.0.0+build.123"); + Void::Testing::expect(v.has_value()); + Void::Testing::expect_eq(v->build, std::string{"build.123"}); } Void::Testing::Test semver_parse_full() { - const auto v = Void::Semver::parse("2.3.4-beta.2+20240101"); - Void::Testing::expect(v.has_value()); - Void::Testing::expect_eq(v->major, 2u); - Void::Testing::expect_eq(v->pre_release, std::string{"beta.2"}); - Void::Testing::expect_eq(v->build, std::string{"20240101"}); + const auto v = Void::Semver::parse("2.3.4-beta.2+20240101"); + Void::Testing::expect(v.has_value()); + Void::Testing::expect_eq(v->major, 2u); + Void::Testing::expect_eq(v->pre_release, std::string{"beta.2"}); + Void::Testing::expect_eq(v->build, std::string{"20240101"}); } Void::Testing::Test semver_parse_invalid() { - 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("not-a-version").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::Semver::Version v{1, 2, 3}; - Void::Testing::expect_eq(v.to_string(), std::string{"1.2.3"}); + Void::Semver::Version v{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::Semver::Version v{1, 0, 0}; - v.pre_release = "alpha"; - Void::Testing::expect_eq(v.to_string(), std::string{"1.0.0-alpha"}); + Void::Semver::Version v{1, 0, 0}; + v.pre_release = "alpha"; + Void::Testing::expect_eq(v.to_string(), std::string{"1.0.0-alpha"}); } Void::Testing::Test semver_round_trip() { - const auto v = Void::Semver::parse("3.1.4-rc.1+build1"); - Void::Testing::expect(v.has_value()); - Void::Testing::expect_eq(v->to_string(), std::string{"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_eq(v->to_string(), std::string{"3.1.4-rc.1+build1"}); } // ── comparison ─────────────────────────────────────────────────────────────── Void::Testing::Test semver_compare_major() { - const auto a = *Void::Semver::parse("2.0.0"); - const auto b = *Void::Semver::parse("1.9.9"); - Void::Testing::expect(a > b); + const auto a = *Void::Semver::parse("2.0.0"); + const auto b = *Void::Semver::parse("1.9.9"); + Void::Testing::expect(a > b); } Void::Testing::Test semver_compare_minor() { - const auto a = *Void::Semver::parse("1.2.0"); - const auto b = *Void::Semver::parse("1.1.9"); - Void::Testing::expect(a > b); + const auto a = *Void::Semver::parse("1.2.0"); + const auto b = *Void::Semver::parse("1.1.9"); + Void::Testing::expect(a > b); } Void::Testing::Test semver_compare_patch() { - const auto a = *Void::Semver::parse("1.0.1"); - const auto b = *Void::Semver::parse("1.0.0"); - Void::Testing::expect(a > b); + const auto a = *Void::Semver::parse("1.0.1"); + const auto b = *Void::Semver::parse("1.0.0"); + Void::Testing::expect(a > b); } Void::Testing::Test semver_release_gt_pre_release() { - const auto a = *Void::Semver::parse("1.0.0"); - const auto b = *Void::Semver::parse("1.0.0-alpha"); - Void::Testing::expect(a > b); + const auto a = *Void::Semver::parse("1.0.0"); + const auto b = *Void::Semver::parse("1.0.0-alpha"); + Void::Testing::expect(a > b); } Void::Testing::Test semver_equal() { - const auto a = *Void::Semver::parse("1.2.3"); - const auto b = *Void::Semver::parse("1.2.3"); - Void::Testing::expect(a == b); + const auto a = *Void::Semver::parse("1.2.3"); + const auto b = *Void::Semver::parse("1.2.3"); + 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 ───────────────────────────────────────────────────────────────────── Void::Testing::Test semver_bump_major() { - const auto v = Void::Semver::Version{1, 2, 3}; - const auto b = v.bumped_major(); - Void::Testing::expect_eq(b.major, 2u); - Void::Testing::expect_eq(b.minor, 0u); - Void::Testing::expect_eq(b.patch, 0u); + const auto v = Void::Semver::Version{1, 2, 3}; + const auto b = v.bumped_major(); + Void::Testing::expect_eq(b.major, 2u); + Void::Testing::expect_eq(b.minor, 0u); + Void::Testing::expect_eq(b.patch, 0u); } Void::Testing::Test semver_bump_minor() { - const auto v = Void::Semver::Version{1, 2, 3}; - const auto b = v.bumped_minor(); - Void::Testing::expect_eq(b.minor, 3u); - Void::Testing::expect_eq(b.patch, 0u); + const auto v = Void::Semver::Version{1, 2, 3}; + const auto b = v.bumped_minor(); + Void::Testing::expect_eq(b.minor, 3u); + Void::Testing::expect_eq(b.patch, 0u); } Void::Testing::Test semver_bump_patch() { - const auto v = Void::Semver::Version{1, 2, 3}; - Void::Testing::expect_eq(v.bumped_patch().patch, 4u); + const auto v = Void::Semver::Version{1, 2, 3}; + Void::Testing::expect_eq(v.bumped_patch().patch, 4u); } -// ── compatible_with ─────────────────────────────────────────────────────────── +// ── compatible_with +// ─────────────────────────────────────────────────────────── Void::Testing::Test semver_compatible_same_major() { - const auto a = *Void::Semver::parse("1.3.0"); - const auto req = *Void::Semver::parse("1.2.0"); - Void::Testing::expect(a.compatible_with(req)); + const auto a = *Void::Semver::parse("1.3.0"); + const auto req = *Void::Semver::parse("1.2.0"); + Void::Testing::expect(a.compatible_with(req)); } Void::Testing::Test semver_incompatible_different_major() { - const auto a = *Void::Semver::parse("2.0.0"); - const auto req = *Void::Semver::parse("1.9.9"); - Void::Testing::expect(!a.compatible_with(req)); + const auto a = *Void::Semver::parse("2.0.0"); + const auto req = *Void::Semver::parse("1.9.9"); + Void::Testing::expect(!a.compatible_with(req)); } Void::Testing::Test semver_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::Semver::Version pre{1,0,0}; - pre.pre_release = "alpha"; - Void::Testing::expect(!pre.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::Semver::Version pre{1, 0, 0}; + pre.pre_release = "alpha"; + Void::Testing::expect(!pre.is_stable()); } diff --git a/tests/standalone/Update/Update.cpp b/tests/standalone/Update/Update.cpp new file mode 100644 index 0000000..c8e0b7b --- /dev/null +++ b/tests/standalone/Update/Update.cpp @@ -0,0 +1,830 @@ +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include + +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; + using Context = std::unique_ptr; + Key key{EVP_PKEY_new_raw_private_key( + EVP_PKEY_ED25519, nullptr, + reinterpret_cast(seedText->data()), + seedText->size()), + &EVP_PKEY_free}; + Void::Testing::require(static_cast(key)); + Context context{EVP_MD_CTX_new(), &EVP_MD_CTX_free}; + Void::Testing::require(static_cast(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(signature.data()), &size, + reinterpret_cast(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{healthInput}, + std::istreambuf_iterator{}}; + 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{healthInput}, + std::istreambuf_iterator{}}; + 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{healthInput}, + std::istreambuf_iterator{}}; + 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{healthInput}, + std::istreambuf_iterator{}}; + 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{healthInput}, + std::istreambuf_iterator{}}; + 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 +}