navid/veins / commit

50bb6b26be98

Navid M <navidmomtahen@gmail.com> · 2026-11-28

parents: 5abea8f29f2c

Browse files at this commit · Download source

all: various build reproducibility fixes and security fixes
--- a/.circleci/config.yml+++ b/.circleci/config.yml@@ -38,7 +38,7 @@           name: Install build dependencies           command: |             sudo apt-get update-            sudo apt-get install -y cmake ninja-build g++ libssl-dev zlib1g-dev libzstd-dev zip jq curl+            sudo apt-get install -y cmake ninja-build g++ libssl-dev zip jq curl   build-and-package-linux:     parameters:       arch:@@ -54,7 +54,8 @@             echo "export VERSION=$VERSION" >> "$BASH_ENV"             cmake -S xveins -B build -G Ninja \               -DCMAKE_BUILD_TYPE=Release \-              -DVN_VERSION="$VERSION"+              -DVN_VERSION="$VERSION" \+              -DVN_COMMIT="${CIRCLE_SHA1:0:12}"       - run:           name: Build           command: cmake --build build -j "$(nproc)"@@ -107,21 +108,24 @@           shell: powershell           command: |             choco install cmake ninja -y --no-progress-            if (-not (Test-Path C:\vcpkg\vcpkg.exe)) {-              git clone --depth 1 https://github.com/microsoft/vcpkg.git C:\vcpkg-              C:\vcpkg\bootstrap-vcpkg.bat+            $vcpkgDir = "C:\vcpkg-2026.10.16"+            if (-not (Test-Path "$vcpkgDir\vcpkg.exe")) {+              git clone --depth 1 --branch 2026.10.16 https://github.com/microsoft/vcpkg.git $vcpkgDir+              & "$vcpkgDir\bootstrap-vcpkg.bat"             }-            C:\vcpkg\vcpkg.exe install openssl:x64-windows-static zlib:x64-windows-static zstd:x64-windows-static+            & "$vcpkgDir\vcpkg.exe" install openssl:x64-windows-static       - run:           name: Configure           shell: powershell           command: |             $version = if ($env:CIRCLE_TAG) { $env:CIRCLE_TAG -replace '^v', '' } else { '0.0.0-dev' }+            $commit = if ($env:CIRCLE_SHA1) { $env:CIRCLE_SHA1.Substring(0, 12) } else { '' }             "VERSION=$version" | Out-File -FilePath $env:BASH_ENV -Append -Encoding ascii             cmake -S xveins -B build -G Ninja `               -DCMAKE_BUILD_TYPE=Release `               -DVN_VERSION="$version" `-              -DCMAKE_TOOLCHAIN_FILE=C:/vcpkg/scripts/buildsystems/vcpkg.cmake `+              -DVN_COMMIT="$commit" `+              -DCMAKE_TOOLCHAIN_FILE=C:/vcpkg-2026.10.16/scripts/buildsystems/vcpkg.cmake `               -DVCPKG_TARGET_TRIPLET=x64-windows-static       - run:           name: Build--- a/xveins/CMakeLists.txt+++ b/xveins/CMakeLists.txt@@ -20,13 +20,29 @@ include(CheckCXXCompilerFlag)  set(BUILD_SHARED_LIBS OFF)++option(VN_COMMIT_FROM_GIT+    "Read VN_COMMIT from git at configure time (off for reproducible/offline builds)"+    OFF)+option(VN_STRIP_RELEASE+    "Strip symbols and debug information from Release binaries"+    ON)+option(VN_HARDEN+    "Enable cheap compiler hardening in Release (FORTIFY, stack protector, PIE)"+    OFF)+option(VN_STRICT "Treat compiler warnings as errors" OFF)+set(VN_DEPS_MIRROR "" CACHE STRING+    "Optional base URL for third-party source archives (same filenames as upstream)")  find_package(Threads REQUIRED)  ########################################################################## # OpenSSL: TLS 1.3, Ed25519, and cryptographic randomness for the native-# protocol. Homebrew keeps OpenSSL keg-only on macOS, so try `brew` before -# the default search when the caller did not provide an explicit root.+# protocol. This remains a system dependency because building OpenSSL from+# source requires platform-specific toolchains (Perl/NASM on Windows) and is+# substantially slower than the rest of the build. Homebrew keeps OpenSSL+# keg-only on macOS, so try `brew` before the default search when the caller+# did not provide an explicit root. ########################################################################## if(APPLE AND NOT OPENSSL_ROOT_DIR AND NOT DEFINED ENV{OPENSSL_ROOT_DIR})     find_program(VN_BREW_EXECUTABLE brew)@@ -45,75 +61,89 @@         endforeach()     endif() endif()-find_package(OpenSSL REQUIRED)-find_package(ZLIB REQUIRED)+find_package(OpenSSL 3.0 REQUIRED)  ##########################################################################-# zstd: prefer an installed package, otherwise a system library, otherwise-# fetch a pinned release.+# Third-party C libraries.+#+# These are fetched from pinned release archives and verified by SHA256, so+# a build never picks up an arbitrary system version (zstd in particular+# changes compressed bytes between releases, which breaks pack-output+# reproducibility). Set VN_DEPS_MIRROR to an internal mirror, or point+# FETCHCONTENT_SOURCE_DIR_<NAME> at an unpacked source tree for offline+# builds. ##########################################################################-find_package(zstd CONFIG QUIET)-if(TARGET zstd::libzstd_static)-    set(VN_ZSTD_TARGET zstd::libzstd_static)-elseif(TARGET libzstd_static)-    set(VN_ZSTD_TARGET libzstd_static)+set(FETCHCONTENT_UPDATES_DISCONNECTED ON)++if(VN_DEPS_MIRROR)+    set(_vn_zstd_url "${VN_DEPS_MIRROR}/zstd-1.5.6.tar.gz")+    set(_vn_blake3_url "${VN_DEPS_MIRROR}/BLAKE3-1.5.5.tar.gz")+    set(_vn_zlib_url "${VN_DEPS_MIRROR}/zlib-1.3.1.tar.gz") else()-    find_library(VN_ZSTD_LIBRARY NAMES libzstd.a zstd)-    if(VN_ZSTD_LIBRARY)-        find_path(VN_ZSTD_INCLUDE_DIR NAMES zstd.h)-        add_library(vn_zstd UNKNOWN IMPORTED)-        set_target_properties(vn_zstd PROPERTIES-            IMPORTED_LOCATION "${VN_ZSTD_LIBRARY}"-        )-        if(VN_ZSTD_INCLUDE_DIR)-            set_target_properties(vn_zstd PROPERTIES-                INTERFACE_INCLUDE_DIRECTORIES "${VN_ZSTD_INCLUDE_DIR}"-            )-        endif()-        set(VN_ZSTD_TARGET vn_zstd)-    elseif(TARGET zstd::libzstd_shared)-        set(VN_ZSTD_TARGET zstd::libzstd_shared)-    elseif(TARGET libzstd)-        set(VN_ZSTD_TARGET libzstd)-    endif()+    set(_vn_zstd_url+        "https://github.com/facebook/zstd/releases/download/v1.5.6/zstd-1.5.6.tar.gz")+    set(_vn_blake3_url+        "https://github.com/BLAKE3-team/BLAKE3/archive/refs/tags/1.5.5.tar.gz")+    set(_vn_zlib_url+        "https://github.com/madler/zlib/releases/download/v1.3.1/zlib-1.3.1.tar.gz") endif() -if(NOT VN_ZSTD_TARGET)-    set(ZSTD_BUILD_PROGRAMS OFF CACHE BOOL "" FORCE)-    set(ZSTD_BUILD_CONTRIB OFF CACHE BOOL "" FORCE)-    set(ZSTD_BUILD_TESTS OFF CACHE BOOL "" FORCE)-    set(ZSTD_BUILD_SHARED OFF CACHE BOOL "" FORCE)-    set(ZSTD_BUILD_STATIC ON CACHE BOOL "" FORCE)-    set(ZSTD_LEGACY_SUPPORT OFF CACHE BOOL "" FORCE)-    set(ZSTD_MULTITHREAD_SUPPORT OFF CACHE BOOL "" FORCE)-    FetchContent_Declare(-        zstd-        GIT_REPOSITORY https://github.com/facebook/zstd.git-        GIT_TAG v1.5.6-        GIT_SHALLOW TRUE-    )-    FetchContent_MakeAvailable(zstd)-    if(TARGET libzstd_static)-        set(VN_ZSTD_TARGET libzstd_static)-    else()-        set(VN_ZSTD_TARGET libzstd)-    endif()+set(ZSTD_BUILD_PROGRAMS OFF CACHE BOOL "" FORCE)+set(ZSTD_BUILD_CONTRIB OFF CACHE BOOL "" FORCE)+set(ZSTD_BUILD_TESTS OFF CACHE BOOL "" FORCE)+set(ZSTD_BUILD_SHARED OFF CACHE BOOL "" FORCE)+set(ZSTD_BUILD_STATIC ON CACHE BOOL "" FORCE)+set(ZSTD_LEGACY_SUPPORT OFF CACHE BOOL "" FORCE)+set(ZSTD_MULTITHREAD_SUPPORT OFF CACHE BOOL "" FORCE)+FetchContent_Declare(zstd+    URL "${_vn_zstd_url}"+    URL_HASH SHA256=8c29e06cf42aacc1eafc4077ae2ec6c6fcb96a626157e0593d5e82a34fd403c1+    DOWNLOAD_EXTRACT_TIMESTAMP TRUE+    SOURCE_SUBDIR build/cmake+)+FetchContent_MakeAvailable(zstd)+if(TARGET libzstd_static)+    set(VN_ZSTD_TARGET libzstd_static)+elseif(TARGET libzstd)+    set(VN_ZSTD_TARGET libzstd)+else()+    message(FATAL_ERROR "zstd: no static library target was created") endif() -find_package(blake3 CONFIG QUIET)+FetchContent_Declare(blake3+    URL "${_vn_blake3_url}"+    URL_HASH SHA256=6feba0750efc1a99a79fb9a495e2628b5cd1603e15f56a06b1d6cb13ac55c618+    DOWNLOAD_EXTRACT_TIMESTAMP TRUE+    SOURCE_SUBDIR c+)+FetchContent_MakeAvailable(blake3) if(TARGET blake3 AND NOT TARGET BLAKE3::blake3)     add_library(BLAKE3::blake3 ALIAS blake3) endif() if(NOT TARGET BLAKE3::blake3)-    FetchContent_Declare(-        blake3-        GIT_REPOSITORY https://github.com/BLAKE3-team/BLAKE3.git-        GIT_TAG 1.5.5-        GIT_SHALLOW TRUE-        SOURCE_SUBDIR c-    )-    FetchContent_MakeAvailable(blake3)+    message(FATAL_ERROR "BLAKE3: no library target was created")+endif()++set(ZLIB_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)+set(ZLIB_BUILD_TESTING OFF CACHE BOOL "" FORCE)+set(ZLIB_INSTALL OFF CACHE BOOL "" FORCE)+FetchContent_Declare(zlib+    URL "${_vn_zlib_url}"+    URL_HASH SHA256=9a93b2b7dfdac77ceba5a558a580e74667dd6fede4585b91eefb60f03b72df23+    DOWNLOAD_EXTRACT_TIMESTAMP TRUE+)+FetchContent_MakeAvailable(zlib)+if(TARGET zlibstatic)+    set(VN_ZLIB_TARGET zlibstatic)+elseif(TARGET zlib)+    set(VN_ZLIB_TARGET zlib)+else()+    message(FATAL_ERROR "zlib: no static library target was created") endif()++message(STATUS+    "veins dependencies: zstd 1.5.6, BLAKE3 1.5.5, zlib 1.3.1, "+    "OpenSSL ${OPENSSL_VERSION}")  set(VN_CORE_SOURCES     src/core/common.cpp@@ -144,10 +174,10 @@  check_cxx_compiler_flag(-Wconversion VN_HAS_WCONVERSION) set(VN_VERSION "${PROJECT_VERSION}" CACHE STRING "veins version")-set(VN_COMMIT "" CACHE STRING "veins source commit hash (empty: detect from git)")+set(VN_COMMIT "" CACHE STRING "veins source commit hash (empty: leave unset)")  set(_VN_COMMIT "${VN_COMMIT}")-if(NOT _VN_COMMIT)+if(NOT _VN_COMMIT AND VN_COMMIT_FROM_GIT)     execute_process(         COMMAND git rev-parse --short=12 HEAD         WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"@@ -166,9 +196,9 @@     target_link_libraries(${target} PRIVATE         BLAKE3::blake3         ${VN_ZSTD_TARGET}+        ${VN_ZLIB_TARGET}         OpenSSL::SSL         OpenSSL::Crypto-        ZLIB::ZLIB         Threads::Threads     )     if(WIN32)@@ -181,14 +211,42 @@      if(MSVC)         target_compile_options(${target} PRIVATE /W4 /permissive- /EHsc /Zc:__cplusplus)+        target_compile_options(${target} PRIVATE $<$<CONFIG:Release>:/Brepro>)         target_compile_definitions(${target} PRIVATE             _CRT_SECURE_NO_WARNINGS NOMINMAX WIN32_LEAN_AND_MEAN         )+        if(VN_STRICT)+            target_compile_options(${target} PRIVATE /WX)+        endif()     else()         target_compile_options(${target} PRIVATE -Wall -Wextra -Wpedantic)         if(VN_HAS_WCONVERSION)             target_compile_options(${target} PRIVATE -Wconversion -Wsign-conversion)+        endif()+        # Keep floating-point contraction off: pack delta selection compares+        # ratios, and identical inputs must choose identical bases on every+        # compiler/architecture.+        target_compile_options(${target} PRIVATE -ffp-contract=off)+        target_compile_options(${target} PRIVATE+            $<$<CONFIG:Release>:-g0>+            $<$<CONFIG:Release>:-ffile-prefix-map=${CMAKE_SOURCE_DIR}=.>+        )+        if(VN_STRIP_RELEASE)+            target_link_options(${target} PRIVATE $<$<CONFIG:Release>:-s>)+        endif()+        if(VN_HARDEN)+            target_compile_options(${target} PRIVATE+                $<$<CONFIG:Release>:-fstack-protector-strong>+                $<$<CONFIG:Release>:-U_FORTIFY_SOURCE>+                $<$<CONFIG:Release>:-D_FORTIFY_SOURCE=3>+                $<$<CONFIG:Release>:-fPIE>+            )+            target_link_options(${target} PRIVATE $<$<CONFIG:Release>:-pie>)+        endif()+        if(VN_STRICT)+            target_compile_options(${target} PRIVATE -Werror)         endif()+        target_compile_options(${target} PRIVATE $<$<CONFIG:Debug>:-D_GLIBCXX_ASSERTIONS>)     endif() endfunction() --- /dev/null+++ b/xveins/CMakePresets.json@@ -0,0 +1,79 @@+{+  "version": 6,+  "cmakeMinimumRequired": {+    "major": 3,+    "minor": 25,+    "patch": 0+  },+  "configurePresets": [+    {+      "name": "dev",+      "displayName": "Developer (Debug)",+      "binaryDir": "${sourceDir}/build/dev",+      "cacheVariables": {+        "CMAKE_BUILD_TYPE": "Debug",+        "CMAKE_EXPORT_COMPILE_COMMANDS": "ON",+        "VN_COMMIT_FROM_GIT": "ON"+      }+    },+    {+      "name": "release",+      "displayName": "Release (stripped, reproducible flags)",+      "binaryDir": "${sourceDir}/build/release",+      "cacheVariables": {+        "CMAKE_BUILD_TYPE": "Release",+        "CMAKE_EXPORT_COMPILE_COMMANDS": "ON",+        "VN_COMMIT_FROM_GIT": "OFF",+        "VN_STRIP_RELEASE": "ON"+      }+    },+    {+      "name": "release-harden",+      "displayName": "Release with cheap compiler hardening",+      "inherits": "release",+      "binaryDir": "${sourceDir}/build/release-harden",+      "cacheVariables": {+        "VN_HARDEN": "ON",+        "VN_STRICT": "ON"+      }+    },+    {+      "name": "asan",+      "displayName": "Debug with AddressSanitizer and UndefinedBehaviorSanitizer",+      "binaryDir": "${sourceDir}/build/asan",+      "cacheVariables": {+        "CMAKE_BUILD_TYPE": "Debug",+        "CMAKE_EXPORT_COMPILE_COMMANDS": "ON",+        "CMAKE_CXX_FLAGS": "-fsanitize=address,undefined -fno-omit-frame-pointer",+        "CMAKE_C_FLAGS": "-fsanitize=address,undefined -fno-omit-frame-pointer",+        "CMAKE_EXE_LINKER_FLAGS": "-fsanitize=address,undefined"+      }+    },+    {+      "name": "tsan",+      "displayName": "Debug with ThreadSanitizer",+      "binaryDir": "${sourceDir}/build/tsan",+      "cacheVariables": {+        "CMAKE_BUILD_TYPE": "Debug",+        "CMAKE_EXPORT_COMPILE_COMMANDS": "ON",+        "CMAKE_CXX_FLAGS": "-fsanitize=thread -fno-omit-frame-pointer",+        "CMAKE_C_FLAGS": "-fsanitize=thread -fno-omit-frame-pointer",+        "CMAKE_EXE_LINKER_FLAGS": "-fsanitize=thread"+      }+    }+  ],+  "buildPresets": [+    { "name": "dev", "configurePreset": "dev" },+    { "name": "release", "configurePreset": "release" },+    { "name": "release-harden", "configurePreset": "release-harden" },+    { "name": "asan", "configurePreset": "asan" },+    { "name": "tsan", "configurePreset": "tsan" }+  ],+  "testPresets": [+    { "name": "dev", "configurePreset": "dev", "output": { "outputOnFailure": true } },+    { "name": "release", "configurePreset": "release", "output": { "outputOnFailure": true } },+    { "name": "release-harden", "configurePreset": "release-harden", "output": { "outputOnFailure": true } },+    { "name": "asan", "configurePreset": "asan", "output": { "outputOnFailure": true } },+    { "name": "tsan", "configurePreset": "tsan", "output": { "outputOnFailure": true } }+  ]+}--- a/xveins/src/cli/cli.cpp+++ b/xveins/src/cli/cli.cpp@@ -1082,7 +1082,7 @@  bool print_tree(const fs::path& root, Store& store, const Id& tree_id, const std::string& prefix,                 std::size_t depth) {-    if (depth > 4096)+    if (depth > MAX_TREE_DEPTH)         return false;     auto body = store.read_body(tree_id, TYPE_TREE);     if (!body)--- a/xveins/src/core/common.cpp+++ b/xveins/src/core/common.cpp@@ -951,7 +951,7 @@     return path_to_bytes(p.filename()); } -std::optional<std::vector<std::uint8_t>> read_file_opt(const fs::path& p) {+std::optional<std::vector<std::uint8_t>> read_file_opt(const fs::path& p, std::uint64_t max_size) { #if defined(_WIN32)     std::ifstream in(p, std::ios::binary);     if (!in)@@ -960,6 +960,8 @@     const std::streamoff n = in.tellg();     if (n < 0)         return std::nullopt;+    if (max_size != 0 && static_cast<std::uint64_t>(n) > max_size)+        return std::nullopt;     in.seekg(0, std::ios::beg);     std::vector<std::uint8_t> data(static_cast<std::size_t>(n));     if (n > 0 && !in.read(reinterpret_cast<char*>(data.data()), n)) {@@ -971,7 +973,8 @@     if (fd < 0)         return std::nullopt;     struct stat st {};-    if (::fstat(fd, &st) != 0 || st.st_size < 0) {+    if (::fstat(fd, &st) != 0 || st.st_size < 0 ||+        (max_size != 0 && static_cast<std::uint64_t>(st.st_size) > max_size)) {         ::close(fd);         return std::nullopt;     }@@ -1009,8 +1012,8 @@     return data; } -Result<std::vector<std::uint8_t>> read_file(const fs::path& p) {-    auto data = read_file_opt(p);+Result<std::vector<std::uint8_t>> read_file(const fs::path& p, std::uint64_t max_size) {+    auto data = read_file_opt(p, max_size);     if (!data)         return fail_io("cannot read " + path_display(p));     return *data;@@ -1077,7 +1080,11 @@     out.flush();     return static_cast<bool>(out); #else-    const int fd = ::open(p.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);+    int flags = O_WRONLY | O_CREAT | O_TRUNC;+#if defined(O_NOFOLLOW)+    flags |= O_NOFOLLOW;+#endif+    const int fd = ::open(p.c_str(), flags, 0644);     if (fd < 0)         return false;     std::size_t done = 0;@@ -1113,7 +1120,11 @@     out.flush();     return static_cast<bool>(out); #else-    const int fd = ::open(p.c_str(), O_WRONLY | O_CREAT | O_APPEND, 0644);+    int flags = O_WRONLY | O_CREAT | O_APPEND;+#if defined(O_NOFOLLOW)+    flags |= O_NOFOLLOW;+#endif+    const int fd = ::open(p.c_str(), flags, 0644);     if (fd < 0)         return false;     std::size_t done = 0;--- a/xveins/src/core/common.h+++ b/xveins/src/core/common.h@@ -42,6 +42,11 @@ constexpr std::size_t MAX_TREE_ENTRIES = 1'000'000; constexpr std::size_t MAX_CONFLICT_TERMS = 64; constexpr std::size_t INLINE_THRESHOLD = 16u * 1024u;+// Bound recursive tree walks so a hostile tree cannot exhaust the stack.+constexpr std::size_t MAX_TREE_DEPTH = 512;+// Packs are read into memory; refuse absurdly large ones instead of relying on+// an allocation failure.+constexpr std::uint64_t MAX_STORE_PACK_BYTES = 8ull * 1024ull * 1024ull * 1024ull;  enum class ErrorKind {     None,@@ -416,8 +421,9 @@ std::string path_to_bytes(const fs::path& p); std::string path_display(const fs::path& p); -Result<std::vector<std::uint8_t>> read_file(const fs::path& p);-std::optional<std::vector<std::uint8_t>> read_file_opt(const fs::path& p);+Result<std::vector<std::uint8_t>> read_file(const fs::path& p, std::uint64_t max_size = 0);+std::optional<std::vector<std::uint8_t>> read_file_opt(const fs::path& p,+                                                       std::uint64_t max_size = 0); std::optional<std::vector<std::uint8_t>> read_file_range(const fs::path& p, std::uint64_t offset,                                                          std::size_t length); bool write_file(const fs::path& p, Bytes data);--- a/xveins/src/git/git.cpp+++ b/xveins/src/git/git.cpp@@ -272,7 +272,7 @@ std::optional<Id> materialize_tree(MaterializeCtx& ctx, const Id& old_id, std::size_t depth);  std::optional<Id> materialize_conflict(MaterializeCtx& ctx, const Id& old_id, std::size_t depth) {-    if (depth > 4096)+    if (depth > MAX_TREE_DEPTH)         return std::nullopt;     auto existing = ctx.conflicts.find(old_id);     if (existing != ctx.conflicts.end())@@ -341,7 +341,7 @@ }  std::optional<Id> materialize_tree(MaterializeCtx& ctx, const Id& old_id, std::size_t depth) {-    if (depth > 4096)+    if (depth > MAX_TREE_DEPTH)         return std::nullopt;     auto existing = ctx.trees.find(old_id);     if (existing != ctx.trees.end())@@ -448,7 +448,7 @@ int import_tree_impl(Writer& writer, git::Repo& repo, IdMap& trees, IdMap& blobs, const Oid& oid,                      std::vector<std::pair<Id, std::vector<std::uint8_t>>>& raw_saves,                      std::size_t& new_trees, std::size_t& new_blobs, std::size_t depth) {-    if (depth > 4096)+    if (depth > MAX_TREE_DEPTH)         return 1;     if (auto existing = trees.get(oid)) {         (void)existing;@@ -518,7 +518,7 @@  bool export_tree(const fs::path& root, Store& store, IdMap& trees, IdMap& blobs, const Id& id,                  Oid& out, std::size_t depth) {-    if (depth > 4096)+    if (depth > MAX_TREE_DEPTH)         return false;     if (auto existing = trees.reverse(id)) {         out = *existing;@@ -609,7 +609,7 @@  bool export_commit(const fs::path& root, Store& store, IdMap& commits, IdMap& trees, IdMap& blobs,                    const std::vector<Id>& native, const Id& id, Oid& out, std::size_t depth) {-    if (depth > 4096)+    if (depth > MAX_TREE_DEPTH)         return false;     if (auto existing = commits.reverse(id)) {         out = *existing;--- a/xveins/src/git/git_internal.h+++ b/xveins/src/git/git_internal.h@@ -14,6 +14,13 @@ namespace vn::git {  using Oid = std::array<std::uint8_t, 20>;++// A single git object is materialized in memory during import/export. Bound it+// so a hostile pack or loose object cannot trigger an unbounded allocation.+constexpr std::size_t MAX_GIT_OBJECT_BODY = 1ull * 1024ull * 1024ull * 1024ull;+// Packs are currently read in full. Bound the file size for the same reason.+constexpr std::uint64_t MAX_GIT_PACK_BYTES = 8ull * 1024ull * 1024ull * 1024ull;+constexpr std::size_t MAX_GIT_DELTA_DEPTH = 128;  struct OidLess {     bool operator()(const Oid& a, const Oid& b) const {@@ -52,7 +59,8 @@ std::optional<Oid> oid_from_hex(std::string_view hex); std::optional<Oid> object_hash(std::uint8_t kind, Bytes body); std::optional<Repo> open_repo(const fs::path& git_dir);-std::optional<Object> read_object(Repo& repo, const Oid& oid, bool verify = false);+std::optional<Object> read_object(Repo& repo, const Oid& oid, bool verify = false,+                                  std::size_t depth = 0); std::shared_ptr<Repo> cached_repo(const fs::path& git_dir);  struct RawTreeEntry {--- a/xveins/src/git/git_object.cpp+++ b/xveins/src/git/git_object.cpp@@ -65,11 +65,13 @@     return 0; } -std::optional<std::vector<std::uint8_t>> inflate_unknown(Bytes input);+std::optional<std::vector<std::uint8_t>> inflate_unknown(Bytes input, std::size_t max_output);  std::optional<std::vector<std::uint8_t>> inflate_exact(Bytes input, std::size_t expected) {+    if (expected > MAX_GIT_OBJECT_BODY)+        return std::nullopt;     if (expected == 0) {-        auto result = inflate_unknown(input);+        auto result = inflate_unknown(input, MAX_GIT_OBJECT_BODY);         if (!result || !result->empty())             return std::nullopt;         return result;@@ -84,22 +86,39 @@     return out; } -std::optional<std::vector<std::uint8_t>> inflate_unknown(Bytes input) {+std::optional<std::vector<std::uint8_t>> inflate_unknown(Bytes input, std::size_t max_output) {+    if (max_output == 0)+        max_output = MAX_GIT_OBJECT_BODY;     z_stream zs{};     if (inflateInit(&zs) != Z_OK)         return std::nullopt;-    std::vector<std::uint8_t> out(4096);+    std::vector<std::uint8_t> out(std::min<std::size_t>(4096, max_output));     zs.next_in = const_cast<Bytef*>(input.data());     zs.avail_in = static_cast<uInt>(input.size());     int rc = Z_OK;     for (;;) {-        if (zs.total_out == out.size())-            out.resize(out.size() * 2);+        if (zs.total_out == out.size()) {+            if (out.size() >= max_output) {+                inflateEnd(&zs);+                return std::nullopt;+            }+            const std::size_t grown =+                std::min(max_output, out.size() > max_output / 2 ? max_output : out.size() * 2);+            if (grown <= out.size()) {+                inflateEnd(&zs);+                return std::nullopt;+            }+            out.resize(grown);+        }         zs.next_out = out.data() + zs.total_out;         zs.avail_out = static_cast<uInt>(out.size() - zs.total_out);         rc = inflate(&zs, Z_NO_FLUSH);         if (rc == Z_STREAM_END)             break;+        if (rc == Z_BUF_ERROR && zs.avail_in == 0) {+            inflateEnd(&zs);+            return std::nullopt;+        }         if (rc != Z_OK) {             inflateEnd(&zs);             return std::nullopt;@@ -155,7 +174,7 @@     if (!src_size || src_size->value != base.size())         return std::nullopt;     const auto dst_size = read_delta_varint(delta, src_size->next);-    if (!dst_size || dst_size->value > 2147483648ull)+    if (!dst_size || dst_size->value > MAX_GIT_OBJECT_BODY)         return std::nullopt;     const std::size_t cap = static_cast<std::size_t>(dst_size->value);     std::vector<std::uint8_t> out(cap);@@ -215,7 +234,7 @@  std::optional<Object> read_at(Repo& repo, Pack& pack, std::uint64_t start, bool verify,                               std::size_t depth) {-    if (depth > 4096 || start >= pack.data.size())+    if (depth > MAX_GIT_DELTA_DEPTH || start >= pack.data.size())         return std::nullopt;     Bytes data(pack.data.data(), pack.data.size());     const std::size_t begin = static_cast<std::size_t>(start);@@ -222,7 +241,7 @@     const std::uint8_t c0 = data[begin];     const std::uint8_t kind = static_cast<std::uint8_t>((c0 >> 4) & 7);     const auto header = read_be_varint(data, begin);-    if (!header || header->value > 2147483648ull)+    if (!header || header->value > MAX_GIT_OBJECT_BODY)         return std::nullopt;     const std::size_t size = static_cast<std::size_t>(header->value);     std::size_t pos = header->next;@@ -245,6 +264,8 @@             more = (c & 0x80) != 0;         }         has_base_off = true;+        if (acc > start)+            return std::nullopt;         base_off = start - acc;     } else if (kind == KIND_REF_DELTA) {         if (pos + 20 > data.size())@@ -270,7 +291,7 @@             return std::nullopt;         base = read_at(repo, pack, base_off, verify, depth + 1);     } else if (has_base_oid) {-        base = read_object(repo, base_oid, verify);+        base = read_object(repo, base_oid, verify, depth + 1);     }     if (!base)         return std::nullopt;@@ -301,6 +322,10 @@         return std::nullopt;     const std::size_t n = be32(data, fanout_off + 255 * 4);     if (n != pack_count)+        return std::nullopt;+    const std::size_t names_off = fanout_off + 1024;+    const std::size_t min_entry = is_v2 ? 28 : 24;+    if (n > (data.size() - 40 - names_off) / min_entry)         return std::nullopt;      Pack pack;@@ -307,7 +332,6 @@     pack.oids.resize(n);     pack.offsets.resize(n);     if (is_v2) {-        const std::size_t names_off = fanout_off + 1024;         const std::size_t crcs_off = names_off + n * 20;         const std::size_t offs_off = crcs_off + n * 4;         const std::size_t large_off = offs_off + n * 4;@@ -342,7 +366,7 @@ }  std::optional<Pack> open_pack(const fs::path& pack_path, const fs::path& idx_path) {-    auto pdata = read_file_opt(pack_path);+    auto pdata = read_file_opt(pack_path, MAX_GIT_PACK_BYTES);     if (!pdata || pdata->size() < 32)         return std::nullopt;     if (std::memcmp(pdata->data(), "PACK", 4) != 0)@@ -356,7 +380,7 @@     if (std::memcmp(pack_trailer.data(), pdata->data() + trailer_off, 20) != 0)         return std::nullopt; -    auto idata = read_file_opt(idx_path);+    auto idata = read_file_opt(idx_path, MAX_GIT_PACK_BYTES);     if (!idata)         return std::nullopt;     auto parsed = parse_idx(bytes_of(*idata), count, Bytes(pdata->data() + trailer_off, 20));@@ -371,10 +395,10 @@     const std::string hex = oid_hex(oid);     const fs::path path = repo.git_dir / "objects" / path_from_bytes(hex.substr(0, 2)) /                           path_from_bytes(hex.substr(2));-    auto compressed = read_file_opt(path);+    auto compressed = read_file_opt(path, MAX_GIT_OBJECT_BODY);     if (!compressed)         return std::nullopt;-    auto inflated = inflate_unknown(bytes_of(*compressed));+    auto inflated = inflate_unknown(bytes_of(*compressed), MAX_GIT_OBJECT_BODY);     if (!inflated)         return std::nullopt;     Bytes data(inflated->data(), inflated->size());@@ -589,12 +613,14 @@     return repo; } -std::optional<Object> read_object(Repo& repo, const Oid& oid, bool verify) {+std::optional<Object> read_object(Repo& repo, const Oid& oid, bool verify, std::size_t depth) {+    if (depth > MAX_GIT_DELTA_DEPTH)+        return std::nullopt;     for (auto& pack : repo.packs) {         auto idx = find_oid(pack, oid);         if (!idx)             continue;-        auto object = read_at(repo, pack, pack.offsets[*idx], verify, 0);+        auto object = read_at(repo, pack, pack.offsets[*idx], verify, depth);         if (!object)             return std::nullopt;         if (verify) {--- a/xveins/src/merge/merge.cpp+++ b/xveins/src/merge/merge.cpp@@ -91,7 +91,7 @@  bool flatten_any(Store& store, Txn* tx, const Id& tree_id, std::string& prefix,                  std::vector<FlatEntry>& out, std::size_t depth) {-    if (depth > 4096)+    if (depth > MAX_TREE_DEPTH)         return false;     auto body = read_body_any(store, tx, TYPE_TREE, tree_id);     if (!body)@@ -1429,7 +1429,7 @@ std::optional<Id> tree_edit_into(Txn& tx, Store& store, const Id& tree_id, std::string_view path,                                  bool present, std::uint8_t kind, const Id& target,                                  std::size_t depth) {-    if (depth > 4096)+    if (depth > MAX_TREE_DEPTH)         return std::nullopt;     auto body = read_body_any(store, &tx, TYPE_TREE, tree_id);     if (!body)--- a/xveins/src/net/net.cpp+++ b/xveins/src/net/net.cpp@@ -477,6 +477,7 @@     if (connected == INVALID_SOCKET_VALUE)         return std::nullopt;     enable_tcp_nodelay(connected);+    set_socket_timeout(connected, 120000);     return std::optional<Socket>(connected); } @@ -525,6 +526,7 @@         return std::nullopt;     const Socket socket = static_cast<Socket>(accepted);     enable_tcp_nodelay(socket);+    set_socket_timeout(socket, 120000);     return socket; #else     const int accepted = ::accept(static_cast<int>(listener), nullptr, nullptr);@@ -531,7 +533,28 @@     if (accepted < 0)         return std::nullopt;     enable_tcp_nodelay(accepted);+    set_socket_timeout(accepted, 120000);     return accepted;+#endif+}++bool set_socket_timeout(Socket socket, std::uint32_t milliseconds) {+#if defined(_WIN32)+    DWORD timeout = milliseconds;+    const bool recv_ok = setsockopt(static_cast<SOCKET>(socket), SOL_SOCKET, SO_RCVTIMEO,+                                    reinterpret_cast<const char*>(&timeout), sizeof(timeout)) == 0;+    const bool send_ok = setsockopt(static_cast<SOCKET>(socket), SOL_SOCKET, SO_SNDTIMEO,+                                    reinterpret_cast<const char*>(&timeout), sizeof(timeout)) == 0;+    return recv_ok && send_ok;+#else+    timeval timeout{};+    timeout.tv_sec = static_cast<time_t>(milliseconds / 1000);+    timeout.tv_usec = static_cast<suseconds_t>((milliseconds % 1000) * 1000);+    const bool recv_ok = setsockopt(static_cast<int>(socket), SOL_SOCKET, SO_RCVTIMEO, &timeout,+                                    sizeof(timeout)) == 0;+    const bool send_ok = setsockopt(static_cast<int>(socket), SOL_SOCKET, SO_SNDTIMEO, &timeout,+                                    sizeof(timeout)) == 0;+    return recv_ok && send_ok; #endif } --- a/xveins/src/net/net.h+++ b/xveins/src/net/net.h@@ -82,6 +82,7 @@ Socket tcp_listen(int port, int backlog = 64); std::optional<Socket> tcp_accept(Socket listener); void close_socket(Socket socket);+bool set_socket_timeout(Socket socket, std::uint32_t milliseconds);  void ignore_sigpipe(); fs::path self_exe();--- a/xveins/src/store/store.cpp+++ b/xveins/src/store/store.cpp@@ -700,7 +700,7 @@             std::size_t voted = SIZE_MAX;             std::size_t voted_count = 0;             for (const auto& [candidate, count] : votes) {-                if (count > voted_count) {+                if (count > voted_count || (count == voted_count && candidate < voted)) {                     voted_count = count;                     voted = candidate;                 }@@ -989,8 +989,10 @@         return 2;     const fs::path pfinal = packs_dir(root) / (output.name + ".vpack");     const fs::path ifinal = packs_dir(root) / (output.name + ".vidx");-    const fs::path ptmp = tmp_dir(root) / (output.name + ".vpack.tmp");-    const fs::path itmp = tmp_dir(root) / (output.name + ".vidx.tmp");+    const std::string suffix =+        "." + std::to_string(static_cast<unsigned long long>(random_u64())) + ".tmp";+    const fs::path ptmp = tmp_dir(root) / (output.name + ".vpack" + suffix);+    const fs::path itmp = tmp_dir(root) / (output.name + ".vidx" + suffix);     if (!write_atomic(ptmp, pfinal, bytes_of(output.pack)))         return 1;     if (!write_atomic(itmp, ifinal, bytes_of(output.index))) {@@ -1011,13 +1013,15 @@     std::vector<RawObject> objects;     std::set<Id> seen;     std::uint64_t before = 0;-    for (const auto& name : list_directory(source_dir)) {+    auto names = list_directory(source_dir);+    std::sort(names.begin(), names.end());+    for (const auto& name : names) {         if (name.size() <= 6 || name.compare(name.size() - 6, 6, ".vpack") != 0)             continue;         const std::string base = name.substr(0, name.size() - 6);         if (!path_is_file(source_dir / path_from_bytes(base + ".vidx")))             continue;-        auto data = read_file_opt(source_dir / path_from_bytes(name));+        auto data = read_file_opt(source_dir / path_from_bytes(name), MAX_STORE_PACK_BYTES);         if (!data) {             error_prefix();             std::cout << "cannot read pack " << name << "\n";@@ -1142,6 +1146,8 @@  static std::optional<std::vector<std::uint8_t>> read_handle_range(StoreHandle& handle, std::uint64_t offset, std::size_t length) {+    if (static_cast<std::uint64_t>(length) > MAX_STORE_PACK_BYTES)+        return std::nullopt; #if !defined(_WIN32)     const int fd = handle_fd(handle);     if (fd < 0)@@ -1174,7 +1180,7 @@         return false;     name.resize(name.size() - 6);     const fs::path idx_path = handle.path.parent_path() / (name + ".vidx");-    auto data = read_file_opt(idx_path);+    auto data = read_file_opt(idx_path, MAX_STORE_PACK_BYTES);     if (!data)         return false;     auto decoded = decode_index(std::move(*data));@@ -1195,7 +1201,7 @@         return true;     if (!ensure_index(handle))         return false;-    auto data = read_file_opt(handle.path);+    auto data = read_file_opt(handle.path, MAX_STORE_PACK_BYTES);     if (!data)         return false;     auto decoded = decode_pack(std::move(*data));@@ -1225,9 +1231,12 @@         handle.mtime_ns = handle_mtime(handle.path);         store.handles_.push_back(std::move(handle));     }-    std::stable_sort(-        store.handles_.begin(), store.handles_.end(),-        [](const StoreHandle& a, const StoreHandle& b) { return a.mtime_ns >= b.mtime_ns; });+    std::sort(store.handles_.begin(), store.handles_.end(),+              [](const StoreHandle& a, const StoreHandle& b) {+                  if (a.mtime_ns != b.mtime_ns)+                      return a.mtime_ns > b.mtime_ns;+                  return a.path < b.path;+              });     return store; } @@ -1259,9 +1268,11 @@             handles_.push_back(std::move(handle));         }     }-    std::stable_sort(-        handles_.begin(), handles_.end(),-        [](const StoreHandle& a, const StoreHandle& b) { return a.mtime_ns >= b.mtime_ns; });+    std::sort(handles_.begin(), handles_.end(), [](const StoreHandle& a, const StoreHandle& b) {+        if (a.mtime_ns != b.mtime_ns)+            return a.mtime_ns > b.mtime_ns;+        return a.path < b.path;+    }); }  static std::optional<Loc> read_record_loc_at(StoreHandle& handle, std::size_t pack_index,@@ -1283,6 +1294,11 @@         return std::nullopt;     if (*raw_len > pack_type_limit(*type))         return std::nullopt;+    // Compressed or delta-framed payloads may exceed the raw length by a small+    // amount, but never by an unbounded amount. Refuse absurd stored lengths+    // before the read allocates them.+    if (*stored_len > static_cast<std::uint64_t>(pack_type_limit(*type)) + MAX_CHUNK_LEN)+        return std::nullopt;     if (*compression == 0 && *raw_len != *stored_len)         return std::nullopt;     Loc loc;@@ -1703,14 +1719,23 @@     return remove_file(op_heads_dir(root) / hex_encode(id)); } +static std::optional<View> load_view_for_head(Store& store, const Id& id);+static void merge_view_into(View& dst, const View& src);+ std::optional<View> current_view(const fs::path& root, Store& store) {     const auto heads = read_heads(root);     if (heads.empty())         return std::nullopt;-    auto op = store.read_operation(heads.front());-    if (!op)+    auto base = load_view_for_head(store, heads.front());+    if (!base)         return std::nullopt;-    return store.read_view(op->view);+    for (std::size_t i = 1; i < heads.size(); ++i) {+        auto extra = load_view_for_head(store, heads[i]);+        if (extra)+            merge_view_into(*base, *extra);+    }+    sort_view(*base);+    return base; }  static std::optional<View> load_view_for_head(Store& store, const Id& id) {@@ -1782,7 +1807,6 @@             if (extra)                 merge_view_into(*base, *extra);         }-        add_unique_head(*base, heads.front());         tx.view_ = std::move(*base);     }     std::stable_sort(tx.view_.bookmarks.begin(), tx.view_.bookmarks.end(),@@ -2124,7 +2148,7 @@  static bool flatten_into(Store& store, const Id& tree_id, std::string& prefix,                          std::vector<FlatEntry>& out, std::size_t depth) {-    if (depth > 4096)+    if (depth > MAX_TREE_DEPTH)         return false;     auto body = store.read_body(tree_id, TYPE_TREE);     if (!body)@@ -2213,7 +2237,7 @@     const auto cached = cache.find(tree_id);     if (cached != cache.end())         return cached->second;-    if (depth > 4096)+    if (depth > MAX_TREE_DEPTH)         return true;     auto body = store.read_body(tree_id, TYPE_TREE);     if (!body)--- a/xveins/src/worktree/remove.cpp+++ b/xveins/src/worktree/remove.cpp@@ -1,6 +1,6 @@ #include "cli/local_commands.h"-#include "worktree/pathspec.h" #include "store/store.h"+#include "worktree/pathspec.h" #include "worktree/worktree.h"  #include <algorithm>@@ -77,7 +77,7 @@  std::optional<Id> filter_tree(Txn& tx, Store& store, const Id& tree_id, std::string_view prefix,                               const std::vector<std::string>& removes, std::size_t depth) {-    if (depth > 4096)+    if (depth > MAX_TREE_DEPTH)         return tree_id;     if (!subtree_affected(prefix, removes))         return tree_id;--- a/xveins/src/worktree/worktree.cpp+++ b/xveins/src/worktree/worktree.cpp@@ -229,7 +229,7 @@                             const AttributeRules& attributes, bool cache_valid, const Cache& cache,                             std::vector<CacheEntry>& new_cache, std::int64_t now_ms,                             BuildState& state, std::size_t depth) {-    if (depth > 4096) {+    if (depth > MAX_TREE_DEPTH) {         state.failed = true;         return std::nullopt;     }