60 changed files with 12913 additions and 425 deletions

No files matched your search

+1 -1
View File
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 4.0.0) cmake_minimum_required(VERSION 4.0.0)
project(Void VERSION 1.2.1 LANGUAGES CXX) project(Void VERSION 1.2.1 LANGUAGES C CXX)
if(PROJECT_IS_TOP_LEVEL) if(PROJECT_IS_TOP_LEVEL)
option(BUILD_SHARED_LIBS "Build Void modules as shared libraries" ON) option(BUILD_SHARED_LIBS "Build Void modules as shared libraries" ON)
elseif(NOT DEFINED BUILD_SHARED_LIBS) elseif(NOT DEFINED BUILD_SHARED_LIBS)
+82 -2
View File
@@ -158,9 +158,89 @@ function(void_fetch_dependency DEP_NAME)
endif() endif()
if(DEP_NAME STREQUAL "SQLite3") if(DEP_NAME STREQUAL "SQLite3")
if(NOT TARGET SQLite3::SQLite3 AND NOT TARGET SQLite::SQLite3) if(TARGET SQLite3::SQLite3)
find_package(SQLite3 REQUIRED) return()
endif() endif()
if(TARGET SQLite::SQLite3)
add_library(SQLite3::SQLite3 ALIAS SQLite::SQLite3)
return()
endif()
set(_void_sqlite_dir "${VOID_SQLITE3_AMALGAMATION_DIR}")
if(NOT _void_sqlite_dir)
find_package(SQLite3 QUIET)
if(TARGET SQLite3::SQLite3)
return()
endif()
if(TARGET SQLite::SQLite3)
add_library(SQLite3::SQLite3 ALIAS SQLite::SQLite3)
return()
endif()
endif()
option(VOID_FETCH_SQLITE3
"Allow FetchContent SQLite3 amalgamation fallback when system SQLite3 is unavailable"
ON)
set(VOID_SQLITE3_AMALGAMATION_DIR "" CACHE PATH
"Path containing pre-downloaded sqlite3.c and sqlite3.h amalgamation sources")
set(VOID_SQLITE3_FETCH_URL
"https://www.sqlite.org/2025/sqlite-amalgamation-3490100.zip"
CACHE STRING "SQLite3 amalgamation archive URL for FetchContent fallback")
set(VOID_SQLITE3_FETCH_HASH "" CACHE STRING
"Optional SHA256 hash (SHA256=...) for VOID_SQLITE3_FETCH_URL")
if(NOT _void_sqlite_dir AND VOID_FETCH_SQLITE3 AND
NOT CMAKE_DISABLE_FIND_PACKAGE_SQLite3)
message(STATUS "[Void] System SQLite3 not found — falling back to SQLite3 amalgamation")
if(VOID_SQLITE3_FETCH_HASH)
FetchContent_Declare(SQLite3
URL "${VOID_SQLITE3_FETCH_URL}"
URL_HASH "${VOID_SQLITE3_FETCH_HASH}"
SYSTEM
)
else()
FetchContent_Declare(SQLite3
URL "${VOID_SQLITE3_FETCH_URL}"
SYSTEM
)
endif()
FetchContent_MakeAvailable(SQLite3)
if(EXISTS "${sqlite3_SOURCE_DIR}/sqlite3.c")
set(_void_sqlite_dir "${sqlite3_SOURCE_DIR}")
else()
file(GLOB _found_sqlite_c LIST_DIRECTORIES FALSE
"${sqlite3_SOURCE_DIR}/*/sqlite3.c")
if(_found_sqlite_c)
list(GET _found_sqlite_c 0 _first_sqlite_c)
get_filename_component(_void_sqlite_dir "${_first_sqlite_c}" DIRECTORY)
endif()
endif()
endif()
if(_void_sqlite_dir AND EXISTS "${_void_sqlite_dir}/sqlite3.c" AND
EXISTS "${_void_sqlite_dir}/sqlite3.h")
void_fetch_dependency(Threads)
add_library(void_sqlite3_amalgamation STATIC
"${_void_sqlite_dir}/sqlite3.c")
set_target_properties(void_sqlite3_amalgamation PROPERTIES
POSITION_INDEPENDENT_CODE ON
C_STANDARD 11
SYSTEM TRUE)
target_include_directories(void_sqlite3_amalgamation SYSTEM PUBLIC
"${_void_sqlite_dir}")
target_compile_definitions(void_sqlite3_amalgamation PRIVATE
SQLITE_THREADSAFE=1
SQLITE_ENABLE_FTS5
SQLITE_ENABLE_JSON1
SQLITE_DQS=0)
target_link_libraries(void_sqlite3_amalgamation PUBLIC
Threads::Threads
"$<$<NOT:$<PLATFORM_ID:Windows>>:${CMAKE_DL_LIBS};m>")
add_library(SQLite3::SQLite3 ALIAS void_sqlite3_amalgamation)
return()
endif()
find_package(SQLite3 REQUIRED)
if(NOT TARGET SQLite3::SQLite3 AND TARGET SQLite::SQLite3) if(NOT TARGET SQLite3::SQLite3 AND TARGET SQLite::SQLite3)
add_library(SQLite3::SQLite3 ALIAS SQLite::SQLite3) add_library(SQLite3::SQLite3 ALIAS SQLite::SQLite3)
endif() endif()
+25 -6
View File
@@ -1,8 +1,8 @@
# Workflow state # Workflow state
Updated: 2026-11-26. Updated: 2026-11-26.
Repository: VoidLibrary; active branch `feat/roadmap-p2-wave8` (from `main` Repository: VoidLibrary; active branch `feat/upstream-vbs-requests` (from `main`
at `d83d0f4`, merged Waves 1–7 and pushed to `origin/main`). at `53d42bd`, merged Waves 1–8 and pushed to `origin/main`).
## Completed objective ## Completed objective
@@ -320,11 +320,30 @@ while leaving local untracked files untouched.
- Full Debug ASan+UBSan (`/tmp/void-w8-asan`, 45 modules): `VoidTests` 1,437 tests (`37.13s`), 0 leaks, 0 UB. - Full Debug ASan+UBSan (`/tmp/void-w8-asan`, 45 modules): `VoidTests` 1,437 tests (`37.13s`), 0 leaks, 0 UB.
- Debug TSan (`/tmp/void-w8-tsan`, `ServicePlugin;ConfigurationAsync;Fsm;Testing`, 20 modules): `VoidTests` 1,110 tests (1,107 passed, 3 skipped, 0 failed, `11.49s`), 0 data races. - Debug TSan (`/tmp/void-w8-tsan`, `ServicePlugin;ConfigurationAsync;Fsm;Testing`, 20 modules): `VoidTests` 1,110 tests (1,107 passed, 3 skipped, 0 failed, `11.49s`), 0 data races.
### VoidBuildSystem Upstream Feature Wave (`VL-001`..`VL-013`, `feat/upstream-vbs-requests`)
- **Batch A (`adfc854`, `VL-002`, `VL-008`, `VL-009`, `VL-012`, `VL-013`)**:
- Reserved `kNetErrorDomain = 26`; enforced `PascalCase` types / `snake_case` methods naming (`VL-012`); added strict RFC 3629/8259 UTF-8 validation in `StrictJson`, `Semver` shorthand comparators (`^1`, `^1.0`, `~1.2`, `>=1.2 <2`), header-only `Data/Toml.hpp` TOML 1.0 parser/serializer with `Origin`, and zero-CMake self-registering `VOID_TEST*` macros.
- Verified (`Data;Text;Testing`, `-Werror`): `690 tests (687 ✔, 3 ⊘)` in `351.9ms`; pure `g++` multi-file stem-collision binary `4/4` (`0.1ms`).
- **Batch B (`b50131f`, `VL-001`, `VL-003`, `VL-010`, `VL-011`)**:
- Full process-group supervision (`PR_SET_CHILD_SUBREAPER`, `waitpid(-pgid)`, `SIGKILL` escalation), `FileLock` / `atomic_symlink_swap` / `reflink_copy_file` / `set_timestamps_nofollow`, Linux `inotify` recursive `DirectoryWatcher`, `Argparse` subcommands/`option_many`/`positional_many`/`ParseOutcome`, top-level `LANGUAGES C CXX`, and FetchContent SQLite3 amalgamation fallback.
- Verified (`/tmp/void-vbs-b`, `-Werror`): `791 tests (788 ✔, 3 ⊘)` in `1.72s`, `ctest` `2/2` (`14.44s` incl. `SystemOnly`, `ConfigurationOnly`, `SqliteOnly`).
- **Batch C (`22c8538`, `VL-006`, `VL-007`)**:
- Optional `OpenSSL::Crypto` (`VOID_CRYPTO_HAS_OPENSSL`) + pure-C++ FIPS 180-4 SHA-1/256/512 & RFC 7693 BLAKE2b-256/512 + HMAC/HKDF + `snake_case` aliases; optional `LibArchive` (`VOID_ARCHIVE_HAS_LIBARCHIVE`) + pure-C++ USTAR/PAX tar & deterministic `ArchiveCompression::Gzip` + `create()`.
- Verified zero-OpenSSL (`534 ✔ / 3 ⊘`, `ctest` `2/2` `5.59s`), zero-LibArchive (`405 ✔ / 3 ⊘`, `ctest` `2/2` `6.22s`), and full backends (`888 ✔ / 3 ⊘`, `ctest` `2/2` `15.53s`).
- **Batch D (`66baae7`, `VL-004`, `VL-005`) + TSan/race fix (`9920bfd`)**:
- POSIX TCP HTTP/1.1 `HttpServer`, streaming `HttpClient` + `HttpClient::secure()` TLS >= 1.2 + CA/SAN verification + cross-origin/downgrade/redaction + `std::stop_token` cancellation + `NetOnly` consumer (`66baae7`); scoped GCC `-Wno-tsan` to `src/Net/Http.cpp` and fixed `StallServer` join order (`9920bfd`).
- Verified `Net;System;Crypto;Testing` (`563 ✔ / 3 ⊘`, `ctest` `2/2` `8.48s` incl. `NetOnly`).
- **Full-suite & sanitizer checks**:
- Full RelWithDebInfo (`/tmp/void-vbs-full`, 45 modules, `-Werror`): `VoidTests` `1,456` discovered (`1,452 ✔`, `4 ⊘`, `0 ✘`) in `21.94s` (`22.09s` post-`9920bfd`), `ctest` `2/2` in `82.82s` (`VoidTests` `22.03s`, `VoidInstalledComponentConsumers` `60.79s` across all `35` consumers incl. `NetOnly`), `VoidFoundationBench` (`rev=66baae74a0b7`) recorded.
- Full Debug ASan+UBSan (`/tmp/void-vbs-asan`, 45 modules, `-Werror`): `1,456` discovered (`1,452 ✔`, `4 ⊘`, `0 ✘`) in `39.11s`, `0` leaks, `0` UB (+ post-`9920bfd` `Http|Net|Server` `9/9 ✔` in `1.58s`).
- Debug TSan (`/tmp/void-vbs-tsan`, `Net;System;SystemAsync;Configuration;Crypto;Archive;Data;Text;Testing`, 17 modules, `-Werror`): `957` discovered (`954 ✔`, `3 ⊘`, `0 ✘`) in `10.65s`, `0` data races, `0` lock-order warnings.
## Ownership and next step ## Ownership and next step
Waves 1–8 (`P0`, `P1`, `P2` Operations Foundations, `System`/`SystemAsync`/`IPC`, Waves 1–8 (`P0`, `P1`, `P2` Operations Foundations, `System`/`SystemAsync`/`IPC`,
`Crypto`/`CryptoAsync`/`Security`/`SecurityAsync`/`Archive`/`Update`, `Crypto`/`CryptoAsync`/`Security`/`SecurityAsync`/`Archive`/`Update`,
`Sqlite`/`SqliteAsync`/`Storage` `G-STORE`, and `Sqlite`/`SqliteAsync`/`Storage` `G-STORE`,
`Service`/`ServicePlugin`/`Plugin`/`Configuration`/`ConfigurationAsync`/`Fsm`) are complete `Service`/`ServicePlugin`/`Plugin`/`Configuration`/`ConfigurationAsync`/`Fsm`)
and merged to `main`, proceeding to the VoidBuildSystem upstream feature wave and the VoidBuildSystem upstream feature wave (`VL-001`..`VL-013`) are complete,
(`VL-001`..`VL-013`) and P2 `Net`. verified, and merged to `main` via `--no-ff`.
+9
View File
@@ -110,6 +110,15 @@ These tasks author plans. Future feature task IDs inside those plans remain plan
| M-CONFIGURATION-01..05 | Hardened `Configuration` (`kConfigurationErrorDomain = 24`, `Bind.hpp` attributes, bounded `Schema<T>` reflection/provenance/redaction/deprecation checks) + split `ConfigurationAsync` (transactional `ReloadController<T>`, `Snapshot<T>`, `prepare_external`, coalescing `WatcherService` integration), `ConfigurationOnly` & `ConfigurationAsyncOnly` consumers (`1dc51d5`) | [M-CONFIGURATION-01-05](tasks/M-CONFIGURATION-01-05.md) | VERIFIED | Standalone `ConfigurationAsync;Testing` `Configuration*` 6/6 (`0.7ms`), `ctest` 2/2 (`13.75s`), Debug TSan 1,107 ✔ (0 races), full RelWithDebInfo (`1,434 ✔`), ASan+UBSan (0 leaks/UB) | | M-CONFIGURATION-01..05 | Hardened `Configuration` (`kConfigurationErrorDomain = 24`, `Bind.hpp` attributes, bounded `Schema<T>` reflection/provenance/redaction/deprecation checks) + split `ConfigurationAsync` (transactional `ReloadController<T>`, `Snapshot<T>`, `prepare_external`, coalescing `WatcherService` integration), `ConfigurationOnly` & `ConfigurationAsyncOnly` consumers (`1dc51d5`) | [M-CONFIGURATION-01-05](tasks/M-CONFIGURATION-01-05.md) | VERIFIED | Standalone `ConfigurationAsync;Testing` `Configuration*` 6/6 (`0.7ms`), `ctest` 2/2 (`13.75s`), Debug TSan 1,107 ✔ (0 races), full RelWithDebInfo (`1,434 ✔`), ASan+UBSan (0 leaks/UB) |
| M-FSM-01..05 | Hardened `Fsm` (`kFsmErrorDomain = 25`, shared `terminal(Status)` incl. `Faulted`, `TerminationReason`, `FsmLimits` bounds & reserved control lane, `MonotonicClock` & borrowed `ExecutionBinding`, per-state stop scopes & waiter/timer purge before `on_exit()`, `run_parallel_structured` / `run_parallel_any_structured` loser stop+join & tie-break, boundary `request_checkpoint` / `safe_point` / `restore_checkpoint` / `restore_legacy_checkpoint`, `acquire_service<I>()`, hardened `Orchestrator` `StopOnFault`/`BoundedRestart` & `FsmModel::~FsmModel()` worker join), `FsmOnly` consumer (`ef5312c`, `40b579d`, `cb988fa`) | [M-FSM-01-05](tasks/M-FSM-01-05.md) | VERIFIED | Standalone `Fsm;Testing` 814 ✔ / 2 skips (`789.1ms`), `ctest` 2/2 (`9.59s`), Debug TSan 1,107 ✔ (0 races, `internal_FsmServiceHotReload` 4/4), full RelWithDebInfo (`1,434 ✔`, `ctest` 2/2 `77.11s`), ASan+UBSan (`1,434 ✔`, 0 leaks/UB) | | M-FSM-01..05 | Hardened `Fsm` (`kFsmErrorDomain = 25`, shared `terminal(Status)` incl. `Faulted`, `TerminationReason`, `FsmLimits` bounds & reserved control lane, `MonotonicClock` & borrowed `ExecutionBinding`, per-state stop scopes & waiter/timer purge before `on_exit()`, `run_parallel_structured` / `run_parallel_any_structured` loser stop+join & tie-break, boundary `request_checkpoint` / `safe_point` / `restore_checkpoint` / `restore_legacy_checkpoint`, `acquire_service<I>()`, hardened `Orchestrator` `StopOnFault`/`BoundedRestart` & `FsmModel::~FsmModel()` worker join), `FsmOnly` consumer (`ef5312c`, `40b579d`, `cb988fa`) | [M-FSM-01-05](tasks/M-FSM-01-05.md) | VERIFIED | Standalone `Fsm;Testing` 814 ✔ / 2 skips (`789.1ms`), `ctest` 2/2 (`9.59s`), Debug TSan 1,107 ✔ (0 races, `internal_FsmServiceHotReload` 4/4), full RelWithDebInfo (`1,434 ✔`, `ctest` 2/2 `77.11s`), ASan+UBSan (`1,434 ✔`, 0 leaks/UB) |
## VoidBuildSystem Upstream Requests (`VL-001`..`VL-013`, `feat/upstream-vbs-requests`)
| ID | Deliverable | Spec | State | Verification summary |
| --- | --- | --- | --- | --- |
| VL-002, VL-008, VL-009, VL-012, VL-013 | `Data/Toml.hpp` (TOML 1.0 parser/serializer + `Origin`), strict RFC 3629/8259 UTF-8 in `StrictJson`, zero-CMake self-registering `VOID_TEST*` macros, `Semver` shorthand comparators (`^1`, `^1.0`, `~1.2`, `>=1.2 <2`), `PascalCase`/`snake_case` naming (`VL-012`), `kNetErrorDomain = 26` (`adfc854`) | — | VERIFIED | Standalone `Data;Text;Testing` `-Werror` `687 ✔ / 3 ⊘` (`351.9ms`); pure `g++` zero-CMake multi-file stem collision binary `4/4` (`0.1ms`), `--list`, `--filter from_dir_b` `1/1`; full RelWithDebInfo (`1,452 ✔`), ASan+UBSan (`0` leaks/UB), TSan (`954 ✔`, `0` races) |
| VL-001, VL-003, VL-010, VL-011 | Process-group supervision (`PR_SET_CHILD_SUBREAPER`, `waitpid(-pgid)`, leader-exit `SIGKILL` escalation), `FileLock` / `atomic_symlink_swap` / `reflink_copy_file` / `set_timestamps_nofollow`, Linux `inotify` recursive `DirectoryWatcher`, `Argparse` subcommands/`option_many`/`positional_many`/`ParseOutcome`, top-level `LANGUAGES C CXX` & FetchContent SQLite3 amalgamation (`b50131f`) | — | VERIFIED | Standalone `/tmp/void-vbs-b` `-Werror` `788 ✔ / 3 ⊘` (`1.72s`), `ctest` `2/2` (`14.44s`, incl. `SystemOnly`, `ConfigurationOnly`, `SqliteOnly`); full RelWithDebInfo (`1,452 ✔`), ASan+UBSan (`0` leaks/UB), TSan (`954 ✔`, `0` races) |
| VL-006, VL-007 | Optional `OpenSSL::Crypto` (`VOID_CRYPTO_HAS_OPENSSL`) + pure-C++ FIPS 180-4 SHA-1/256/512 & RFC 7693 BLAKE2b-256/512 + HMAC/HKDF + `snake_case` hash aliases (`22c8538`); optional `LibArchive` (`VOID_ARCHIVE_HAS_LIBARCHIVE`) + pure-C++ USTAR/PAX tar & deterministic `ArchiveCompression::Gzip` + `create()` (`22c8538`) | — | VERIFIED | Zero-OpenSSL `534 ✔ / 3 ⊘` (`1.09s`, `ctest` `2/2` `5.59s`); zero-LibArchive `405 ✔ / 3 ⊘` (`1.45s`, `ctest` `2/2` `6.22s`); full-backend `888 ✔ / 3 ⊘` (`3.70s`, `ctest` `2/2` `15.53s`); full RelWithDebInfo (`1,452 ✔`), ASan+UBSan (`0` leaks/UB), TSan (`954 ✔`, `0` races) |
| VL-004, VL-005 | POSIX TCP HTTP/1.1 `HttpServer` (`query`, `file_body`/`from_file`, `Router::allowed_methods`, `bound_port`, `431`/`413`, TE+CL smuggling `400`, streaming `BodyReader`, `HEAD`->`GET`, `shutdown`), streaming `HttpClient` + `HttpClient::secure()` TLS >= 1.2 + CA/SAN + cross-origin/downgrade/redaction + `NetErrorCode` (`kNetErrorDomain = 26`) + `std::stop_token` + `NetOnly` consumer (`66baae7`) + TSan `-Wno-tsan` scope & `StallServer` fix (`9920bfd`) | — | VERIFIED | Standalone `Net;System;Crypto;Testing` `563 ✔ / 3 ⊘` (`2.36s`), `ctest` `2/2` (`8.48s` incl. `NetOnly`); Debug TSan `954 ✔ / 3 ⊘` (`10.65s`, `0` races); full RelWithDebInfo `1,452 ✔ / 4 ⊘` (`22.09s`), `ctest` `2/2` (`82.82s`, `35` consumers); ASan+UBSan `1,452 ✔` (`39.11s`) + `Http\|Net\|Server` `9/9` (`1.58s`, `0` leaks/UB) |
All workers share the checkout and have disjoint file ownership defined in their All workers share the checkout and have disjoint file ownership defined in their
persisted task specifications. Root owns all cross-cutting files and resolves contract persisted task specifications. Root owns all cross-cutting files and resolves contract
changes. No worker owns application code, build files, existing docs/short-url.md, or Git changes. No worker owns application code, build files, existing docs/short-url.md, or Git
+10
View File
@@ -281,3 +281,13 @@ Branch: `feat/roadmap-p2-wave6b` (branched from `main` at `acd77ee`). Toolchain
| Wave 8 integrated RelWithDebInfo + consumers (`cb988fa`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` RelWithDebInfo (`-Werror`, `/tmp/void-w8-full`), 45 modules, `VoidTests` + `ctest` | **PASSED**: `1,437` discovered (`1,434 ✔`, `3 ⊘` skipped, `0 ✘`) in `20.99s`; `ctest` `2/2` in `77.11s` (`VoidTests` `20.97s`, all `34` installed consumers `56.13s`) | | Wave 8 integrated RelWithDebInfo + consumers (`cb988fa`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` RelWithDebInfo (`-Werror`, `/tmp/void-w8-full`), 45 modules, `VoidTests` + `ctest` | **PASSED**: `1,437` discovered (`1,434 ✔`, `3 ⊘` skipped, `0 ✘`) in `20.99s`; `ctest` `2/2` in `77.11s` (`VoidTests` `20.97s`, all `34` installed consumers `56.13s`) |
| Wave 8 full Debug ASan+UBSan (`cb988fa`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug ASan+UBSan (`-Werror`, `/tmp/void-w8-asan`, `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1`, `UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1`), 45 modules | **PASSED**: `1,437` discovered (`1,434 ✔`, `3 ⊘` skipped, `0 ✘`) in `37.13s`, `0` leaks, `0` UB | | Wave 8 full Debug ASan+UBSan (`cb988fa`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug ASan+UBSan (`-Werror`, `/tmp/void-w8-asan`, `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1`, `UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1`), 45 modules | **PASSED**: `1,437` discovered (`1,434 ✔`, `3 ⊘` skipped, `0 ✘`) in `37.13s`, `0` leaks, `0` UB |
| Post-W8 Benchmark (`cb988fa`, `rev=cb988fa98509`) | `/tmp/void-w8-full/benchmarks/VoidFoundationBench --json /tmp/void-w8-full/post-w8.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.38ns, `core_uuid_parse_hyphenated` 24.71ns, `core_uuid_to_string` 16.45ns, `core_hash_fnv1a64_256b` 179.94ns, `core_hash_murmur3_256b` 67.31ns, `functional_result_ok_chain` 1.12ns, `functional_error_with_context` 57.98ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.72ns, `containers_lru_get_put` 20.58ns, `binary_reader_u64_be` 1.30ns, `data_json_parse_small_object` 319.62ns, `data_json_serialize_small_object` 167.55ns | | Post-W8 Benchmark (`cb988fa`, `rev=cb988fa98509`) | `/tmp/void-w8-full/benchmarks/VoidFoundationBench --json /tmp/void-w8-full/post-w8.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.38ns, `core_uuid_parse_hyphenated` 24.71ns, `core_uuid_to_string` 16.45ns, `core_hash_fnv1a64_256b` 179.94ns, `core_hash_murmur3_256b` 67.31ns, `functional_result_ok_chain` 1.12ns, `functional_error_with_context` 57.98ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.72ns, `containers_lru_get_put` 20.58ns, `binary_reader_u64_be` 1.30ns, `data_json_parse_small_object` 319.62ns, `data_json_serialize_small_object` 167.55ns |
| Batch A `VL-002`/`008`/`009`/`012`/`013` (`adfc854`) | `dev cpp-gcc -c` RelWithDebInfo (`-Werror`, `/tmp/void-vbs-a`, `Data;Text;Testing`) + pure `g++` zero-CMake multi-file stem collision binary (`tests/package/TestingNativeGxx/{dir_a,dir_b}/dup.cpp`) | **PASSED**: `VoidTests` `690 tests` (`687 ✔`, `3 ⊘`, `0 ✘`) in `351.9ms`; pure `g++` `4/4` (`0.1ms`), `--list`, `--filter from_dir_b` `1/1` |
| Batch B `VL-001`/`003`/`010`/`011` (`b50131f`) | `dev cpp-gcc -c` RelWithDebInfo (`-Werror`, `/tmp/void-vbs-b`, FetchContent SQLite3 amalgamation), `VoidTests` + `ctest` | **PASSED**: `VoidTests` `791 tests` (`788 ✔`, `3 ⊘`, `0 ✘`) in `1.72s`; `ctest` `2/2` in `14.44s` (`VoidTests` `1.76s`, `VoidInstalledComponentConsumers` `12.68s` incl. `SystemOnly`, `ConfigurationOnly`, `SqliteOnly`) |
| Batch C zero-OpenSSL `VL-007` (`22c8538`) | `dev cpp-gcc -c` RelWithDebInfo (`-Werror`, `/tmp/void-vbs-no-openssl`, `-DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE`, `Crypto;System;Text;Testing`) | **PASSED**: `VoidTests` `537 tests` (`534 ✔`, `3 ⊘`, `0 ✘`) in `1.09s`; `ctest` `2/2` in `5.59s` incl. `CryptoOnly` |
| Batch C zero-LibArchive `VL-006` (`22c8538`) | `dev cpp-gcc -c` RelWithDebInfo (`-Werror`, `/tmp/void-vbs-no-libarchive`, `-DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE`, `Archive;Testing`) | **PASSED**: `VoidTests` `408 tests` (`405 ✔`, `3 ⊘`, `0 ✘`) in `1.45s`; `ctest` `2/2` in `6.22s` incl. `ArchiveOnly` |
| Batch C full backends `VL-006`/`007` (`22c8538`) | `dev cpp-gcc -p libarchive -p openssl -c` RelWithDebInfo (`-Werror`, `/tmp/void-vbs-c`, `Crypto;CryptoAsync;Archive;Update;Testing`) | **PASSED**: `VoidTests` `891 tests` (`888 ✔`, `3 ⊘`, `0 ✘`) in `3.70s`; `ctest` `2/2` in `15.53s` incl. `CryptoOnly`, `CryptoAsyncOnly`, `ArchiveOnly`, `UpdateOnly`, `Audited` |
| Batch D `VL-004`/`005` (`66baae7`) | `dev cpp-gcc -p openssl -c` RelWithDebInfo (`-Werror`, `/tmp/void-vbs-d`, `Net;System;Crypto;Testing`) | **PASSED**: `VoidTests` `566 tests` (`563 ✔`, `3 ⊘`, `0 ✘`) in `2.36s`; `ctest` `2/2` in `8.48s` (`VoidTests` `2.39s`, `VoidInstalledComponentConsumers` `6.09s` incl. `NetOnly`) |
| Integrated RelWithDebInfo + consumers (`66baae7`, `9920bfd`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` RelWithDebInfo (`-Werror`, `/tmp/void-vbs-full`), 45 modules, `VoidTests` + `ctest` | **PASSED**: `1,456` discovered (`1,452 ✔`, `4 ⊘`, `0 ✘`) in `21.94s`; `ctest` `2/2` in `82.82s` (`VoidTests` `22.03s`, `VoidInstalledComponentConsumers` `60.79s` across all `35` consumers incl. `NetOnly`); post-`9920bfd` rebuild `VoidTests` `1,456` (`1,452 ✔`, `4 ⊘`) in `22.09s` |
| Full Debug ASan+UBSan (`66baae7`, `9920bfd`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug ASan+UBSan (`-Werror`, `/tmp/void-vbs-asan`, `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1`, `UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1`), 45 modules | **PASSED**: `1,456` discovered (`1,452 ✔`, `4 ⊘`, `0 ✘`) in `39.11s`, `0` leaks, `0` UB; post-`9920bfd` incremental `--filter 'Http\|Net\|Server'` `9/9 ✔` in `1.58s` |
| Debug TSan (`9920bfd`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug TSan (`-Werror`, `/tmp/void-vbs-tsan`, `TSAN_OPTIONS=halt_on_error=1:second_deadlock_stack=1`), 17 modules (`Net;System;SystemAsync;Configuration;Crypto;Archive;Data;Text;Testing`) | **PASSED**: `957` discovered (`954 ✔`, `3 ⊘`, `0 ✘`) in `10.65s`, `0` data races, `0` lock-order warnings |
| Post-VBS Benchmark (`66baae7`, `rev=66baae74a0b7`) | `/tmp/void-vbs-full/benchmarks/VoidFoundationBench --json /tmp/void-vbs-full/post-vbs.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.40ns, `core_uuid_parse_hyphenated` 26.35ns, `core_uuid_to_string` 18.33ns, `core_hash_fnv1a64_256b` 185.86ns, `core_hash_murmur3_256b` 69.58ns, `functional_result_ok_chain` 1.16ns, `functional_error_with_context` 59.59ns, `math_checked_add_loop` 0.48ns, `containers_spsc_ring_push_pop` 8.97ns, `containers_lru_get_put` 21.17ns, `binary_reader_u64_be` 1.34ns, `data_json_parse_small_object` 316.05ns, `data_json_serialize_small_object` 174.83ns |
+21 -6
View File
@@ -29,9 +29,14 @@ namespace Void::Archive
std::uint64_t bytes{0}; std::uint64_t bytes{0};
}; };
/// Extract a tar/tar.zst archive incrementally into `destination` without /// Returns true if Void::Archive was built with LibArchive support (required
/// invoking an external process. Preserved 1.x incremental API; callers /// for .tar.zst and .tar.gz compression/decompression; uncompressed USTAR/PAX
/// requiring all-or-nothing directory visibility should use /// .tar reading and writing work with zero external dependencies).
[[nodiscard]] bool has_libarchive_backend() noexcept;
/// Extract a tar/tar.gz/tar.zst archive incrementally into `destination`
/// without invoking an external process. Preserved 1.x incremental API;
/// callers requiring all-or-nothing directory visibility should use
/// `extract_staged` + `StagedTree::publish`. /// `extract_staged` + `StagedTree::publish`.
[[nodiscard]] Void::Result::Result<ExtractionResult> [[nodiscard]] Void::Result::Result<ExtractionResult>
extract(const std::filesystem::path& archivePath, extract(const std::filesystem::path& archivePath,
@@ -177,9 +182,9 @@ namespace Void::Archive
std::chrono::seconds min_age = std::chrono::seconds min_age =
std::chrono::seconds{300}); std::chrono::seconds{300});
/// Create a bounded, optionally reproducible tar or tar.zst archive from /// Create a bounded, optionally reproducible tar, tar.gz, or tar.zst
/// regular file and directory entries. Sorts normalized paths, rejects /// archive from regular file and directory entries. Sorts normalized
/// duplicates/conflicts, and opens source files with O_NOFOLLOW. /// paths, rejects duplicates/conflicts, and opens source files with O_NOFOLLOW.
[[nodiscard]] Void::Result::Result<void> [[nodiscard]] Void::Result::Result<void>
create_archive(ByteSink& sink, std::span<const CreateEntry> entries, create_archive(ByteSink& sink, std::span<const CreateEntry> entries,
const CreationOptions& options = {}); const CreationOptions& options = {});
@@ -189,6 +194,16 @@ namespace Void::Archive
std::span<const CreateEntry> entries, std::span<const CreateEntry> entries,
const CreationOptions& options = {}); const CreationOptions& options = {});
/// Canonical snake_case alias for `create_archive`.
[[nodiscard]] Void::Result::Result<void>
create(ByteSink& sink, std::span<const CreateEntry> entries,
const CreationOptions& options = {});
[[nodiscard]] Void::Result::Result<void>
create(const std::filesystem::path& output_path,
std::span<const CreateEntry> entries,
const CreationOptions& options = {});
/// Hardened untrusted-input profile: extracts the archive in an isolated /// Hardened untrusted-input profile: extracts the archive in an isolated
/// System child process with bounded execution time and RSS checks, then /// System child process with bounded execution time and RSS checks, then
/// independently verifies the staged tree and inventory in the parent /// independently verifies the staged tree and inventory in the parent
+6 -1
View File
@@ -175,13 +175,17 @@ namespace Void::Archive
ProgressCallback on_progress{}; ProgressCallback on_progress{};
}; };
enum class ArchiveCompression : std::uint8_t { None = 0, Zstd }; enum class ArchiveCompression : std::uint8_t { None = 0, Zstd, Gzip };
struct CreationOptions { struct CreationOptions {
ArchiveCompression compression{ArchiveCompression::Zstd}; ArchiveCompression compression{ArchiveCompression::Zstd};
bool reproducible{true}; bool reproducible{true};
ReadLimits limits{}; ReadLimits limits{};
std::stop_token stop{}; std::stop_token stop{};
std::int64_t canonical_mtime{0};
std::uint32_t canonical_uid{0};
std::uint32_t canonical_gid{0};
bool prefer_builtin_tar{false};
}; };
struct CreateEntry { struct CreateEntry {
@@ -190,6 +194,7 @@ namespace Void::Archive
bool executable{false}; bool executable{false};
std::vector<std::byte> content{}; std::vector<std::byte> content{};
std::optional<std::filesystem::path> source_file{}; std::optional<std::filesystem::path> source_file{};
std::optional<std::uint32_t> mode{};
}; };
struct IsolationOptions { struct IsolationOptions {
+85 -5
View File
@@ -2,7 +2,10 @@
#include <Void/Core/Meta.hpp> #include <Void/Core/Meta.hpp>
#include <cstdint>
#include <expected> #include <expected>
#include <functional>
#include <memory>
#include <optional> #include <optional>
#include <string> #include <string>
#include <string_view> #include <string_view>
@@ -11,23 +14,56 @@
namespace Void::Argparse namespace Void::Argparse
{ {
enum class ParseOutcome : std::uint8_t {
Ok,
Help,
Error,
};
struct ParseResult {
ParseOutcome outcome{ParseOutcome::Ok};
std::string message{};
std::vector<std::string> matched_command_path{};
[[nodiscard]] bool ok() const noexcept
{
return outcome == ParseOutcome::Ok;
}
[[nodiscard]] bool is_help() const noexcept
{
return outcome == ParseOutcome::Help;
}
[[nodiscard]] bool is_error() const noexcept
{
return outcome == ParseOutcome::Error;
}
};
// ── Parser // ── Parser
// ──────────────────────────────────────────────────────────────────── // ────────────────────────────────────────────────────────────────────
// Fluent command-line argument parser. // Fluent command-line argument parser.
// //
// Supports: // Supports:
// --flag, -f boolean flag (default false, set to true by // --flag, -f boolean flag (default false, set to true by
// presence) // presence)
// --key=value option with value (= or space separator) // --key=value option with value (= or space separator)
// --key value option with value // --key value option with value
// option_many(...) repeatable option collecting all occurrences
// subcommand(...) nested subcommand parsers (e.g. "compdb use")
// positional args collected in declaration order // positional args collected in declaration order
// --help / -h auto-generated help text // --help / -h auto-generated help text (ParseOutcome::Help)
class Parser class Parser
{ {
public: public:
explicit Parser(std::string program, std::string description = {}); explicit Parser(std::string program, std::string description = {});
~Parser();
Parser(const Parser&) = delete;
Parser& operator=(const Parser&) = delete;
Parser(Parser&&) noexcept;
Parser& operator=(Parser&&) noexcept;
// Add a boolean flag. // Add a boolean flag.
// long_name: e.g. "--verbose" short_name: e.g. "-v" (short_name // long_name: e.g. "--verbose" short_name: e.g. "-v" (short_name
@@ -43,6 +79,12 @@ namespace Void::Argparse
std::string_view description, std::string_view description,
std::optional<std::string>& out); std::optional<std::string>& out);
// Add a repeatable option collecting all occurrences into `out`.
Parser& option_many(std::string_view long_name,
std::string_view short_name,
std::string_view description,
std::vector<std::string>& out);
// Add an option with a default value. out is always set after // Add an option with a default value. out is always set after
// parse(). // parse().
Parser& option_default(std::string_view long_name, Parser& option_default(std::string_view long_name,
@@ -55,7 +97,28 @@ namespace Void::Argparse
Parser& positional(std::string_view name, Parser& positional(std::string_view name,
std::string_view description, std::string& out); std::string_view description, std::string& out);
// Parse argc/argv. Returns error message on failure. // Add a variadic trailing positional argument list.
Parser& positional_many(std::string_view name,
std::string_view description,
std::vector<std::string>& out,
bool required = false);
// Register a nested subcommand and return a reference to its
// Parser. The returned reference remains valid for the lifetime of
// the parent Parser.
Parser& subcommand(std::string name, std::string description = {},
std::function<void()> on_selected = {});
// Control whether a parser with subcommands requires one to be
// selected (default: true when any subcommand is registered).
Parser& require_subcommand(bool required = true) noexcept;
// Parse argc/argv with explicit Ok / Help / Error classification.
[[nodiscard]] ParseResult
parse_detailed(int argc, const char* const* argv) const;
// Parse argc/argv. Returns error message (or help text) on
// non-Ok outcome for 1.x compatibility.
[[nodiscard]] std::expected<void, std::string> [[nodiscard]] std::expected<void, std::string>
parse(int argc, const char* const* argv) const; parse(int argc, const char* const* argv) const;
@@ -70,18 +133,33 @@ namespace Void::Argparse
}; };
struct OptionEntry { struct OptionEntry {
std::string lng, sht, desc, def; std::string lng, sht, desc, def;
std::optional<std::string>* out_opt; std::optional<std::string>* out_opt{nullptr};
std::string* out_str; std::string* out_str{nullptr};
std::vector<std::string>* out_many{nullptr};
}; };
struct PosEntry { struct PosEntry {
std::string name, desc; std::string name, desc;
std::string* out; std::string* out;
}; };
struct MultiPosEntry {
std::string name, desc;
std::vector<std::string>* out{nullptr};
bool required{false};
};
struct SubcommandEntry {
std::string name;
std::unique_ptr<Parser> parser;
std::function<void()> on_selected;
};
std::string program_, description_; std::string program_, description_;
std::vector<FlagEntry> flags_; std::vector<FlagEntry> flags_;
std::vector<OptionEntry> options_; std::vector<OptionEntry> options_;
std::vector<PosEntry> positionals_; std::vector<PosEntry> positionals_;
std::optional<MultiPosEntry> positional_many_;
std::vector<SubcommandEntry> subcommands_;
bool has_explicit_require_sub_{false};
bool require_subcommand_{true};
}; };
// ── reflective options struct // ── reflective options struct
@@ -147,6 +225,8 @@ namespace Void::Argparse
parser.flag(lng, sht, desc, out.[:m:]); parser.flag(lng, sht, desc, out.[:m:]);
} else if constexpr (Void::Meta::is_optional_v<MT>) { } else if constexpr (Void::Meta::is_optional_v<MT>) {
parser.option(lng, sht, desc, out.[:m:]); parser.option(lng, sht, desc, out.[:m:]);
} else if constexpr (std::same_as<MT, std::vector<std::string>>) {
parser.option_many(lng, sht, desc, out.[:m:]);
} else if constexpr (std::same_as<MT, std::string>) { } else if constexpr (std::same_as<MT, std::string>) {
const std::string def = out.[:m:]; const std::string def = out.[:m:];
parser.option_default(lng, sht, desc, out.[:m:], def); parser.option_default(lng, sht, desc, out.[:m:], def);
+28 -1
View File
@@ -13,9 +13,14 @@
namespace Void::Crypto namespace Void::Crypto
{ {
enum class HashAlgorithm { Sha1, Sha256, Sha512 }; enum class HashAlgorithm { Sha1, Sha256, Sha512, Blake2b256, Blake2b512 };
using Digest = std::vector<std::byte>; using Digest = std::vector<std::byte>;
/// Returns true if Void::Crypto was built with OpenSSL support (required
/// for Ed25519; hashing/HMAC/HKDF work on the built-in pure-C++ backend
/// with zero external dependencies).
[[nodiscard]] bool has_openssl_backend() noexcept;
class Hasher class Hasher
{ {
public: public:
@@ -60,6 +65,11 @@ namespace Void::Crypto
[[nodiscard]] Void::Result::Result<Digest> [[nodiscard]] Void::Result::Result<Digest>
hashFile(HashAlgorithm algorithm, const std::filesystem::path& path, hashFile(HashAlgorithm algorithm, const std::filesystem::path& path,
const ProviderOptions& provider); const ProviderOptions& provider);
[[nodiscard]] Void::Result::Result<Digest>
hash_file(HashAlgorithm algorithm, const std::filesystem::path& path);
[[nodiscard]] Void::Result::Result<Digest>
hash_file(HashAlgorithm algorithm, const std::filesystem::path& path,
const ProviderOptions& provider);
[[nodiscard]] Void::Result::Result<Digest> [[nodiscard]] Void::Result::Result<Digest>
sha1(std::span<const std::byte> data); sha1(std::span<const std::byte> data);
@@ -70,12 +80,29 @@ namespace Void::Crypto
[[nodiscard]] Void::Result::Result<Digest> [[nodiscard]] Void::Result::Result<Digest>
sha512(std::span<const std::byte> data); sha512(std::span<const std::byte> data);
[[nodiscard]] Void::Result::Result<Digest> sha512(std::string_view data); [[nodiscard]] Void::Result::Result<Digest> sha512(std::string_view data);
[[nodiscard]] Void::Result::Result<Digest>
blake2b256(std::span<const std::byte> data);
[[nodiscard]] Void::Result::Result<Digest> blake2b256(std::string_view data);
[[nodiscard]] Void::Result::Result<Digest>
blake2b512(std::span<const std::byte> data);
[[nodiscard]] Void::Result::Result<Digest> blake2b512(std::string_view data);
[[nodiscard]] Void::Result::Result<Digest> [[nodiscard]] Void::Result::Result<Digest>
sha1File(const std::filesystem::path& path); sha1File(const std::filesystem::path& path);
[[nodiscard]] Void::Result::Result<Digest> [[nodiscard]] Void::Result::Result<Digest>
sha256File(const std::filesystem::path& path); sha256File(const std::filesystem::path& path);
[[nodiscard]] Void::Result::Result<Digest> [[nodiscard]] Void::Result::Result<Digest>
sha512File(const std::filesystem::path& path); sha512File(const std::filesystem::path& path);
[[nodiscard]] Void::Result::Result<Digest>
sha1_file(const std::filesystem::path& path);
[[nodiscard]] Void::Result::Result<Digest>
sha256_file(const std::filesystem::path& path);
[[nodiscard]] Void::Result::Result<Digest>
sha512_file(const std::filesystem::path& path);
[[nodiscard]] Void::Result::Result<Digest>
blake2b256_file(const std::filesystem::path& path);
[[nodiscard]] Void::Result::Result<Digest>
blake2b512_file(const std::filesystem::path& path);
/// Move-only owning Ed25519 private key handle. Has no implicit copy, /// Move-only owning Ed25519 private key handle. Has no implicit copy,
/// string conversion, or secret formatting. /// string conversion, or secret formatting.
+2 -1
View File
@@ -111,10 +111,11 @@ namespace Void::Crypto
MovedFrom MovedFrom
}; };
/// Per-operation OpenSSL 3 provider selection. Never mutates process-wide /// Per-operation backend/provider selection. Never mutates process-wide
/// provider state. /// provider state.
struct ProviderOptions { struct ProviderOptions {
std::string property_query{}; std::string property_query{};
bool prefer_builtin{false};
}; };
struct Ed25519PublicKey { struct Ed25519PublicKey {
+246
View File
@@ -1,5 +1,6 @@
#pragma once #pragma once
#include <array>
#include <charconv> #include <charconv>
#include <cmath> #include <cmath>
#include <cstddef> #include <cstddef>
@@ -41,6 +42,72 @@ namespace Void::Json::Strict
ParseError error; ParseError error;
}; };
[[nodiscard]] constexpr std::size_t
validate_utf8_at(const std::string_view input,
const std::size_t pos) noexcept
{
if (pos >= input.size()) {
return 0U;
}
const auto b0 = static_cast<unsigned char>(input[pos]);
if (b0 <= 0x7FU) {
return 1U;
}
if (b0 >= 0xC2U && b0 <= 0xDFU) {
if (pos + 1U >= input.size()) {
return 0U;
}
const auto b1 = static_cast<unsigned char>(input[pos + 1U]);
return (b1 >= 0x80U && b1 <= 0xBFU) ? 2U : 0U;
}
if (b0 >= 0xE0U && b0 <= 0xEFU) {
if (pos + 2U >= input.size()) {
return 0U;
}
const auto b1 = static_cast<unsigned char>(input[pos + 1U]);
const auto b2 = static_cast<unsigned char>(input[pos + 2U]);
const unsigned char lo = (b0 == 0xE0U) ? 0xA0U : 0x80U;
const unsigned char hi = (b0 == 0xEDU) ? 0x9FU : 0xBFU;
if (b1 < lo || b1 > hi || b2 < 0x80U || b2 > 0xBFU) {
return 0U;
}
return 3U;
}
if (b0 >= 0xF0U && b0 <= 0xF4U) {
if (pos + 3U >= input.size()) {
return 0U;
}
const auto b1 = static_cast<unsigned char>(input[pos + 1U]);
const auto b2 = static_cast<unsigned char>(input[pos + 2U]);
const auto b3 = static_cast<unsigned char>(input[pos + 3U]);
const unsigned char lo = (b0 == 0xF0U) ? 0x90U : 0x80U;
const unsigned char hi = (b0 == 0xF4U) ? 0x8FU : 0xBFU;
if (b1 < lo || b1 > hi || b2 < 0x80U || b2 > 0xBFU ||
b3 < 0x80U || b3 > 0xBFU) {
return 0U;
}
return 4U;
}
return 0U;
}
[[nodiscard]] inline std::expected<void, ParseError>
validate_utf8_bytes(const std::string_view input)
{
std::size_t pos = 0U;
while (pos < input.size()) {
const std::size_t len = validate_utf8_at(input, pos);
if (len == 0U) {
return std::unexpected{ParseError{
.offset = pos,
.message = "invalid UTF-8 sequence",
}};
}
pos += len;
}
return {};
}
class Parser final class Parser final
{ {
public: public:
@@ -179,6 +246,18 @@ namespace Void::Json::Strict
fail("control character in string"); fail("control character in string");
} }
if (value != '\\') { if (value != '\\') {
if (value >= 0x80U) {
const std::size_t seq_start = position_ - 1U;
const std::size_t len =
validate_utf8_at(input_, seq_start);
if (len == 0U) {
position_ = seq_start;
fail("invalid UTF-8 sequence");
}
output.append(input_.substr(seq_start, len));
position_ = seq_start + len;
continue;
}
output.push_back(static_cast<char>(value)); output.push_back(static_cast<char>(value));
continue; continue;
} }
@@ -435,4 +514,171 @@ namespace Void::Json::Strict
.allowDecimals = true}); .allowDecimals = true});
} }
[[nodiscard]] inline bool is_valid_utf8(const std::string_view input) noexcept
{
std::size_t pos = 0U;
while (pos < input.size()) {
const std::size_t len = Detail::validate_utf8_at(input, pos);
if (len == 0U) {
return false;
}
pos += len;
}
return true;
}
[[nodiscard]] inline std::expected<void, ParseError>
validate_utf8(const std::string_view input)
{
return Detail::validate_utf8_bytes(input);
}
namespace Detail
{
inline void append_escaped_string(std::string& out,
const std::string_view text)
{
const auto utf8 = validate_utf8_bytes(text);
if (!utf8.has_value()) {
throw ParseFailure{.error = utf8.error()};
}
out.push_back('"');
std::size_t pos = 0U;
while (pos < text.size()) {
const auto ch = static_cast<unsigned char>(text[pos]);
switch (ch) {
case '"':
out += "\\\"";
++pos;
break;
case '\\':
out += "\\\\";
++pos;
break;
case '\b':
out += "\\b";
++pos;
break;
case '\f':
out += "\\f";
++pos;
break;
case '\n':
out += "\\n";
++pos;
break;
case '\r':
out += "\\r";
++pos;
break;
case '\t':
out += "\\t";
++pos;
break;
default:
if (ch < 0x20U) {
static constexpr char kHex[] = "0123456789abcdef";
out += "\\u00";
out.push_back(kHex[(ch >> 4U) & 0x0FU]);
out.push_back(kHex[ch & 0x0FU]);
++pos;
} else if (ch >= 0x80U) {
const std::size_t len = validate_utf8_at(text, pos);
out.append(text.substr(pos, len));
pos += len;
} else {
out.push_back(static_cast<char>(ch));
++pos;
}
break;
}
}
out.push_back('"');
}
inline void serialize_value(std::string& out, const Value& val,
const std::size_t depth,
const std::size_t maximumDepth)
{
if (depth > maximumDepth) {
throw ParseFailure{
.error =
{
.offset = out.size(),
.message = "nesting limit exceeded during serialize",
},
};
}
std::visit(
[&](const auto& node) {
using T = std::decay_t<decltype(node)>;
if constexpr (std::same_as<T, std::nullptr_t>) {
out += "null";
} else if constexpr (std::same_as<T, bool>) {
out += (node ? "true" : "false");
} else if constexpr (std::same_as<T, std::int64_t>) {
std::array<char, 32> buf{};
const auto res = std::to_chars(
buf.data(), buf.data() + buf.size(), node);
out.append(buf.data(), res.ptr);
} else if constexpr (std::same_as<T, double>) {
if (!std::isfinite(node)) {
throw ParseFailure{
.error =
{
.offset = out.size(),
.message =
"non-finite double is not valid JSON",
},
};
}
std::array<char, 64> buf{};
const auto res = std::to_chars(
buf.data(), buf.data() + buf.size(), node,
std::chars_format::general);
out.append(buf.data(), res.ptr);
} else if constexpr (std::same_as<T, std::string>) {
append_escaped_string(out, node);
} else if constexpr (std::same_as<T, Value::Array>) {
out.push_back('[');
for (std::size_t i = 0; i < node.size(); ++i) {
if (i > 0U) {
out.push_back(',');
}
serialize_value(out, node[i], depth + 1U,
maximumDepth);
}
out.push_back(']');
} else if constexpr (std::same_as<T, Value::Object>) {
out.push_back('{');
bool first = true;
for (const auto& [k, v] : node) {
if (!first) {
out.push_back(',');
}
first = false;
append_escaped_string(out, k);
out.push_back(':');
serialize_value(out, v, depth + 1U, maximumDepth);
}
out.push_back('}');
}
},
val.value);
}
} // namespace Detail
[[nodiscard]] inline std::expected<std::string, ParseError>
serialize(const Value& value,
const std::size_t maximumDepth = default_maximum_depth)
{
try {
std::string out;
Detail::serialize_value(out, value, 0U, maximumDepth);
return out;
} catch (const Detail::ParseFailure& failure) {
return std::unexpected{failure.error};
}
}
} // namespace Void::Json::Strict } // namespace Void::Json::Strict
File diff suppressed because it is too large. Load diff
+1
View File
@@ -75,6 +75,7 @@ namespace Void::Result
inline constexpr std::uint32_t kPluginErrorDomain = 23; inline constexpr std::uint32_t kPluginErrorDomain = 23;
inline constexpr std::uint32_t kConfigurationErrorDomain = 24; inline constexpr std::uint32_t kConfigurationErrorDomain = 24;
inline constexpr std::uint32_t kFsmErrorDomain = 25; inline constexpr std::uint32_t kFsmErrorDomain = 25;
inline constexpr std::uint32_t kNetErrorDomain = 26;
struct ErrorCode { struct ErrorCode {
std::uint32_t domain{kGenericErrorDomain}; std::uint32_t domain{kGenericErrorDomain};
+182 -2
View File
@@ -4,13 +4,79 @@
#include <Void/Functional/Result.hpp> #include <Void/Functional/Result.hpp>
#include <chrono> #include <chrono>
#include <cstddef>
#include <cstdint> #include <cstdint>
#include <filesystem>
#include <functional>
#include <optional> #include <optional>
#include <span>
#include <stop_token>
#include <string> #include <string>
#include <string_view>
#include <system_error>
#include <vector> #include <vector>
namespace Void::Net namespace Void::Net
{ {
enum class NetErrorCode : std::int32_t {
none = 0,
invalid_url = 1,
invalid_argument = 2,
connect_failed = 3,
tls_error = 4,
protocol_error = 5,
timeout = 6,
cancelled = 7,
quota_exceeded = 8,
io_error = 9,
redirect_blocked = 10,
payload_too_large = 11,
headers_too_large = 12
};
[[nodiscard]] inline Void::Result::Error
make_net_error(NetErrorCode code, std::string message = {},
std::error_code sys_err = {})
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case NetErrorCode::none:
kind = ErrorKind::internal;
break;
case NetErrorCode::invalid_url:
case NetErrorCode::invalid_argument:
case NetErrorCode::redirect_blocked:
kind = ErrorKind::invalid_argument;
break;
case NetErrorCode::connect_failed:
case NetErrorCode::io_error:
kind = ErrorKind::io;
break;
case NetErrorCode::tls_error:
case NetErrorCode::protocol_error:
kind = ErrorKind::corrupt;
break;
case NetErrorCode::timeout:
kind = ErrorKind::timeout;
break;
case NetErrorCode::cancelled:
kind = ErrorKind::cancelled;
break;
case NetErrorCode::quota_exceeded:
case NetErrorCode::payload_too_large:
case NetErrorCode::headers_too_large:
kind = ErrorKind::exhausted;
break;
}
return Error{kind, std::move(message),
ErrorCode{Void::Result::kNetErrorDomain,
static_cast<std::int32_t>(code)},
sys_err};
}
enum class Method { Get, Post, Put, Delete, Patch, Head, Options }; enum class Method { Get, Post, Put, Delete, Patch, Head, Options };
@@ -62,6 +128,54 @@ namespace Void::Net
} }
}; };
struct HttpClientOptions {
ProxyConfig proxy{};
std::string user_agent{"Void.Net/1.0"};
bool verify_tls{true};
std::string ca_file{};
std::uint64_t max_body_size{64ULL * 1024 * 1024};
int max_redirects{0};
bool allow_insecure_redirects{false};
};
struct TransferProgress {
std::uint64_t bytes_transferred{0};
std::optional<std::uint64_t> total_bytes{};
};
struct DownloadOptions {
std::vector<Header> headers{};
std::chrono::seconds timeout{30};
std::uint64_t max_bytes{0};
std::stop_token stop{};
std::function<void(std::span<const std::byte>)> on_chunk{};
std::function<void(const TransferProgress&)> on_progress{};
};
struct DownloadResult {
std::uint16_t status{0};
std::vector<Header> headers{};
std::uint64_t bytes_written{0};
std::chrono::milliseconds elapsed{0};
[[nodiscard]] bool ok() const noexcept
{
return status >= 200 && status < 300;
}
[[nodiscard]] std::optional<std::string_view>
header(std::string_view name) const;
};
struct UploadOptions {
Method method{Method::Put};
std::vector<Header> headers{};
std::string content_type{"application/octet-stream"};
std::chrono::seconds timeout{30};
std::uint64_t max_upload_bytes{0};
std::stop_token stop{};
std::function<void(const TransferProgress&)> on_progress{};
};
/// Synchronous HTTP/HTTPS client built on Boost.Beast/Asio + OpenSSL. /// Synchronous HTTP/HTTPS client built on Boost.Beast/Asio + OpenSSL.
/// Supports direct connections, HTTP-CONNECT and SOCKS5 proxies, and TLS. /// Supports direct connections, HTTP-CONNECT and SOCKS5 proxies, and TLS.
/// Generic: no application-specific defaults beyond a configurable /// Generic: no application-specific defaults beyond a configurable
@@ -73,6 +187,12 @@ namespace Void::Net
HttpClient() = default; HttpClient() = default;
explicit HttpClient(ProxyConfig proxy) : m_proxy(std::move(proxy)) {} explicit HttpClient(ProxyConfig proxy) : m_proxy(std::move(proxy)) {}
explicit HttpClient(HttpClientOptions options);
/// Preset with TLS peer & hostname certificate verification enabled
/// by default (`verify_tls = true`).
[[nodiscard]] static HttpClient
secure(ProxyConfig proxy = {});
void set_proxy(ProxyConfig proxy) { m_proxy = std::move(proxy); } void set_proxy(ProxyConfig proxy) { m_proxy = std::move(proxy); }
[[nodiscard]] const ProxyConfig& proxy() const noexcept [[nodiscard]] const ProxyConfig& proxy() const noexcept
@@ -83,9 +203,33 @@ namespace Void::Net
/// Default User-Agent applied when a request sets none. /// Default User-Agent applied when a request sets none.
void set_user_agent(std::string ua) { m_user_agent = std::move(ua); } void set_user_agent(std::string ua) { m_user_agent = std::move(ua); }
/// Verify TLS peer certificates (default: false, matching common /// Verify TLS peer certificates (default constructor keeps `false`
/// scraping/proxy use; enable for security-sensitive callers). /// for 1.x compatibility; `HttpClient::secure()` defaults `true`).
void set_verify_tls(bool on) noexcept { m_verify_tls = on; } void set_verify_tls(bool on) noexcept { m_verify_tls = on; }
[[nodiscard]] bool verify_tls() const noexcept
{
return m_verify_tls;
}
/// Optional custom PEM CA bundle/certificate file used when
/// `verify_tls` is enabled.
void set_ca_file(std::string ca_file)
{
m_ca_file = std::move(ca_file);
}
[[nodiscard]] const std::string& ca_file() const noexcept
{
return m_ca_file;
}
void set_allow_insecure_redirects(bool allow) noexcept
{
m_allow_insecure_redirects = allow;
}
[[nodiscard]] bool allow_insecure_redirects() const noexcept
{
return m_allow_insecure_redirects;
}
/// Maximum response body size in bytes. 0 means unlimited. Default /// Maximum response body size in bytes. 0 means unlimited. Default
/// is 64 MiB (Beast's own default of ~1 MiB is too small for binary /// is 64 MiB (Beast's own default of ~1 MiB is too small for binary
@@ -100,12 +244,34 @@ namespace Void::Net
/// header). Opt-in so callers that inspect redirects keep working. /// header). Opt-in so callers that inspect redirects keep working.
void set_max_redirects(int n) noexcept { m_max_redirects = n; } void set_max_redirects(int n) noexcept { m_max_redirects = n; }
/// Format request method, scrubbed URL, and headers for logs while
/// redacting `Authorization`, `Proxy-Authorization`, `Cookie`, and
/// `X-Api-Key`.
[[nodiscard]] static std::string
format_request_diagnostics(const Request& req);
/// Execute a request. A per-request `Request::proxy` is not modelled; /// Execute a request. A per-request `Request::proxy` is not modelled;
/// the client-level proxy applies. Returns an Error only on transport /// the client-level proxy applies. Returns an Error only on transport
/// failure — a non-2xx HTTP response is a successful Result. /// failure — a non-2xx HTTP response is a successful Result.
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error> [[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
send(const Request& req) const; send(const Request& req) const;
/// Stream response body directly to `destination` without buffering
/// the full payload in memory, enforcing `options.max_bytes` and
/// `options.stop` cancellation.
[[nodiscard]] Void::Result::Result<DownloadResult,
Void::Result::Error>
download_to_file(std::string_view url,
const std::filesystem::path& destination,
const DownloadOptions& options = {}) const;
/// Stream a regular file directly as the HTTP request body without
/// buffering the full file in memory.
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
upload_file(std::string_view url,
const std::filesystem::path& source_path,
const UploadOptions& options = {}) const;
// Convenience wrappers. // Convenience wrappers.
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error> [[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
get(std::string_view url, get(std::string_view url,
@@ -113,14 +279,28 @@ namespace Void::Net
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error> [[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
post(std::string_view url, std::string body, post(std::string_view url, std::string body,
std::vector<Header> headers = {}) const; std::vector<Header> headers = {}) const;
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
put_file(std::string_view url,
const std::filesystem::path& source_path,
std::vector<Header> headers = {},
std::string content_type =
"application/octet-stream") const;
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
post_file(std::string_view url,
const std::filesystem::path& source_path,
std::vector<Header> headers = {},
std::string content_type =
"application/octet-stream") const;
private: private:
ProxyConfig m_proxy{}; ProxyConfig m_proxy{};
std::string m_user_agent = "Void.Net/1.0"; std::string m_user_agent = "Void.Net/1.0";
bool m_verify_tls = false; bool m_verify_tls = false;
std::string m_ca_file{};
std::uint64_t m_max_body = 64ull * 1024 * 1024; std::uint64_t m_max_body = 64ull * 1024 * 1024;
int m_max_redirects = 0; int m_max_redirects = 0;
bool m_allow_insecure_redirects = false;
}; };
} // namespace Void::Net } // namespace Void::Net
+108
View File
@@ -0,0 +1,108 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <Void/Net/Http.hpp>
#include <Void/Net/Server.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <memory>
#include <optional>
#include <span>
#include <string>
namespace Void::Net
{
struct HttpServerOptions {
std::string bind_host{"127.0.0.1"};
std::uint16_t port{0};
std::size_t max_header_bytes{64ULL * 1024};
std::size_t max_headers{128};
std::uint64_t max_body_bytes{16ULL * 1024 * 1024};
std::uint64_t max_streaming_body_bytes{512ULL * 1024 * 1024};
std::size_t max_concurrent_connections{64};
std::chrono::milliseconds read_timeout{std::chrono::seconds{30}};
std::chrono::milliseconds write_timeout{std::chrono::seconds{30}};
int listen_backlog{128};
};
/// Streaming request body reader passed to streaming HTTP route handlers.
class BodyReader
{
public:
struct State;
explicit BodyReader(State& state) noexcept : m_state(&state) {}
BodyReader(const BodyReader&) = delete;
BodyReader& operator=(const BodyReader&) = delete;
[[nodiscard]] std::optional<std::uint64_t>
content_length() const noexcept;
[[nodiscard]] bool is_chunked() const noexcept;
[[nodiscard]] std::uint64_t bytes_read() const noexcept;
/// Read up to dst.size() decoded body bytes. Returns 0 at EOF.
[[nodiscard]] Void::Result::Result<std::size_t>
read_some(std::span<std::byte> dst);
/// Stream the request body atomically to `destination`, enforcing
/// `max_bytes` (or server max_streaming_body_bytes when 0).
[[nodiscard]] Void::Result::Result<std::uint64_t>
read_to_file(const std::filesystem::path& destination,
std::uint64_t max_bytes = 0);
private:
State* m_state{nullptr};
};
using StreamingRouteHandler =
std::function<RouteResult(const ServerRequest&, BodyReader&)>;
/// Concrete POSIX TCP HTTP/1.1 listener dispatching buffered routes through
/// `Void::Net::Router` and streaming routes via `BodyReader`.
class HttpServer
{
public:
explicit HttpServer(HttpServerOptions options = {});
explicit HttpServer(Router& external_router,
HttpServerOptions options = {});
~HttpServer() noexcept;
HttpServer(HttpServer&&) noexcept;
HttpServer& operator=(HttpServer&&) noexcept;
HttpServer(const HttpServer&) = delete;
HttpServer& operator=(const HttpServer&) = delete;
[[nodiscard]] Router& router() noexcept;
[[nodiscard]] Void::Result::Result<void>
add_route(Method method, std::string pattern,
RouteHandler handler);
[[nodiscard]] Void::Result::Result<void>
add_streaming_route(Method method, std::string pattern,
StreamingRouteHandler handler);
[[nodiscard]] Void::Result::Result<void> start();
void shutdown(std::chrono::milliseconds drain_timeout =
std::chrono::seconds{5}) noexcept;
[[nodiscard]] bool running() const noexcept;
[[nodiscard]] std::uint16_t bound_port() const noexcept;
[[nodiscard]] std::string bind_address() const;
[[nodiscard]] std::string base_url() const;
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
};
} // namespace Void::Net
+10
View File
@@ -30,6 +30,7 @@ namespace Void::Net
std::vector<Header> headers; std::vector<Header> headers;
std::string body; std::string body;
RouteParameters parameters; RouteParameters parameters;
std::string query{};
[[nodiscard]] std::optional<std::string_view> [[nodiscard]] std::optional<std::string_view>
header(std::string_view name) const noexcept; header(std::string_view name) const noexcept;
@@ -39,6 +40,12 @@ namespace Void::Net
std::uint16_t status{200}; std::uint16_t status{200};
std::vector<Header> headers; std::vector<Header> headers;
std::string body; std::string body;
std::optional<std::filesystem::path> file_body{};
[[nodiscard]] static ServerResponse
from_file(std::filesystem::path path,
std::string content_type = {},
std::uint16_t status = 200);
[[nodiscard]] std::optional<std::string_view> [[nodiscard]] std::optional<std::string_view>
header(std::string_view name) const noexcept; header(std::string_view name) const noexcept;
@@ -67,6 +74,9 @@ namespace Void::Net
[[nodiscard]] Void::Result::Result<std::optional<ServerResponse>> [[nodiscard]] Void::Result::Result<std::optional<ServerResponse>>
dispatch(ServerRequest request) const; dispatch(ServerRequest request) const;
[[nodiscard]] std::vector<Method>
allowed_methods(std::string_view path) const;
[[nodiscard]] std::size_t size() const; [[nodiscard]] std::size_t size() const;
private: private:
+90
View File
@@ -0,0 +1,90 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/System/Types.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <memory>
#include <string>
#include <vector>
namespace Void::FileSystem
{
enum class DirectoryEventKind : std::uint8_t {
Created,
Modified,
Deleted,
Renamed,
AttributeChanged,
RescanRequired,
};
struct DirectoryEvent {
DirectoryEventKind kind{DirectoryEventKind::Modified};
std::filesystem::path path{};
std::filesystem::path old_path{};
bool is_directory{false};
std::string detail{};
};
/// Predicate queried for every discovered/modified path. Returning true skips
/// watching (for directories) and suppresses event delivery for that path.
using IgnorePredicate =
std::function<bool(const std::filesystem::path& path, bool is_directory)>;
struct DirectoryWatcherOptions {
IgnorePredicate ignore{};
std::size_t max_watches{65536};
std::size_t max_queued_events{4096};
std::chrono::milliseconds rename_pair_window{std::chrono::milliseconds{50}};
};
/// Kernel-event (Linux inotify) recursive directory watcher with auto-watch
/// attachment on new subdirectories, rename pairing, ignore filtering, and
/// explicit RescanRequired signaling on queue overflow or watch exhaustion.
class DirectoryWatcher final
{
public:
~DirectoryWatcher() noexcept;
DirectoryWatcher(const DirectoryWatcher&) = delete;
DirectoryWatcher& operator=(const DirectoryWatcher&) = delete;
DirectoryWatcher(DirectoryWatcher&&) noexcept;
DirectoryWatcher& operator=(DirectoryWatcher&&) noexcept;
[[nodiscard]] static Void::Result::Result<DirectoryWatcher,
Void::Result::Error>
create(const std::filesystem::path& root,
DirectoryWatcherOptions options = {});
[[nodiscard]] Void::Result::Result<std::vector<DirectoryEvent>,
Void::Result::Error>
poll(std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
/// Re-walk `root()` and rebuild all inotify watches from scratch.
[[nodiscard]] Void::Result::Result<void, Void::Result::Error> rescan();
/// Wake any thread blocked inside poll().
void wake() noexcept;
/// Enqueue a RescanRequired event and wake waiters (deterministic test hook).
void simulate_overflow_for_test();
[[nodiscard]] const std::filesystem::path& root() const noexcept;
[[nodiscard]] std::size_t watch_count() const noexcept;
[[nodiscard]] int native_handle() const noexcept;
private:
struct Impl;
std::unique_ptr<Impl> impl_{};
explicit DirectoryWatcher(std::unique_ptr<Impl> impl) noexcept;
};
} // namespace Void::FileSystem
+592
View File
@@ -24,10 +24,17 @@
#ifndef _WIN32 #ifndef _WIN32
#include <fcntl.h> #include <fcntl.h>
#include <sys/file.h>
#include <sys/ioctl.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <sys/syscall.h>
#include <time.h>
#include <unistd.h> #include <unistd.h>
#if defined(__linux__) #if defined(__linux__)
#include <sys/random.h> #include <sys/random.h>
#if __has_include(<linux/fs.h>)
#include <linux/fs.h>
#endif
#endif #endif
#endif #endif
@@ -548,4 +555,589 @@ namespace detail
return {}; return {};
} }
// ── VL-010: File Locks, Atomic Symlink Swap, Reflink Copy, Timestamps ────────
enum class LockMode : std::uint8_t {
Shared,
Exclusive,
};
/// RAII advisory file lock backed by POSIX flock(2).
class FileLock final
{
public:
FileLock() noexcept = default;
~FileLock() noexcept { unlock(); }
FileLock(const FileLock&) = delete;
FileLock& operator=(const FileLock&) = delete;
FileLock(FileLock&& other) noexcept
: fd_(std::move(other.fd_))
, mode_(other.mode_)
{
}
FileLock& operator=(FileLock&& other) noexcept
{
if (this != &other) {
unlock();
fd_ = std::move(other.fd_);
mode_ = other.mode_;
}
return *this;
}
[[nodiscard]] bool locked() const noexcept { return fd_.valid(); }
[[nodiscard]] LockMode mode() const noexcept { return mode_; }
[[nodiscard]] int native_handle() const noexcept { return fd_.get(); }
void unlock() noexcept
{
#ifndef _WIN32
if (fd_.valid()) {
while (::flock(fd_.get(), LOCK_UN) != 0 && errno == EINTR) {
}
fd_.reset();
}
#endif
}
[[nodiscard]] static Void::Result::Result<FileLock, Void::Result::Error>
lock(const std::filesystem::path& path,
LockMode mode = LockMode::Exclusive)
{
auto res = acquire(path, mode, false);
if (!res.has_value()) {
return std::unexpected{std::move(res.error())};
}
if (!res->has_value()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::internal,
"FileSystem::FileLock::lock: unexpected empty result")};
}
return std::move(**res);
}
[[nodiscard]] static Void::Result::Result<std::optional<FileLock>,
Void::Result::Error>
try_lock(const std::filesystem::path& path,
LockMode mode = LockMode::Exclusive)
{
return acquire(path, mode, true);
}
private:
explicit FileLock(Void::System::OwnedFd fd, LockMode mode) noexcept
: fd_(std::move(fd))
, mode_(mode)
{
}
[[nodiscard]] static Void::Result::Result<std::optional<FileLock>,
Void::Result::Error>
acquire(const std::filesystem::path& path,
LockMode mode,
bool nonblocking)
{
#ifndef _WIN32
if (path.empty()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::FileLock: empty path")};
}
int raw = ::open(path.c_str(), O_CREAT | O_RDWR | O_CLOEXEC, 0666);
if (raw < 0 && mode == LockMode::Shared &&
(errno == EACCES || errno == EROFS)) {
raw = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);
}
if (raw < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::FileLock: cannot open '{}'",
path.string()),
err)};
}
Void::System::OwnedFd fd{raw};
const int op = (mode == LockMode::Shared ? LOCK_SH : LOCK_EX) |
(nonblocking ? LOCK_NB : 0);
for (;;) {
if (::flock(fd.get(), op) == 0) {
return std::optional<FileLock>{
FileLock{std::move(fd), mode}};
}
const int err = errno;
if (err == EINTR) {
continue;
}
if (nonblocking && (err == EWOULDBLOCK || err == EAGAIN)) {
return std::optional<FileLock>{std::nullopt};
}
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::FileLock: flock failed for '{}'",
path.string()),
err)};
}
#else
(void)path;
(void)mode;
(void)nonblocking;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::FileLock: unsupported platform")};
#endif
}
Void::System::OwnedFd fd_{};
LockMode mode_{LockMode::Exclusive};
};
/// Atomically create or replace symlink at `link_path` pointing to `target`
/// (symlinkat temp -> renameat -> optional parent dir fsync).
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
atomic_symlink_swap(
const std::filesystem::path& link_path,
const std::filesystem::path& target,
ReplaceDurability durability = ReplaceDurability::durable_sync)
{
#ifndef _WIN32
if (link_path.empty() || !link_path.has_filename() || target.empty()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::atomic_symlink_swap: empty link or target path")};
}
const std::string target_name = link_path.filename().string();
if (target_name == "." || target_name == "..") {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::atomic_symlink_swap: invalid link filename")};
}
const std::filesystem::path parent =
link_path.parent_path().empty() ? std::filesystem::path{"."}
: link_path.parent_path();
const int raw_dir =
::open(parent.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (raw_dir < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::atomic_symlink_swap: cannot open parent '{}'",
parent.string()),
err)};
}
Void::System::OwnedFd dir_fd{raw_dir};
std::string tmp_name;
bool created = false;
int last_err = 0;
for (int attempt = 0; attempt < 32; ++attempt) {
tmp_name = std::format(
".{}.void_lnk_{:016x}", target_name, detail::next_temp_entropy());
if (::symlinkat(target.c_str(), dir_fd.get(), tmp_name.c_str()) == 0) {
created = true;
break;
}
last_err = errno;
if (last_err != EEXIST) {
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(last_err),
std::format(
"FileSystem::atomic_symlink_swap: symlinkat failed in '{}'",
parent.string()),
last_err)};
}
}
if (!created) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::already_exists,
"FileSystem::atomic_symlink_swap: exhausted temporary link names",
last_err)};
}
bool cleanup = true;
struct CleanupGuard {
int dfd{-1};
const std::string* name{nullptr};
bool* active{nullptr};
~CleanupGuard() noexcept
{
if (active != nullptr && *active && dfd >= 0 && name != nullptr) {
(void)::unlinkat(dfd, name->c_str(), 0);
}
}
} cleanup_guard{dir_fd.get(), &tmp_name, &cleanup};
if (::renameat(dir_fd.get(),
tmp_name.c_str(),
dir_fd.get(),
target_name.c_str()) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::atomic_symlink_swap: renameat failed for '{}'",
link_path.string()),
err)};
}
cleanup = false;
if (durability == ReplaceDurability::durable_sync) {
if (const int err = detail::fsync_eintr(dir_fd.get()); err != 0) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::durability_unknown,
std::format(
"FileSystem::atomic_symlink_swap: parent dir fsync failed for '{}'",
link_path.string()),
err)};
}
}
return {};
#else
(void)link_path;
(void)target;
(void)durability;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::atomic_symlink_swap: unsupported platform")};
#endif
}
enum class CopyMethod : std::uint8_t {
Reflink,
PrivateCopy,
};
struct CopyResult {
std::uint64_t bytes{0};
CopyMethod method{CopyMethod::PrivateCopy};
};
struct CopyOptions {
bool overwrite{true};
bool preserve_permissions{true};
ReplaceDurability durability{ReplaceDurability::atomic_visibility};
};
/// Copy a regular file using CoW reflink (`ioctl(FICLONE)`) with atomic
/// staging and private-copy fallback. Explicitly never creates hardlinks.
[[nodiscard]] inline Void::Result::Result<CopyResult, Void::Result::Error>
reflink_copy_file(const std::filesystem::path& src,
const std::filesystem::path& dst,
CopyOptions options = {})
{
#ifndef _WIN32
if (src.empty() || dst.empty() || !dst.has_filename()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::reflink_copy_file: invalid source or destination path")};
}
const std::string dst_name = dst.filename().string();
if (dst_name == "." || dst_name == "..") {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::reflink_copy_file: invalid destination filename")};
}
const int raw_src = ::open(src.c_str(), O_RDONLY | O_CLOEXEC);
if (raw_src < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: cannot open '{}'",
src.string()),
err)};
}
Void::System::OwnedFd src_fd{raw_src};
struct stat src_st {};
if (::fstat(src_fd.get(), &src_st) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: fstat failed on '{}'",
src.string()),
err)};
}
if (!S_ISREG(src_st.st_mode)) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
std::format("FileSystem::reflink_copy_file: '{}' is not a regular file",
src.string()))};
}
const std::filesystem::path parent =
dst.parent_path().empty() ? std::filesystem::path{"."}
: dst.parent_path();
const int raw_dir =
::open(parent.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (raw_dir < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: cannot open parent '{}'",
parent.string()),
err)};
}
Void::System::OwnedFd dir_fd{raw_dir};
const mode_t create_mode = options.preserve_permissions
? static_cast<mode_t>(src_st.st_mode & 0777)
: static_cast<mode_t>(0644);
std::string tmp_name;
Void::System::OwnedFd tmp_fd;
int last_err = 0;
for (int attempt = 0; attempt < 32; ++attempt) {
tmp_name = std::format(
".{}.void_cp_{:016x}", dst_name, detail::next_temp_entropy());
const int fd = ::openat(dir_fd.get(),
tmp_name.c_str(),
O_CREAT | O_EXCL | O_RDWR | O_NOFOLLOW |
O_CLOEXEC,
create_mode);
if (fd >= 0) {
tmp_fd.reset(fd);
break;
}
last_err = errno;
if (last_err != EEXIST) {
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(last_err),
std::format("FileSystem::reflink_copy_file: create temp in '{}'",
parent.string()),
last_err)};
}
}
if (!tmp_fd.valid()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::already_exists,
"FileSystem::reflink_copy_file: exhausted temp names",
last_err)};
}
bool cleanup_tmp = true;
struct TempGuard {
int dfd{-1};
const std::string* name{nullptr};
bool* active{nullptr};
~TempGuard() noexcept
{
if (active != nullptr && *active && dfd >= 0 && name != nullptr) {
(void)::unlinkat(dfd, name->c_str(), 0);
}
}
} temp_guard{dir_fd.get(), &tmp_name, &cleanup_tmp};
CopyResult result;
result.bytes = static_cast<std::uint64_t>(src_st.st_size);
bool cloned = false;
#if defined(__linux__) && defined(FICLONE)
for (;;) {
if (::ioctl(tmp_fd.get(), FICLONE, src_fd.get()) == 0) {
cloned = true;
result.method = CopyMethod::Reflink;
break;
}
if (errno == EINTR) {
continue;
}
const int err = errno;
if (err == EOPNOTSUPP || err == EXDEV || err == EINVAL ||
err == ENOTTY || err == ENOSYS || err == EBADF || err == ETXTBSY
#if defined(ENOTSUP) && (!defined(EOPNOTSUPP) || ENOTSUP != EOPNOTSUPP)
|| err == ENOTSUP
#endif
) {
break;
}
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: FICLONE failed for '{}'",
dst.string()),
err)};
}
#endif
if (!cloned) {
result.method = CopyMethod::PrivateCopy;
std::vector<char> buf(64ULL * 1024ULL);
std::uint64_t copied = 0;
for (;;) {
const ssize_t r = ::read(src_fd.get(), buf.data(), buf.size());
if (r > 0) {
std::size_t off = 0;
const auto ur = static_cast<std::size_t>(r);
while (off < ur) {
const ssize_t w =
::write(tmp_fd.get(), buf.data() + off, ur - off);
if (w < 0) {
if (errno == EINTR) {
continue;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format(
"FileSystem::reflink_copy_file: write failed for '{}'",
dst.string()),
err)};
}
off += static_cast<std::size_t>(w);
}
copied += ur;
} else if (r == 0) {
break;
} else {
if (errno == EINTR) {
continue;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format(
"FileSystem::reflink_copy_file: read failed on '{}'",
src.string()),
err)};
}
}
result.bytes = copied;
}
if (options.preserve_permissions) {
(void)::fchmod(tmp_fd.get(), create_mode);
}
if (options.durability == ReplaceDurability::durable_sync) {
if (const int err = detail::fsync_eintr(tmp_fd.get()); err != 0) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::sync_failed,
std::format("FileSystem::reflink_copy_file: fsync failed for '{}'",
dst.string()),
err)};
}
}
if (auto closed = tmp_fd.close(); !closed.has_value()) {
return std::unexpected{std::move(closed.error())};
}
if (options.overwrite) {
if (::renameat(dir_fd.get(),
tmp_name.c_str(),
dir_fd.get(),
dst_name.c_str()) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: rename failed for '{}'",
dst.string()),
err)};
}
} else {
if (::linkat(dir_fd.get(),
tmp_name.c_str(),
dir_fd.get(),
dst_name.c_str(),
0) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: publish failed for '{}'",
dst.string()),
err)};
}
(void)::unlinkat(dir_fd.get(), tmp_name.c_str(), 0);
}
cleanup_tmp = false;
if (options.durability == ReplaceDurability::durable_sync) {
if (const int err = detail::fsync_eintr(dir_fd.get()); err != 0) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::durability_unknown,
std::format(
"FileSystem::reflink_copy_file: parent fsync failed for '{}'",
dst.string()),
err)};
}
}
return result;
#else
(void)src;
(void)dst;
(void)options;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::reflink_copy_file: unsupported platform")};
#endif
}
/// Set access and modification timestamps without dereferencing symlinks.
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
set_timestamps_nofollow(const std::filesystem::path& path,
std::int64_t atime_sec,
std::int32_t atime_nsec,
std::int64_t mtime_sec,
std::int32_t mtime_nsec)
{
#ifndef _WIN32
if (path.empty()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::set_timestamps_nofollow: empty path")};
}
auto valid_nsec = [](std::int32_t ns) noexcept {
return (ns >= 0 && ns < 1'000'000'000) || ns == UTIME_NOW ||
ns == UTIME_OMIT;
};
if (!valid_nsec(atime_nsec) || !valid_nsec(mtime_nsec)) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::set_timestamps_nofollow: nanoseconds out of range")};
}
struct timespec ts[2]{};
ts[0].tv_sec = static_cast<time_t>(atime_sec);
ts[0].tv_nsec = static_cast<long>(atime_nsec);
ts[1].tv_sec = static_cast<time_t>(mtime_sec);
ts[1].tv_nsec = static_cast<long>(mtime_nsec);
if (::utimensat(AT_FDCWD, path.c_str(), ts, AT_SYMLINK_NOFOLLOW) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::set_timestamps_nofollow: utimensat failed for '{}'",
path.string()),
err)};
}
return {};
#else
(void)path;
(void)atime_sec;
(void)atime_nsec;
(void)mtime_sec;
(void)mtime_nsec;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::set_timestamps_nofollow: unsupported platform")};
#endif
}
/// Set canonical modification and access timestamps (default UNIX epoch 0)
/// without following symlinks (`utimensat(..., AT_SYMLINK_NOFOLLOW)`).
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
set_canonical_mtime(const std::filesystem::path& path,
std::int64_t unix_seconds = 0,
std::int32_t nanoseconds = 0)
{
return set_timestamps_nofollow(
path, unix_seconds, nanoseconds, unix_seconds, nanoseconds);
}
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
set_canonical_mtime(const std::filesystem::path& path,
std::chrono::sys_seconds tp)
{
return set_canonical_mtime(path, tp.time_since_epoch().count(), 0);
}
} // namespace Void::FileSystem } // namespace Void::FileSystem
+7
View File
@@ -116,6 +116,7 @@ public:
[[nodiscard]] bool valid() const noexcept; [[nodiscard]] bool valid() const noexcept;
[[nodiscard]] bool running() const noexcept; [[nodiscard]] bool running() const noexcept;
[[nodiscard]] bool process_group_alive() const noexcept;
[[nodiscard]] long long pid() const noexcept; [[nodiscard]] long long pid() const noexcept;
[[nodiscard]] long long pgid() const noexcept; [[nodiscard]] long long pgid() const noexcept;
[[nodiscard]] bool owns_process_group() const noexcept; [[nodiscard]] bool owns_process_group() const noexcept;
@@ -201,4 +202,10 @@ private:
const std::vector<std::string>& arguments, const std::vector<std::string>& arguments,
bool close_extra_fds); bool close_extra_fds);
/// Opt the current process into Linux PR_SET_CHILD_SUBREAPER so orphaned
/// descendant processes in spawned process groups reparent to this process
/// and can be reaped directly via waitpid(-pgid, ...).
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
enable_subreaper() noexcept;
} // namespace Void::Process } // namespace Void::Process
+185 -5
View File
@@ -1,10 +1,190 @@
#pragma once #pragma once
namespace Void::Testing { #include <Void/Testing/Config.hpp>
#include <Void/Testing/Detail/Registry.hpp>
// Aliases to void so users can omit return statements safely #include <initializer_list>
// and avoid compiler warnings/errors. Perfectly matches std::function<void()>. #include <string>
using Test = void; #include <string_view>
using DisabledTest = void; #include <utility>
#include <vector>
namespace Void::Testing
{
// Aliases to void so users can omit return statements safely
// and avoid compiler warnings/errors. Perfectly matches
// std::function<void()>.
using Test = void;
using DisabledTest = void;
namespace Detail
{
[[nodiscard]] inline std::string
normalize_suite_label(std::string_view raw)
{
if (raw.size() >= 2 && raw.front() == '"' && raw.back() == '"') {
raw = raw.substr(1, raw.size() - 2);
}
return std::string{raw};
}
class NativeRegistrar final
{
public:
NativeRegistrar(void (*fn)(), std::string_view suite,
const char* file, int line,
std::string_view name,
std::initializer_list<const char*> tags = {},
bool disabled = false,
std::string_view skip_reason = {})
{
std::vector<std::string> tag_vec;
tag_vec.reserve(tags.size());
for (const char* t : tags) {
if (t != nullptr) {
tag_vec.emplace_back(t);
}
}
Registry::instance().add(TestCase{
.run = fn,
.name = std::string{name},
.suite = normalize_suite_label(suite),
.file = file != nullptr ? file : "",
.line = line,
.disabled = disabled,
.skip_reason = std::string{skip_reason},
.tags = std::move(tag_vec),
});
}
};
template <typename FixtureT> class NativeFixtureRegistrar final
{
public:
NativeFixtureRegistrar(void (*fn)(FixtureT&),
std::string_view suite,
const char* file, int line,
std::string_view name,
std::initializer_list<const char*> tags = {},
bool disabled = false,
std::string_view skip_reason = {})
{
std::vector<std::string> tag_vec;
tag_vec.reserve(tags.size());
for (const char* t : tags) {
if (t != nullptr) {
tag_vec.emplace_back(t);
}
}
Registry::instance().add(TestCase{
.run =
[fn]() {
FixtureT fixture{};
if constexpr (requires { fixture.setup(); }) {
fixture.setup();
}
try {
fn(fixture);
} catch (...) {
if constexpr (requires {
fixture.teardown();
}) {
fixture.teardown();
}
throw;
}
if constexpr (requires { fixture.teardown(); }) {
fixture.teardown();
}
},
.name = std::string{name},
.suite = normalize_suite_label(suite),
.file = file != nullptr ? file : "",
.line = line,
.disabled = disabled,
.skip_reason = std::string{skip_reason},
.tags = std::move(tag_vec),
});
}
};
} // namespace Detail
} // namespace Void::Testing } // namespace Void::Testing
#define VOID_TESTING_DETAIL_CAT_IMPL(a, b) a##b
#define VOID_TESTING_DETAIL_CAT(a, b) VOID_TESTING_DETAIL_CAT_IMPL(a, b)
#ifdef __COUNTER__
#define VOID_TESTING_DETAIL_NEXT_ID __COUNTER__
#else
#define VOID_TESTING_DETAIL_NEXT_ID __LINE__
#endif
#define VOID_TESTING_DETAIL_DEFINE_TEST(suite_expr, test_name, disabled_flag, \
skip_msg, uid, ...) \
static void VOID_TESTING_DETAIL_CAT(_void_native_test_fn_, uid)(); \
namespace \
{ \
[[maybe_unused]] const ::Void::Testing::Detail::NativeRegistrar \
VOID_TESTING_DETAIL_CAT(_void_native_test_reg_, uid){ \
&VOID_TESTING_DETAIL_CAT(_void_native_test_fn_, uid), \
(suite_expr), \
__FILE__, \
__LINE__, \
#test_name, \
{__VA_ARGS__}, \
(disabled_flag), \
(skip_msg)}; \
} \
static void VOID_TESTING_DETAIL_CAT(_void_native_test_fn_, uid)()
#define VOID_TESTING_DETAIL_DEFINE_FIXTURE_TEST(fixture_type, test_name, \
disabled_flag, skip_msg, uid) \
static void VOID_TESTING_DETAIL_CAT(_void_native_fx_fn_, uid)( \
fixture_type&); \
namespace \
{ \
[[maybe_unused]] const ::Void::Testing::Detail::NativeFixtureRegistrar< \
fixture_type> \
VOID_TESTING_DETAIL_CAT(_void_native_fx_reg_, uid){ \
&VOID_TESTING_DETAIL_CAT(_void_native_fx_fn_, uid), \
#fixture_type, \
__FILE__, \
__LINE__, \
#test_name, \
{}, \
(disabled_flag), \
(skip_msg)}; \
} \
static void VOID_TESTING_DETAIL_CAT(_void_native_fx_fn_, uid)( \
[[maybe_unused]] fixture_type& fixture)
/// Declare a self-registering test case with zero CMake scanner dependency.
/// Symbols are internal-linkage and counter-disambiguated so files sharing the
/// same basename in different subdirectories link cleanly together.
#define VOID_TEST(suite, name) \
VOID_TESTING_DETAIL_DEFINE_TEST(#suite, name, false, "", \
VOID_TESTING_DETAIL_NEXT_ID)
/// Same as VOID_TEST, taking tags (string literals) after `name`.
#define VOID_TEST_TAGGED(suite, name, ...) \
VOID_TESTING_DETAIL_DEFINE_TEST(#suite, name, false, "", \
VOID_TESTING_DETAIL_NEXT_ID, __VA_ARGS__)
/// Declare a skipped/disabled self-registering test case.
#define VOID_TEST_DISABLED(suite, name, reason) \
VOID_TESTING_DETAIL_DEFINE_TEST(#suite, name, true, (reason), \
VOID_TESTING_DETAIL_NEXT_ID)
/// Declare a self-registering fixture test. The fixture instance is bound as
/// `fixture` inside the test body, with optional setup()/teardown() hooks.
#define VOID_TEST_FIXTURE(fixture_type, name) \
VOID_TESTING_DETAIL_DEFINE_FIXTURE_TEST(fixture_type, name, false, "", \
VOID_TESTING_DETAIL_NEXT_ID)
#define VOID_TEST_FIXTURE_DISABLED(fixture_type, name, reason) \
VOID_TESTING_DETAIL_DEFINE_FIXTURE_TEST(fixture_type, name, true, (reason), \
VOID_TESTING_DETAIL_NEXT_ID)
+94 -23
View File
@@ -438,6 +438,54 @@ namespace Void::Semver
using Clause = std::vector<Comparator>; using Clause = std::vector<Comparator>;
std::vector<Clause> m_alternatives; std::vector<Clause> m_alternatives;
struct PartialVersion {
Version version{};
int components{0};
};
[[nodiscard]] static std::optional<PartialVersion>
parse_partial(std::string_view token)
{
if (token.empty()) {
return std::nullopt;
}
if (token.find('-') != std::string_view::npos ||
token.find('+') != std::string_view::npos) {
const auto full = parse_strict(token);
if (!full) {
return std::nullopt;
}
return PartialVersion{*full, 3};
}
const auto first_dot = token.find('.');
if (first_dot == std::string_view::npos) {
unsigned major = 0;
if (!Detail::parse_component(token, major)) {
return std::nullopt;
}
return PartialVersion{
Version{.major = major, .minor = 0, .patch = 0}, 1};
}
const auto second_dot = token.find('.', first_dot + 1);
if (second_dot == std::string_view::npos) {
unsigned major = 0;
unsigned minor = 0;
if (!Detail::parse_component(token.substr(0, first_dot),
major) ||
!Detail::parse_component(token.substr(first_dot + 1),
minor)) {
return std::nullopt;
}
return PartialVersion{
Version{.major = major, .minor = minor, .patch = 0}, 2};
}
const auto full = parse_strict(token);
if (!full) {
return std::nullopt;
}
return PartialVersion{*full, 3};
}
[[nodiscard]] static bool append_token(Clause& clause, [[nodiscard]] static bool append_token(Clause& clause,
std::string_view token) std::string_view token)
{ {
@@ -447,53 +495,76 @@ namespace Void::Semver
if (token.starts_with('^') || token.starts_with('~')) { if (token.starts_with('^') || token.starts_with('~')) {
const char kind = token.front(); const char kind = token.front();
token.remove_prefix(1); token.remove_prefix(1);
const auto lower = parse_strict(token); const auto partial = parse_partial(token);
if (!lower) { if (!partial) {
return false; return false;
} }
const Version& lower = partial->version;
Version upper; Version upper;
if (kind == '~') { if (kind == '~') {
if (lower->minor == if (partial->components == 1) {
if (lower.major ==
std::numeric_limits<unsigned>::max()) {
return false;
}
upper = Version{.major = lower.major + 1,
.minor = 0,
.patch = 0,
.pre_release = {},
.build = {}};
} else {
if (lower.minor ==
std::numeric_limits<unsigned>::max()) {
return false;
}
upper = Version{.major = lower.major,
.minor = lower.minor + 1,
.patch = 0,
.pre_release = {},
.build = {}};
}
} else if (partial->components == 1) {
if (lower.major ==
std::numeric_limits<unsigned>::max()) { std::numeric_limits<unsigned>::max()) {
return false; return false;
} }
upper = Version{.major = lower->major, upper = Version{.major = lower.major + 1,
.minor = lower->minor + 1,
.patch = 0,
.pre_release = {},
.build = {}};
} else if (lower->major > 0) {
if (lower->major ==
std::numeric_limits<unsigned>::max()) {
return false;
}
upper = Version{.major = lower->major + 1,
.minor = 0, .minor = 0,
.patch = 0, .patch = 0,
.pre_release = {}, .pre_release = {},
.build = {}}; .build = {}};
} else if (lower->minor > 0) { } else if (lower.major > 0) {
if (lower->minor == if (lower.major ==
std::numeric_limits<unsigned>::max()) {
return false;
}
upper = Version{.major = lower.major + 1,
.minor = 0,
.patch = 0,
.pre_release = {},
.build = {}};
} else if (lower.minor > 0) {
if (lower.minor ==
std::numeric_limits<unsigned>::max()) { std::numeric_limits<unsigned>::max()) {
return false; return false;
} }
upper = Version{.major = 0, upper = Version{.major = 0,
.minor = lower->minor + 1, .minor = lower.minor + 1,
.patch = 0, .patch = 0,
.pre_release = {}, .pre_release = {},
.build = {}}; .build = {}};
} else { } else {
if (lower->patch == if (lower.patch ==
std::numeric_limits<unsigned>::max()) { std::numeric_limits<unsigned>::max()) {
return false; return false;
} }
upper = Version{.major = 0, upper = Version{.major = 0,
.minor = 0, .minor = 0,
.patch = lower->patch + 1, .patch = lower.patch + 1,
.pre_release = {}, .pre_release = {},
.build = {}}; .build = {}};
} }
clause.push_back({Operation::GreaterEqual, *lower}); clause.push_back({Operation::GreaterEqual, lower});
clause.push_back({Operation::Less, std::move(upper)}); clause.push_back({Operation::Less, std::move(upper)});
return true; return true;
} }
@@ -518,11 +589,11 @@ namespace Void::Semver
} else if (token.starts_with('=')) { } else if (token.starts_with('=')) {
token.remove_prefix(1); token.remove_prefix(1);
} }
const auto version = parse_strict(token); const auto partial = parse_partial(token);
if (!version) { if (!partial) {
return false; return false;
} }
clause.push_back({operation, *version}); clause.push_back({operation, partial->version});
return true; return true;
} }
+148 -30
View File
@@ -1,10 +1,13 @@
#include <Void/Archive/Archive.hpp> #include <Void/Archive/Archive.hpp>
#include "BuiltinTar.hpp"
#include <array> #include <array>
#include <atomic> #include <atomic>
#include <cerrno> #include <cerrno>
#include <cstring> #include <cstring>
#include <format> #include <format>
#include <limits>
#include <memory> #include <memory>
#include <optional> #include <optional>
#include <set> #include <set>
@@ -13,8 +16,10 @@
#include <system_error> #include <system_error>
#include <utility> #include <utility>
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
#include <archive.h> #include <archive.h>
#include <archive_entry.h> #include <archive_entry.h>
#endif
#ifndef _WIN32 #ifndef _WIN32
#include <fcntl.h> #include <fcntl.h>
@@ -28,6 +33,7 @@ namespace Void::Archive
{ {
namespace namespace
{ {
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
using ArchiveHandle = using ArchiveHandle =
std::unique_ptr<archive, decltype(&archive_read_free)>; std::unique_ptr<archive, decltype(&archive_read_free)>;
@@ -39,6 +45,7 @@ namespace Void::Archive
"Archive::extract: {}: {}", operation, "Archive::extract: {}: {}", operation,
message == nullptr ? "unknown archive error" : message)}; message == nullptr ? "unknown archive error" : message)};
} }
#endif
[[nodiscard]] std::optional<std::filesystem::path> [[nodiscard]] std::optional<std::filesystem::path>
safe_relative_path(std::string_view rawPath, bool directory) safe_relative_path(std::string_view rawPath, bool directory)
@@ -225,12 +232,14 @@ namespace Void::Archive
return {}; return {};
} }
template <typename ReadFn>
[[nodiscard]] Void::Result::Result<std::uint64_t> [[nodiscard]] Void::Result::Result<std::uint64_t>
extract_regular(archive *reader, int rootDescriptor, extract_regular_stream(int rootDescriptor,
const std::filesystem::path &relative, const std::filesystem::path &relative,
const std::filesystem::path &displayRoot, const std::filesystem::path &displayRoot,
const ExtractionOptions &options, const ExtractionOptions &options,
std::uint64_t alreadyExtracted, bool executable) std::uint64_t alreadyExtracted,
bool executable, ReadFn &&read_fn)
{ {
auto openedParent = open_parent_directory( auto openedParent = open_parent_directory(
rootDescriptor, relative.parent_path(), displayRoot); rootDescriptor, relative.parent_path(), displayRoot);
@@ -286,15 +295,14 @@ namespace Void::Archive
std::array<std::byte, 64 * 1024> buffer{}; std::array<std::byte, 64 * 1024> buffer{};
std::uint64_t fileBytes = 0; std::uint64_t fileBytes = 0;
for (;;) { for (;;) {
const auto count = auto chunk = read_fn(std::span{buffer});
archive_read_data(reader, buffer.data(), buffer.size()); if (!chunk.has_value()) {
if (count == 0) { return fail(chunk.error().message());
}
if (*chunk == 0) {
break; break;
} }
if (count < 0) { const auto amount = static_cast<std::uint64_t>(*chunk);
return fail(archive_error(reader, "read entry").message());
}
const auto amount = static_cast<std::uint64_t>(count);
if (amount > options.maxFileBytes - fileBytes || if (amount > options.maxFileBytes - fileBytes ||
amount > amount >
options.maxTotalBytes - alreadyExtracted - fileBytes) { options.maxTotalBytes - alreadyExtracted - fileBytes) {
@@ -303,11 +311,11 @@ namespace Void::Archive
} }
std::size_t written = 0; std::size_t written = 0;
while (written < static_cast<std::size_t>(count)) { while (written < *chunk) {
const auto result = ::write( const auto result = ::write(
descriptor.get(), descriptor.get(),
reinterpret_cast<const char *>(buffer.data()) + written, reinterpret_cast<const char *>(buffer.data()) + written,
static_cast<std::size_t>(count) - written); *chunk - written);
if (result < 0 && errno == EINTR) { if (result < 0 && errno == EINTR) {
continue; continue;
} }
@@ -448,10 +456,12 @@ namespace Void::Archive
return {}; return {};
} }
template <typename ReadFn>
[[nodiscard]] Void::Result::Result<std::uint64_t> [[nodiscard]] Void::Result::Result<std::uint64_t>
extract_regular(archive *reader, const std::filesystem::path &path, extract_regular_stream(const std::filesystem::path &path,
const ExtractionOptions &options, const ExtractionOptions &options,
std::uint64_t alreadyExtracted) std::uint64_t alreadyExtracted,
ReadFn &&read_fn)
{ {
std::error_code error; std::error_code error;
const auto status = std::filesystem::symlink_status(path, error); const auto status = std::filesystem::symlink_status(path, error);
@@ -486,15 +496,14 @@ namespace Void::Archive
std::array<std::byte, 64 * 1024> buffer{}; std::array<std::byte, 64 * 1024> buffer{};
std::uint64_t fileBytes = 0; std::uint64_t fileBytes = 0;
for (;;) { for (;;) {
const auto count = auto chunk = read_fn(std::span{buffer});
archive_read_data(reader, buffer.data(), buffer.size()); if (!chunk.has_value()) {
if (count == 0) { return fail(chunk.error().message());
}
if (*chunk == 0) {
break; break;
} }
if (count < 0) { const auto amount = static_cast<std::uint64_t>(*chunk);
return fail(archive_error(reader, "read entry").message());
}
const auto amount = static_cast<std::uint64_t>(count);
if (amount > options.maxFileBytes - fileBytes || if (amount > options.maxFileBytes - fileBytes ||
amount > amount >
options.maxTotalBytes - alreadyExtracted - fileBytes) { options.maxTotalBytes - alreadyExtracted - fileBytes) {
@@ -502,7 +511,7 @@ namespace Void::Archive
"Archive::extract: extracted size exceeds policy"); "Archive::extract: extracted size exceeds policy");
} }
output.write(reinterpret_cast<const char *>(buffer.data()), output.write(reinterpret_cast<const char *>(buffer.data()),
count); static_cast<std::streamsize>(*chunk));
if (!output) { if (!output) {
return fail("Archive::extract: write failed"); return fail("Archive::extract: write failed");
} }
@@ -544,11 +553,13 @@ namespace Void::Archive
} }
#endif #endif
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
ArchiveHandle reader{archive_read_new(), &archive_read_free}; ArchiveHandle reader{archive_read_new(), &archive_read_free};
if (!reader) { if (!reader) {
return Void::Result::fail( return Void::Result::fail(
"Archive::extract: cannot allocate archive reader"); "Archive::extract: cannot allocate archive reader");
} }
archive_read_support_filter_gzip(reader.get());
archive_read_support_filter_zstd(reader.get()); archive_read_support_filter_zstd(reader.get());
archive_read_support_filter_none(reader.get()); archive_read_support_filter_none(reader.get());
archive_read_support_format_tar(reader.get()); archive_read_support_format_tar(reader.get());
@@ -633,14 +644,23 @@ namespace Void::Archive
return Void::Result::fail( return Void::Result::fail(
"Archive::extract: declared entry size exceeds policy"); "Archive::extract: declared entry size exceeds policy");
} }
auto read_libarchive_chunk =
[&](std::span<std::byte> dst) -> Void::Result::Result<std::size_t> {
const auto count =
archive_read_data(reader.get(), dst.data(), dst.size());
if (count < 0) {
return std::unexpected{archive_error(reader.get(), "read entry")};
}
return static_cast<std::size_t>(count);
};
#ifndef _WIN32 #ifndef _WIN32
const bool executable = (archive_entry_perm(entry) & 0111) != 0; const bool executable = (archive_entry_perm(entry) & 0111) != 0;
auto extracted = auto extracted = extract_regular_stream(
extract_regular(reader.get(), root->get(), *relative, root->get(), *relative, destination, options, result.bytes,
destination, options, result.bytes, executable); executable, read_libarchive_chunk);
#else #else
auto extracted = auto extracted = extract_regular_stream(
extract_regular(reader.get(), output, options, result.bytes); output, options, result.bytes, read_libarchive_chunk);
#endif #endif
if (!extracted) { if (!extracted) {
return std::unexpected{extracted.error()}; return std::unexpected{extracted.error()};
@@ -648,5 +668,103 @@ namespace Void::Archive
result.bytes += *extracted; result.bytes += *extracted;
} }
return result; return result;
#else
auto source = FileByteSource::open(archivePath);
if (!source.has_value()) {
return std::unexpected{std::move(source.error())};
}
ReadLimits limits;
limits.max_entries = options.maxEntries;
limits.max_file_bytes = options.maxFileBytes;
limits.max_total_bytes = options.maxTotalBytes;
limits.max_compressed_bytes = std::numeric_limits<std::uint64_t>::max();
Detail::BuiltinTarStream stream{
*source, limits, {}, std::nullopt,
Void::Time::SystemMonotonicClock::instance()};
if (auto opened = stream.open(); !opened.has_value()) {
return std::unexpected{std::move(opened.error())};
}
ExtractionResult result;
std::set<std::filesystem::path> seen;
for (;;) {
auto next = stream.next_entry();
if (!next.has_value()) {
return std::unexpected{std::move(next.error())};
}
if (!next->has_value()) {
break;
}
if (++result.entries > options.maxEntries) {
return Void::Result::fail(
"Archive::extract: entry count exceeds policy");
}
const auto &entry = **next;
if (entry.type == EntryType::Hardlink ||
entry.type == EntryType::Symlink || !entry.linkname.empty()) {
return Void::Result::fail(
"Archive::extract: links are not allowed");
}
if (entry.type != EntryType::Directory &&
entry.type != EntryType::RegularFile) {
return Void::Result::fail(
"Archive::extract: special files are not allowed");
}
const bool is_dir = (entry.type == EntryType::Directory);
auto relative = safe_relative_path(entry.path, is_dir);
if (!relative || !seen.insert(*relative).second) {
return Void::Result::fail(std::format(
"Archive::extract: unsafe or duplicate path '{}'",
entry.path));
}
#ifdef _WIN32
if (auto parents = safe_parents(root, relative->parent_path());
!parents) {
return std::unexpected{parents.error()};
}
const auto output = root / *relative;
#endif
if (is_dir) {
#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;
}
if (entry.declared_size > options.maxFileBytes ||
entry.declared_size > options.maxTotalBytes - result.bytes) {
return Void::Result::fail(
"Archive::extract: declared entry size exceeds policy");
}
auto read_builtin_chunk =
[&](std::span<std::byte> dst) -> Void::Result::Result<std::size_t> {
return stream.read_entry_data(dst);
};
#ifndef _WIN32
const bool executable = (entry.mode & 0111U) != 0U;
auto extracted = extract_regular_stream(
root->get(), *relative, destination, options, result.bytes,
executable, read_builtin_chunk);
#else
auto extracted = extract_regular_stream(
output, options, result.bytes, read_builtin_chunk);
#endif
if (!extracted) {
return std::unexpected{extracted.error()};
}
result.bytes += *extracted;
}
return result;
#endif
} }
} // namespace Void::Archive } // namespace Void::Archive
+867
View File
@@ -0,0 +1,867 @@
#include "BuiltinTar.hpp"
#include <algorithm>
#include <array>
#include <cerrno>
#include <charconv>
#include <chrono>
#include <cstring>
#include <format>
#include <string_view>
#ifndef _WIN32
#include <unistd.h>
#endif
namespace Void::Archive::Detail
{
namespace
{
constexpr std::size_t kTarBlockSize = 512;
[[nodiscard]] bool is_zero_block(const std::array<std::byte, kTarBlockSize>& block) noexcept
{
for (const std::byte b : block) {
if (b != std::byte{0}) {
return false;
}
}
return true;
}
inline void write_octal(std::span<std::byte> field, std::uint64_t value) noexcept
{
if (field.size() < 2) {
return;
}
field.back() = std::byte{0};
std::size_t pos = field.size() - 1;
while (pos > 0) {
--pos;
field[pos] = static_cast<std::byte>('0' + (value & 7ULL));
value >>= 3ULL;
}
}
[[nodiscard]] Void::Result::Result<std::uint64_t>
parse_octal(std::span<const std::byte> field, const char* name)
{
const auto* p = reinterpret_cast<const unsigned char*>(field.data());
std::size_t n = field.size();
if (n > 0 && (p[0] & 0x80U) != 0U) {
// POSIX / GNU big-endian base-256 unsigned extension.
if ((p[0] & 0x40U) != 0U) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
std::format("Archive: negative base-256 field '{}'",
name))};
}
std::uint64_t v = static_cast<std::uint64_t>(p[0] & 0x3FU);
for (std::size_t i = 1; i < n; ++i) {
if (v > (std::numeric_limits<std::uint64_t>::max() >> 8U)) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
std::format("Archive: overflowing field '{}'",
name))};
}
v = (v << 8U) | static_cast<std::uint64_t>(p[i]);
}
return v;
}
std::size_t i = 0;
while (i < n && (p[i] == ' ' || p[i] == '\0')) {
++i;
}
if (i == n) {
return std::uint64_t{0};
}
std::uint64_t out = 0;
bool saw_digit = false;
for (; i < n; ++i) {
if (p[i] == '\0' || p[i] == ' ') {
break;
}
if (p[i] < '0' || p[i] > '7') {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
std::format("Archive: invalid octal character in '{}'",
name))};
}
if (out > (std::numeric_limits<std::uint64_t>::max() >> 3U)) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
std::format("Archive: octal overflow in '{}'", name))};
}
out = (out << 3U) | static_cast<std::uint64_t>(p[i] - '0');
saw_digit = true;
}
if (!saw_digit) {
return std::uint64_t{0};
}
return out;
}
[[nodiscard]] std::string_view
c_field(std::span<const std::byte> field) noexcept
{
const char* s = reinterpret_cast<const char*>(field.data());
std::size_t len = 0;
while (len < field.size() && s[len] != '\0') {
++len;
}
return {s, len};
}
[[nodiscard]] std::uint32_t
compute_checksum_unsigned(const std::array<std::byte, kTarBlockSize>& block) noexcept
{
std::uint32_t sum = 0;
for (std::size_t i = 0; i < kTarBlockSize; ++i) {
if (i >= 148 && i < 156) {
sum += static_cast<std::uint32_t>(' ');
} else {
sum += static_cast<std::uint32_t>(
std::to_integer<std::uint8_t>(block[i]));
}
}
return sum;
}
[[nodiscard]] std::int32_t
compute_checksum_signed(const std::array<std::byte, kTarBlockSize>& block) noexcept
{
std::int32_t sum = 0;
for (std::size_t i = 0; i < kTarBlockSize; ++i) {
if (i >= 148 && i < 156) {
sum += static_cast<std::int32_t>(' ');
} else {
sum += static_cast<std::int32_t>(
static_cast<signed char>(
std::to_integer<unsigned char>(block[i])));
}
}
return sum;
}
void build_ustar_header(std::array<std::byte, kTarBlockSize>& hdr,
std::string_view wire_name, char typeflag,
std::uint32_t mode, std::uint32_t uid,
std::uint32_t gid, std::uint64_t size,
std::uint64_t mtime) noexcept
{
hdr.fill(std::byte{0});
// Split into prefix (<=155) + name (<=100) only when needed and valid;
// callers handling paths >255 emit PAX 'x' before this header.
std::string_view prefix{};
std::string_view name = wire_name;
if (wire_name.size() > 100) {
const std::size_t min_split =
wire_name.size() > 100 ? wire_name.size() - 101 : 0;
const std::size_t max_split = std::min<std::size_t>(155, wire_name.size() - 1);
std::size_t chosen = std::string_view::npos;
for (std::size_t pos = max_split; pos >= min_split; --pos) {
if (pos < wire_name.size() && wire_name[pos] == '/') {
const std::string_view cand_prefix = wire_name.substr(0, pos);
const std::string_view cand_name = wire_name.substr(pos + 1);
if (!cand_prefix.empty() && cand_prefix.size() <= 155 &&
!cand_name.empty() && cand_name.size() <= 100) {
chosen = pos;
break;
}
}
if (pos == 0) {
break;
}
}
if (chosen != std::string_view::npos) {
prefix = wire_name.substr(0, chosen);
name = wire_name.substr(chosen + 1);
} else {
name = wire_name.substr(0, 100);
}
}
std::memcpy(hdr.data() + 0, name.data(), std::min<std::size_t>(name.size(), 100));
write_octal(std::span{hdr}.subspan(100, 8), mode & 07777U);
write_octal(std::span{hdr}.subspan(108, 8), uid);
write_octal(std::span{hdr}.subspan(116, 8), gid);
// Clamp size field to 11 octal digits when PAX overrides size.
const std::uint64_t ustar_size =
size <= 077777777777ULL ? size : 0ULL;
write_octal(std::span{hdr}.subspan(124, 12), ustar_size);
write_octal(std::span{hdr}.subspan(136, 12), mtime);
std::fill(hdr.begin() + 148, hdr.begin() + 156, std::byte{' '});
hdr[156] = static_cast<std::byte>(typeflag);
std::memcpy(hdr.data() + 257, "ustar\0", 6);
hdr[263] = std::byte{'0'};
hdr[264] = std::byte{'0'};
write_octal(std::span{hdr}.subspan(329, 8), 0);
write_octal(std::span{hdr}.subspan(337, 8), 0);
if (!prefix.empty()) {
std::memcpy(hdr.data() + 345, prefix.data(),
std::min<std::size_t>(prefix.size(), 155));
}
const std::uint32_t sum = compute_checksum_unsigned(hdr);
write_octal(std::span{hdr}.subspan(148, 7), sum);
hdr[155] = std::byte{' '};
}
[[nodiscard]] std::string
make_pax_record(std::string_view key, std::string_view value)
{
const std::size_t rest_len = 1U + key.size() + 1U + value.size() + 1U;
std::size_t total = rest_len + 1U;
for (;;) {
const std::string digits = std::to_string(total);
const std::size_t next = digits.size() + rest_len;
if (next == total) {
break;
}
total = next;
}
return std::format("{} {}={}\n", total, key, value);
}
[[nodiscard]] Void::Result::Result<void>
write_padding(ByteSink& sink, std::uint64_t written)
{
const std::size_t rem = static_cast<std::size_t>(written % kTarBlockSize);
if (rem == 0) {
return {};
}
std::array<std::byte, kTarBlockSize> zeros{};
return sink.write(std::span{zeros}.subspan(0, kTarBlockSize - rem));
}
[[nodiscard]] bool
can_fit_ustar_path(std::string_view wire_path) noexcept
{
if (wire_path.size() <= 100) {
return true;
}
if (wire_path.size() > 256) {
return false;
}
const std::size_t min_split = wire_path.size() - 101;
const std::size_t max_split = std::min<std::size_t>(155, wire_path.size() - 1);
for (std::size_t pos = max_split; pos >= min_split; --pos) {
if (pos < wire_path.size() && wire_path[pos] == '/') {
const std::size_t p_len = pos;
const std::size_t n_len = wire_path.size() - (pos + 1);
if (p_len >= 1 && p_len <= 155 && n_len >= 1 && n_len <= 100) {
return true;
}
}
if (pos == 0) {
break;
}
}
return false;
}
[[nodiscard]] Void::Result::Result<void>
parse_pax_records(std::string_view payload, std::string& path_out,
std::string& link_out,
std::optional<std::uint64_t>& size_out,
std::size_t max_path_bytes)
{
std::size_t pos = 0;
while (pos < payload.size()) {
const std::size_t sp = payload.find(' ', pos);
if (sp == std::string_view::npos) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
"Archive: malformed PAX record length")};
}
std::size_t rec_len = 0;
const auto lr = std::from_chars(payload.data() + pos,
payload.data() + sp, rec_len);
if (lr.ec != std::errc{} || lr.ptr != payload.data() + sp ||
rec_len == 0 || pos + rec_len > payload.size() ||
sp >= pos + rec_len) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
"Archive: invalid PAX extended header record length")};
}
const std::string_view rec =
payload.substr(sp + 1, pos + rec_len - (sp + 1));
if (rec.empty() || rec.back() != '\n') {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
"Archive: PAX record missing trailing newline")};
}
const std::string_view kv = rec.substr(0, rec.size() - 1);
const std::size_t eq = kv.find('=');
if (eq == std::string_view::npos) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
"Archive: PAX record missing '='")};
}
const std::string_view key = kv.substr(0, eq);
const std::string_view val = kv.substr(eq + 1);
if (key == "path") {
if (val.size() > max_path_bytes + 1U) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive: PAX path exceeds configured limit")};
}
path_out.assign(val);
} else if (key == "linkpath") {
if (val.size() > max_path_bytes + 1U) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive: PAX linkpath exceeds configured limit")};
}
link_out.assign(val);
} else if (key == "size") {
std::uint64_t parsed_size = 0;
const auto sr = std::from_chars(
val.data(), val.data() + val.size(), parsed_size);
if (sr.ec != std::errc{} ||
sr.ptr != val.data() + val.size()) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
"Archive: invalid PAX size field")};
}
size_out = parsed_size;
}
pos += rec_len;
}
return {};
}
} // namespace
Void::Result::Result<void>
write_builtin_tar(ByteSink& sink,
std::span<const BuiltinCreateItem> items,
const CreationOptions& options)
{
const std::uint64_t mtime =
options.reproducible
? static_cast<std::uint64_t>(std::max<std::int64_t>(
0, options.canonical_mtime))
: static_cast<std::uint64_t>(std::max<std::int64_t>(
0,
std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch())
.count()));
const std::uint32_t uid =
options.reproducible ? options.canonical_uid : 0U;
const std::uint32_t gid =
options.reproducible ? options.canonical_gid : 0U;
std::array<std::byte, kTarBlockSize> hdr{};
std::vector<std::byte> io_buf(options.limits.transfer_buffer_bytes);
for (const auto& item : items) {
if (options.stop.stop_requested()) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::cancelled,
"Archive::create_archive: cancelled")};
}
const std::string wire_path =
item.is_directory ? (item.path + "/") : item.path;
const bool need_pax_path = !can_fit_ustar_path(wire_path);
const bool need_pax_size = item.size > 077777777777ULL;
if (need_pax_path || need_pax_size) {
std::string pax;
if (need_pax_path) {
pax += make_pax_record("path", wire_path);
}
if (need_pax_size) {
pax += make_pax_record("size", std::to_string(item.size));
}
std::string pax_name = "PaxHeaders.0/";
const std::size_t suffix_take = std::min<std::size_t>(
100U - pax_name.size(), item.path.size());
pax_name.append(item.path.substr(0, suffix_take));
build_ustar_header(hdr, pax_name, 'x', 0644U, 0U, 0U,
pax.size(), 0ULL);
if (auto w = sink.write(hdr); !w.has_value()) {
return w;
}
const auto pax_bytes =
std::as_bytes(std::span{pax.data(), pax.size()});
if (auto w = sink.write(pax_bytes); !w.has_value()) {
return w;
}
if (auto p = write_padding(sink, pax.size()); !p.has_value()) {
return p;
}
}
build_ustar_header(hdr, wire_path, item.is_directory ? '5' : '0',
item.mode, uid, gid, item.size, mtime);
if (auto w = sink.write(hdr); !w.has_value()) {
return w;
}
if (!item.is_directory) {
if (item.source_fd >= 0) {
#ifndef _WIN32
std::uint64_t remaining = item.size;
while (remaining > 0) {
const std::size_t want = static_cast<std::size_t>(
std::min<std::uint64_t>(remaining, io_buf.size()));
const ssize_t r =
::read(item.source_fd, io_buf.data(), want);
if (r < 0 && errno == EINTR) {
continue;
}
if (r <= 0) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::io_error,
"Archive::create_archive: source file shrunk "
"or read failed")};
}
if (auto w = sink.write(std::span<const std::byte>{
io_buf.data(), static_cast<std::size_t>(r)});
!w.has_value()) {
return w;
}
remaining -= static_cast<std::uint64_t>(r);
}
#endif
} else if (!item.inline_content.empty()) {
if (auto w = sink.write(item.inline_content);
!w.has_value()) {
return w;
}
}
if (auto p = write_padding(sink, item.size); !p.has_value()) {
return p;
}
}
}
// Standard two 512-byte zero EOF blocks.
std::array<std::byte, kTarBlockSize * 2> eof_blocks{};
return sink.write(eof_blocks);
}
BuiltinTarStream::BuiltinTarStream(
ByteSource& source, const ReadLimits& limits, std::stop_token stop,
std::optional<Void::Time::MonotonicClock::time_point> deadline,
const Void::Time::MonotonicClock& clock)
: m_source(&source), m_limits(limits), m_stop(std::move(stop)),
m_deadline(deadline), m_clock(&clock)
{
}
Void::Result::Result<void> BuiltinTarStream::check_stop_deadline() const
{
if (m_stop.stop_requested()) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::cancelled,
"Archive::Reader: operation cancelled")};
}
if (m_deadline.has_value() && m_clock->now() >= *m_deadline) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::timeout,
"Archive::Reader: deadline expired")};
}
return {};
}
Void::Result::Result<std::size_t>
BuiltinTarStream::read_exact_or_eof(std::span<std::byte> dst)
{
std::size_t filled = 0;
if (m_prefetch_off < m_prefetch.size()) {
const std::size_t take =
std::min(dst.size(), m_prefetch.size() - m_prefetch_off);
std::memcpy(dst.data(), m_prefetch.data() + m_prefetch_off, take);
m_prefetch_off += take;
filled += take;
if (m_prefetch_off == m_prefetch.size()) {
m_prefetch.clear();
m_prefetch_off = 0;
}
}
while (filled < dst.size()) {
if (auto chk = check_stop_deadline(); !chk.has_value()) {
return std::unexpected{std::move(chk.error())};
}
const std::size_t want = dst.size() - filled;
auto r = m_source->read(dst.subspan(filled, want));
if (!r.has_value()) {
return std::unexpected{std::move(r.error())};
}
if (*r == 0) {
break;
}
const auto n = static_cast<std::uint64_t>(*r);
if (n > m_limits.max_compressed_bytes - m_total_compressed) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive::Reader: compressed input exceeds limit")};
}
m_total_compressed += n;
filled += *r;
}
return filled;
}
Void::Result::Result<void>
BuiltinTarStream::read_exact_required(std::span<std::byte> dst,
const char* context)
{
auto n = read_exact_or_eof(dst);
if (!n.has_value()) {
return std::unexpected{std::move(n.error())};
}
if (*n != dst.size()) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
std::format("Archive::Reader: unexpected EOF while reading {}",
context))};
}
return {};
}
Void::Result::Result<void>
BuiltinTarStream::discard_bytes(std::uint64_t count,
const char* context)
{
std::array<std::byte, 4096> scratch{};
std::uint64_t rem = count;
while (rem > 0) {
const std::size_t want = static_cast<std::size_t>(
std::min<std::uint64_t>(rem, scratch.size()));
if (auto r = read_exact_required(std::span{scratch}.subspan(0, want),
context);
!r.has_value()) {
return r;
}
rem -= want;
}
return {};
}
Void::Result::Result<void> BuiltinTarStream::open()
{
if (auto chk = check_stop_deadline(); !chk.has_value()) {
return chk;
}
m_prefetch.resize(std::min<std::size_t>(512U,
m_limits.transfer_buffer_bytes));
auto r = m_source->read(m_prefetch);
if (!r.has_value()) {
return std::unexpected{std::move(r.error())};
}
m_prefetch.resize(*r);
m_prefetch_off = 0;
const auto n = static_cast<std::uint64_t>(*r);
if (n > m_limits.max_compressed_bytes) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive::Reader: input exceeds compressed limit")};
}
m_total_compressed = n;
if (*r == 0) {
m_reached_eof = true;
return {};
}
// Reject compressed streams cleanly when LibArchive is unavailable.
if (m_prefetch.size() >= 2 &&
m_prefetch[0] == std::byte{0x1F} &&
m_prefetch[1] == std::byte{0x8B}) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::unsupported_format,
"Archive::Reader: gzip archives require LibArchive backend")};
}
if (m_prefetch.size() >= 4 &&
m_prefetch[0] == std::byte{0x28} &&
m_prefetch[1] == std::byte{0xB5} &&
m_prefetch[2] == std::byte{0x2F} &&
m_prefetch[3] == std::byte{0xFD}) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::unsupported_format,
"Archive::Reader: zstd archives require LibArchive backend")};
}
return {};
}
Void::Result::Result<std::optional<BuiltinTarEntry>>
BuiltinTarStream::next_entry()
{
if (m_reached_eof) {
return std::optional<BuiltinTarEntry>{std::nullopt};
}
if (m_has_active_entry) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::conflict,
"Archive::Reader: active entry must be drained or skipped")};
}
std::string next_pax_path;
std::string next_pax_link;
std::optional<std::uint64_t> next_pax_size;
std::string global_pax_path;
std::string global_pax_link;
std::optional<std::uint64_t> global_pax_size;
std::string gnu_long_name;
std::string gnu_long_link;
std::array<std::byte, kTarBlockSize> hdr{};
for (;;) {
auto nread = read_exact_or_eof(hdr);
if (!nread.has_value()) {
return std::unexpected{std::move(nread.error())};
}
if (*nread == 0) {
m_reached_eof = true;
return std::optional<BuiltinTarEntry>{std::nullopt};
}
if (*nread != kTarBlockSize) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
"Archive::Reader: truncated tar header block")};
}
if (is_zero_block(hdr)) {
m_reached_eof = true;
return std::optional<BuiltinTarEntry>{std::nullopt};
}
auto recorded_sum = parse_octal(std::span{hdr}.subspan(148, 8),
"chksum");
if (!recorded_sum.has_value()) {
return std::unexpected{std::move(recorded_sum.error())};
}
const std::uint32_t usum = compute_checksum_unsigned(hdr);
const std::int32_t ssum = compute_checksum_signed(hdr);
if (*recorded_sum != usum &&
static_cast<std::int64_t>(*recorded_sum) !=
static_cast<std::int64_t>(ssum)) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
"Archive::Reader: tar header checksum mismatch")};
}
auto parsed_mode =
parse_octal(std::span{hdr}.subspan(100, 8), "mode");
if (!parsed_mode.has_value()) {
return std::unexpected{std::move(parsed_mode.error())};
}
auto parsed_size =
parse_octal(std::span{hdr}.subspan(124, 12), "size");
if (!parsed_size.has_value()) {
return std::unexpected{std::move(parsed_size.error())};
}
const char typeflag = static_cast<char>(std::to_integer<unsigned char>(hdr[156]));
if (typeflag == 'x' || typeflag == 'g' || typeflag == 'L' ||
typeflag == 'K') {
if (*parsed_size > m_limits.max_metadata_bytes ||
*parsed_size >
m_limits.max_metadata_bytes - m_metadata_budget_used) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive::Reader: tar extended header exceeds metadata "
"limit")};
}
m_metadata_budget_used += static_cast<std::size_t>(*parsed_size);
std::string payload(static_cast<std::size_t>(*parsed_size), '\0');
if (!payload.empty()) {
if (auto rr = read_exact_required(
std::as_writable_bytes(std::span{payload}),
"extended tar header");
!rr.has_value()) {
return std::unexpected{std::move(rr.error())};
}
}
const std::size_t pad =
static_cast<std::size_t>((kTarBlockSize - (*parsed_size % kTarBlockSize)) % kTarBlockSize);
if (pad > 0) {
if (auto dr = discard_bytes(pad, "extended header padding");
!dr.has_value()) {
return std::unexpected{std::move(dr.error())};
}
}
if (typeflag == 'x') {
if (auto pr = parse_pax_records(
payload, next_pax_path, next_pax_link,
next_pax_size, m_limits.max_path_bytes);
!pr.has_value()) {
return std::unexpected{std::move(pr.error())};
}
} else if (typeflag == 'g') {
if (auto pr = parse_pax_records(
payload, global_pax_path, global_pax_link,
global_pax_size, m_limits.max_path_bytes);
!pr.has_value()) {
return std::unexpected{std::move(pr.error())};
}
} else {
while (!payload.empty() && payload.back() == '\0') {
payload.pop_back();
}
if (payload.size() > m_limits.max_path_bytes + 1U) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive::Reader: GNU long name exceeds limit")};
}
if (typeflag == 'L') {
gnu_long_name = std::move(payload);
} else {
gnu_long_link = std::move(payload);
}
}
continue;
}
const std::string_view magic_view =
c_field(std::span{hdr}.subspan(257, 6));
std::string path;
if (!next_pax_path.empty()) {
path = std::move(next_pax_path);
} else if (!gnu_long_name.empty()) {
path = std::move(gnu_long_name);
} else if (!global_pax_path.empty()) {
path = global_pax_path;
} else {
const std::string_view name =
c_field(std::span{hdr}.subspan(0, 100));
const std::string_view prefix =
magic_view.starts_with("ustar")
? c_field(std::span{hdr}.subspan(345, 155))
: std::string_view{};
if (!prefix.empty()) {
path = std::string{prefix} + "/" + std::string{name};
} else {
path.assign(name);
}
}
std::string link;
if (!next_pax_link.empty()) {
link = std::move(next_pax_link);
} else if (!gnu_long_link.empty()) {
link = std::move(gnu_long_link);
} else if (!global_pax_link.empty()) {
link = global_pax_link;
} else {
link.assign(c_field(std::span{hdr}.subspan(157, 100)));
}
const std::uint64_t entry_size =
next_pax_size.has_value()
? *next_pax_size
: (global_pax_size.has_value() ? *global_pax_size
: *parsed_size);
EntryType etype = EntryType::Other;
if (typeflag == '1') {
etype = EntryType::Hardlink;
} else if (typeflag == '2') {
etype = EntryType::Symlink;
} else if (typeflag == '5') {
etype = EntryType::Directory;
} else if (typeflag == '0' || typeflag == '\0') {
if (typeflag == '\0' && !magic_view.starts_with("ustar") &&
entry_size == 0 && path.ends_with('/')) {
etype = EntryType::Directory;
} else {
etype = EntryType::RegularFile;
}
}
BuiltinTarEntry out{};
out.path = std::move(path);
out.linkname = std::move(link);
out.type = etype;
out.mode = static_cast<std::uint32_t>(*parsed_mode & 07777ULL);
out.declared_size =
(etype == EntryType::RegularFile) ? entry_size : 0ULL;
m_entry_size = (etype == EntryType::RegularFile) ? entry_size : 0ULL;
m_entry_remaining = m_entry_size;
m_has_active_entry = (etype == EntryType::RegularFile);
// Non-regular entries with declared non-zero payload must advance
// over padding if any (standard tar has 0 size for dirs/links).
if (!m_has_active_entry && entry_size > 0) {
const std::uint64_t pad =
(kTarBlockSize - (entry_size % kTarBlockSize)) % kTarBlockSize;
if (auto dr = discard_bytes(entry_size + pad,
"non-regular entry payload");
!dr.has_value()) {
return std::unexpected{std::move(dr.error())};
}
}
return std::optional<BuiltinTarEntry>{std::move(out)};
}
}
Void::Result::Result<void> BuiltinTarStream::finish_active_entry_padding()
{
m_has_active_entry = false;
const std::uint64_t pad =
(kTarBlockSize - (m_entry_size % kTarBlockSize)) % kTarBlockSize;
m_entry_size = 0;
m_entry_remaining = 0;
if (pad > 0) {
return discard_bytes(pad, "tar entry block padding");
}
return {};
}
Void::Result::Result<std::size_t>
BuiltinTarStream::read_entry_data(std::span<std::byte> dst)
{
if (!m_has_active_entry) {
return std::size_t{0};
}
if (m_entry_remaining == 0) {
if (auto fin = finish_active_entry_padding(); !fin.has_value()) {
return std::unexpected{std::move(fin.error())};
}
return std::size_t{0};
}
if (dst.empty()) {
return std::size_t{0};
}
const std::size_t want = static_cast<std::size_t>(
std::min<std::uint64_t>(dst.size(), m_entry_remaining));
if (auto rr = read_exact_required(dst.subspan(0, want),
"tar entry data");
!rr.has_value()) {
return std::unexpected{std::move(rr.error())};
}
m_entry_remaining -= want;
if (m_entry_remaining == 0) {
if (auto fin = finish_active_entry_padding(); !fin.has_value()) {
return std::unexpected{std::move(fin.error())};
}
}
return want;
}
Void::Result::Result<std::uint64_t> BuiltinTarStream::skip_entry_data()
{
if (!m_has_active_entry) {
return std::uint64_t{0};
}
const std::uint64_t skipped = m_entry_remaining;
const std::uint64_t rem = m_entry_remaining;
m_entry_remaining = 0;
if (rem > 0) {
if (auto dr = discard_bytes(rem, "tar entry data");
!dr.has_value()) {
return std::unexpected{std::move(dr.error())};
}
}
if (auto fin = finish_active_entry_padding(); !fin.has_value()) {
return std::unexpected{std::move(fin.error())};
}
return skipped;
}
} // namespace Void::Archive::Detail
+93
View File
@@ -0,0 +1,93 @@
#pragma once
#include <Void/Archive/Types.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <span>
#include <stop_token>
#include <string>
namespace Void::Archive::Detail
{
struct BuiltinCreateItem {
std::string path{};
bool is_directory{false};
std::uint32_t mode{0644};
std::uint64_t size{0};
std::span<const std::byte> inline_content{};
int source_fd{-1};
};
[[nodiscard]] Void::Result::Result<void>
write_builtin_tar(ByteSink& sink,
std::span<const BuiltinCreateItem> items,
const CreationOptions& options);
struct BuiltinTarEntry {
std::string path{};
std::string linkname{};
EntryType type{EntryType::RegularFile};
std::uint64_t declared_size{0};
std::uint32_t mode{0644};
};
class BuiltinTarStream
{
public:
BuiltinTarStream(
ByteSource& source, const ReadLimits& limits,
std::stop_token stop,
std::optional<Void::Time::MonotonicClock::time_point> deadline,
const Void::Time::MonotonicClock& clock);
[[nodiscard]] Void::Result::Result<void> open();
[[nodiscard]] Void::Result::Result<std::optional<BuiltinTarEntry>>
next_entry();
[[nodiscard]] Void::Result::Result<std::size_t>
read_entry_data(std::span<std::byte> dst);
[[nodiscard]] Void::Result::Result<std::uint64_t> skip_entry_data();
[[nodiscard]] std::uint64_t total_compressed_bytes() const noexcept
{
return m_total_compressed;
}
private:
[[nodiscard]] Void::Result::Result<void> check_stop_deadline() const;
[[nodiscard]] Void::Result::Result<std::size_t>
read_exact_or_eof(std::span<std::byte> dst);
[[nodiscard]] Void::Result::Result<void>
read_exact_required(std::span<std::byte> dst,
const char* context);
[[nodiscard]] Void::Result::Result<void>
discard_bytes(std::uint64_t count, const char* context);
[[nodiscard]] Void::Result::Result<void>
finish_active_entry_padding();
ByteSource* m_source{nullptr};
ReadLimits m_limits{};
std::stop_token m_stop{};
std::optional<Void::Time::MonotonicClock::time_point> m_deadline{};
const Void::Time::MonotonicClock* m_clock{
&Void::Time::SystemMonotonicClock::instance()};
std::vector<std::byte> m_prefetch{};
std::size_t m_prefetch_off{0};
std::uint64_t m_total_compressed{0};
bool m_reached_eof{false};
bool m_has_active_entry{false};
std::uint64_t m_entry_size{0};
std::uint64_t m_entry_remaining{0};
std::size_t m_metadata_budget_used{0};
};
} // namespace Void::Archive::Detail
+326 -21
View File
@@ -1,6 +1,8 @@
#include <Void/Archive/Archive.hpp> #include <Void/Archive/Archive.hpp>
#include <Void/System/Process.hpp> #include <Void/System/Process.hpp>
#include "BuiltinTar.hpp"
#include <algorithm> #include <algorithm>
#include <array> #include <array>
#include <atomic> #include <atomic>
@@ -18,8 +20,10 @@
#include <utility> #include <utility>
#include <vector> #include <vector>
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
#include <archive.h> #include <archive.h>
#include <archive_entry.h> #include <archive_entry.h>
#endif
#ifndef _WIN32 #ifndef _WIN32
#include <dirent.h> #include <dirent.h>
@@ -51,12 +55,14 @@ namespace Void::Archive
constexpr std::string_view kInventoryFilename = "inventory.txt"; constexpr std::string_view kInventoryFilename = "inventory.txt";
constexpr std::string_view kTreeSubdir = "tree"; constexpr std::string_view kTreeSubdir = "tree";
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
using ArchiveReadPtr = using ArchiveReadPtr =
std::unique_ptr<archive, decltype(&archive_read_free)>; std::unique_ptr<archive, decltype(&archive_read_free)>;
using ArchiveWritePtr = using ArchiveWritePtr =
std::unique_ptr<archive, decltype(&archive_write_free)>; std::unique_ptr<archive, decltype(&archive_write_free)>;
using ArchiveEntryPtr = using ArchiveEntryPtr =
std::unique_ptr<archive_entry, decltype(&archive_entry_free)>; std::unique_ptr<archive_entry, decltype(&archive_entry_free)>;
#endif
class OwnedFd class OwnedFd
{ {
@@ -129,6 +135,7 @@ namespace Void::Archive
std::error_code{err, std::generic_category()}); std::error_code{err, std::generic_category()});
} }
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
[[nodiscard]] Void::Result::Error [[nodiscard]] Void::Result::Error
make_libarchive_error(archive* a, std::string_view op, make_libarchive_error(archive* a, std::string_view op,
ArchiveErrorCode fallback = ArchiveErrorCode fallback =
@@ -140,6 +147,7 @@ namespace Void::Archive
return make_archive_error(fallback, return make_archive_error(fallback,
std::format("Archive: {}: {}", op, detail)); std::format("Archive: {}: {}", op, detail));
} }
#endif
[[nodiscard]] bool is_safe_single_component( [[nodiscard]] bool is_safe_single_component(
std::string_view name, std::size_t max_bytes = 255) noexcept std::string_view name, std::size_t max_bytes = 255) noexcept
@@ -894,6 +902,15 @@ namespace Void::Archive
} }
} // namespace } // namespace
bool has_libarchive_backend() noexcept
{
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
return true;
#else
return false;
#endif
}
std::string sanitize_diagnostic_path(std::string_view raw) noexcept std::string sanitize_diagnostic_path(std::string_view raw) noexcept
{ {
std::string out; std::string out;
@@ -1088,10 +1105,14 @@ namespace Void::Archive
std::optional<Void::Time::MonotonicClock::time_point> deadline{}; std::optional<Void::Time::MonotonicClock::time_point> deadline{};
const Void::Time::MonotonicClock* clock{ const Void::Time::MonotonicClock* clock{
&Void::Time::SystemMonotonicClock::instance()}; &Void::Time::SystemMonotonicClock::instance()};
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
ArchiveReadPtr handle{nullptr, &archive_read_free}; ArchiveReadPtr handle{nullptr, &archive_read_free};
std::vector<std::byte> read_buf{}; std::vector<std::byte> read_buf{};
PathTracker tracker;
std::optional<Void::Result::Error> source_error{}; std::optional<Void::Result::Error> source_error{};
#endif
std::unique_ptr<Detail::BuiltinTarStream> builtin_stream{};
bool using_builtin{false};
PathTracker tracker;
bool has_active_file{false}; bool has_active_file{false};
bool reached_eof{false}; bool reached_eof{false};
bool poisoned{false}; bool poisoned{false};
@@ -1101,7 +1122,10 @@ namespace Void::Archive
std::uint64_t total_compressed{0}; std::uint64_t total_compressed{0};
explicit Impl(const ReadLimits& lim) explicit Impl(const ReadLimits& lim)
: limits(lim), read_buf(lim.transfer_buffer_bytes), : limits(lim),
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
read_buf(lim.transfer_buffer_bytes),
#endif
tracker(lim.max_metadata_bytes) tracker(lim.max_metadata_bytes)
{ {
} }
@@ -1121,6 +1145,7 @@ namespace Void::Archive
return {}; return {};
} }
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
static la_ssize_t libarchive_read_cb(archive* a, void* client_data, static la_ssize_t libarchive_read_cb(archive* a, void* client_data,
const void** buffer) const void** buffer)
{ {
@@ -1150,6 +1175,7 @@ namespace Void::Archive
*buffer = self->read_buf.data(); *buffer = self->read_buf.data();
return static_cast<la_ssize_t>(n); return static_cast<la_ssize_t>(n);
} }
#endif
}; };
Reader::Reader(std::unique_ptr<Impl> impl) noexcept Reader::Reader(std::unique_ptr<Impl> impl) noexcept
@@ -1178,6 +1204,7 @@ namespace Void::Archive
return std::unexpected{std::move(chk.error())}; return std::unexpected{std::move(chk.error())};
} }
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
impl->handle = impl->handle =
ArchiveReadPtr{archive_read_new(), &archive_read_free}; ArchiveReadPtr{archive_read_new(), &archive_read_free};
if (!impl->handle) { if (!impl->handle) {
@@ -1185,6 +1212,7 @@ namespace Void::Archive
ArchiveErrorCode::io_error, ArchiveErrorCode::io_error,
"Archive::Reader: cannot allocate libarchive reader")}; "Archive::Reader: cannot allocate libarchive reader")};
} }
(void)archive_read_support_filter_gzip(impl->handle.get());
(void)archive_read_support_filter_zstd(impl->handle.get()); (void)archive_read_support_filter_zstd(impl->handle.get());
(void)archive_read_support_filter_none(impl->handle.get()); (void)archive_read_support_filter_none(impl->handle.get());
(void)archive_read_support_format_tar(impl->handle.get()); (void)archive_read_support_format_tar(impl->handle.get());
@@ -1199,6 +1227,16 @@ namespace Void::Archive
impl->handle.get(), "open archive", impl->handle.get(), "open archive",
ArchiveErrorCode::unsupported_format)}; ArchiveErrorCode::unsupported_format)};
} }
impl->using_builtin = false;
#else
impl->builtin_stream = std::make_unique<Detail::BuiltinTarStream>(
source, limits, stop, deadline, clock);
if (auto opened = impl->builtin_stream->open(); !opened.has_value()) {
return std::unexpected{std::move(opened.error())};
}
impl->total_compressed = impl->builtin_stream->total_compressed_bytes();
impl->using_builtin = true;
#endif
return Reader{std::move(impl)}; return Reader{std::move(impl)};
} }
@@ -1242,6 +1280,91 @@ namespace Void::Archive
return std::unexpected{std::move(chk.error())}; return std::unexpected{std::move(chk.error())};
} }
if (m_impl->using_builtin) {
auto next = m_impl->builtin_stream->next_entry();
m_impl->total_compressed =
m_impl->builtin_stream->total_compressed_bytes();
if (!next.has_value()) {
m_impl->poisoned = true;
return std::unexpected{std::move(next.error())};
}
if (!next->has_value()) {
m_impl->reached_eof = true;
return std::optional<EntryInfo>{std::nullopt};
}
if (m_impl->entries_seen >= m_impl->limits.max_entries) {
m_impl->poisoned = true;
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive::Reader: entry count exceeds limit")};
}
++m_impl->entries_seen;
const auto& raw = **next;
if (raw.path.empty()) {
m_impl->poisoned = true;
return std::unexpected{make_archive_error(
ArchiveErrorCode::unsafe_entry,
"Archive::Reader: entry has no pathname")};
}
if (raw.type == EntryType::Hardlink ||
raw.type == EntryType::Symlink || !raw.linkname.empty()) {
m_impl->poisoned = true;
return std::unexpected{make_archive_error(
ArchiveErrorCode::unsafe_entry,
std::format("Archive::Reader: links are not allowed ('{}')",
sanitize_diagnostic_path(raw.path)))};
}
if (raw.type != EntryType::Directory &&
raw.type != EntryType::RegularFile) {
m_impl->poisoned = true;
return std::unexpected{make_archive_error(
ArchiveErrorCode::unsafe_entry,
std::format("Archive::Reader: special files are not allowed "
"('{}')",
sanitize_diagnostic_path(raw.path)))};
}
const bool is_dir = (raw.type == EntryType::Directory);
auto vp = validate_archive_path(raw.path, is_dir, m_impl->limits);
if (!vp.has_value()) {
m_impl->poisoned = true;
return std::unexpected{std::move(vp.error())};
}
if (auto rec = m_impl->tracker.record(*vp, is_dir);
!rec.has_value()) {
m_impl->poisoned = true;
return std::unexpected{std::move(rec.error())};
}
std::uint64_t declared_size = 0;
bool executable = false;
if (!is_dir) {
declared_size = raw.declared_size;
if (declared_size > m_impl->limits.max_file_bytes ||
declared_size > m_impl->limits.max_total_bytes -
m_impl->total_decompressed) {
m_impl->poisoned = true;
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive::Reader: declared entry size exceeds policy")};
}
executable = (raw.mode & 0111U) != 0U;
m_impl->has_active_file = true;
m_impl->entry_bytes_read = 0;
}
return std::optional<EntryInfo>{EntryInfo{
.path = std::move(vp->normalized),
.type = is_dir ? EntryType::Directory : EntryType::RegularFile,
.declared_size = declared_size,
.safe_mode = is_dir ? 0755U : (executable ? 0755U : 0644U),
.executable = executable,
.accepted = true,
}};
}
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
archive_entry* entry = nullptr; archive_entry* entry = nullptr;
const int status = const int status =
archive_read_next_header(m_impl->handle.get(), &entry); archive_read_next_header(m_impl->handle.get(), &entry);
@@ -1335,6 +1458,12 @@ namespace Void::Archive
.executable = executable, .executable = executable,
.accepted = true, .accepted = true,
}}; }};
#else
m_impl->poisoned = true;
return std::unexpected{make_archive_error(
ArchiveErrorCode::unsupported_format,
"Archive::Reader: libarchive backend unavailable")};
#endif
} }
Void::Result::Result<std::size_t> Void::Result::Result<std::size_t>
@@ -1358,21 +1487,46 @@ namespace Void::Archive
const std::size_t to_read = const std::size_t to_read =
std::min(dst.size(), m_impl->limits.transfer_buffer_bytes); std::min(dst.size(), m_impl->limits.transfer_buffer_bytes);
const la_ssize_t n = std::size_t read_bytes = 0;
archive_read_data(m_impl->handle.get(), dst.data(), to_read); if (m_impl->using_builtin) {
if (n == 0) { auto r =
m_impl->has_active_file = false; m_impl->builtin_stream->read_entry_data(dst.subspan(0, to_read));
return std::size_t{0}; m_impl->total_compressed =
} m_impl->builtin_stream->total_compressed_bytes();
if (n < 0) { if (!r.has_value()) {
m_impl->poisoned = true; m_impl->poisoned = true;
if (m_impl->source_error.has_value()) { return std::unexpected{std::move(r.error())};
return std::unexpected{std::move(*m_impl->source_error)};
} }
return std::unexpected{ read_bytes = *r;
make_libarchive_error(m_impl->handle.get(), "read entry data")}; if (read_bytes == 0) {
m_impl->has_active_file = false;
return std::size_t{0};
}
} else {
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
const la_ssize_t n =
archive_read_data(m_impl->handle.get(), dst.data(), to_read);
if (n == 0) {
m_impl->has_active_file = false;
return std::size_t{0};
}
if (n < 0) {
m_impl->poisoned = true;
if (m_impl->source_error.has_value()) {
return std::unexpected{std::move(*m_impl->source_error)};
}
return std::unexpected{make_libarchive_error(
m_impl->handle.get(), "read entry data")};
}
read_bytes = static_cast<std::size_t>(n);
#else
m_impl->poisoned = true;
return std::unexpected{make_archive_error(
ArchiveErrorCode::unsupported_format,
"Archive::Reader: libarchive backend unavailable")};
#endif
} }
const auto amount = static_cast<std::uint64_t>(n); const auto amount = static_cast<std::uint64_t>(read_bytes);
if (amount > m_impl->limits.max_file_bytes - m_impl->entry_bytes_read || if (amount > m_impl->limits.max_file_bytes - m_impl->entry_bytes_read ||
amount > m_impl->limits.max_total_bytes - amount > m_impl->limits.max_total_bytes -
m_impl->total_decompressed) { m_impl->total_decompressed) {
@@ -1383,7 +1537,7 @@ namespace Void::Archive
} }
m_impl->entry_bytes_read += amount; m_impl->entry_bytes_read += amount;
m_impl->total_decompressed += amount; m_impl->total_decompressed += amount;
return static_cast<std::size_t>(n); return read_bytes;
} }
Void::Result::Result<std::uint64_t> Reader::skip_entry() Void::Result::Result<std::uint64_t> Reader::skip_entry()
@@ -1462,6 +1616,7 @@ namespace Void::Archive
} }
// Opt-in forensic listing: reports rejected entries without writing. // Opt-in forensic listing: reports rejected entries without writing.
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
struct ForensicState { struct ForensicState {
ByteSource* source{nullptr}; ByteSource* source{nullptr};
ReadLimits limits{}; ReadLimits limits{};
@@ -1477,6 +1632,7 @@ namespace Void::Archive
ArchiveErrorCode::io_error, ArchiveErrorCode::io_error,
"Archive::list_entries: cannot allocate reader")}; "Archive::list_entries: cannot allocate reader")};
} }
(void)archive_read_support_filter_gzip(handle.get());
(void)archive_read_support_filter_zstd(handle.get()); (void)archive_read_support_filter_zstd(handle.get());
(void)archive_read_support_filter_none(handle.get()); (void)archive_read_support_filter_none(handle.get());
(void)archive_read_support_format_tar(handle.get()); (void)archive_read_support_format_tar(handle.get());
@@ -1592,6 +1748,88 @@ namespace Void::Archive
(void)archive_read_data_skip(handle.get()); (void)archive_read_data_skip(handle.get());
} }
return out; return out;
#else
Detail::BuiltinTarStream stream{
source, limits, {}, std::nullopt,
Void::Time::SystemMonotonicClock::instance()};
if (auto opened = stream.open(); !opened.has_value()) {
return std::unexpected{std::move(opened.error())};
}
std::vector<EntryInfo> out;
PathTracker tracker{limits.max_metadata_bytes};
std::size_t metadata_bytes = 0;
for (;;) {
auto next = stream.next_entry();
if (!next.has_value()) {
return std::unexpected{std::move(next.error())};
}
if (!next->has_value()) {
break;
}
if (out.size() >= limits.max_entries) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive::list_entries: entry count exceeds limit")};
}
const auto& raw = **next;
const std::string sanitized =
raw.path.empty() ? "<missing>"
: sanitize_diagnostic_path(raw.path);
if (sanitized.size() + 64U > limits.max_metadata_bytes ||
metadata_bytes >
limits.max_metadata_bytes - (sanitized.size() + 64U)) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive::list_entries: metadata limit exceeded")};
}
metadata_bytes += sanitized.size() + 64U;
EntryInfo info;
info.path = sanitized;
if (raw.type == EntryType::Hardlink) {
info.type = EntryType::Hardlink;
info.accepted = false;
info.rejection_reason = "hardlink disallowed";
} else if (raw.type == EntryType::Symlink ||
!raw.linkname.empty()) {
info.type = EntryType::Symlink;
info.accepted = false;
info.rejection_reason = "symlink disallowed";
} else if (raw.type != EntryType::Directory &&
raw.type != EntryType::RegularFile) {
info.type = EntryType::Other;
info.accepted = false;
info.rejection_reason = "special file disallowed";
} else {
const bool is_dir = (raw.type == EntryType::Directory);
info.type =
is_dir ? EntryType::Directory : EntryType::RegularFile;
info.declared_size = raw.declared_size;
info.executable = !is_dir && ((raw.mode & 0111U) != 0U);
info.safe_mode =
is_dir ? 0755U : (info.executable ? 0755U : 0644U);
auto vp = validate_archive_path(raw.path, is_dir, limits);
if (!vp.has_value()) {
info.accepted = false;
info.rejection_reason = vp.error().message();
} else if (auto rec = tracker.record(*vp, is_dir);
!rec.has_value()) {
info.accepted = false;
info.rejection_reason = rec.error().message();
} else {
info.path = std::move(vp->normalized);
info.accepted = true;
}
}
out.push_back(std::move(info));
if (auto sk = stream.skip_entry_data(); !sk.has_value()) {
return std::unexpected{std::move(sk.error())};
}
}
return out;
#endif
} }
Void::Result::Result<std::vector<EntryInfo>> Void::Result::Result<std::vector<EntryInfo>>
@@ -2314,6 +2552,30 @@ namespace Void::Archive
return a.path < b.path; return a.path < b.path;
}); });
if (options.compression == ArchiveCompression::None &&
(options.prefer_builtin_tar || !has_libarchive_backend())) {
std::vector<Detail::BuiltinCreateItem> builtin_items;
builtin_items.reserve(normalized.size());
for (const auto& item : normalized) {
const bool is_dir = (item.src->type == EntryType::Directory);
const std::uint32_t perm =
item.src->mode.has_value()
? (*item.src->mode & 0777U)
: (is_dir ? 0755U
: (item.src->executable ? 0755U : 0644U));
builtin_items.push_back(Detail::BuiltinCreateItem{
.path = item.path,
.is_directory = is_dir,
.mode = perm,
.size = item.size,
.inline_content = item.src->content,
.source_fd = item.file_fd.get(),
});
}
return Detail::write_builtin_tar(sink, builtin_items, options);
}
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
struct SinkBridge { struct SinkBridge {
ByteSink* sink{nullptr}; ByteSink* sink{nullptr};
std::optional<Void::Result::Error> err{}; std::optional<Void::Result::Error> err{};
@@ -2331,6 +2593,19 @@ namespace Void::Archive
return std::unexpected{ return std::unexpected{
make_libarchive_error(writer.get(), "add zstd filter")}; make_libarchive_error(writer.get(), "add zstd filter")};
} }
} else if (options.compression == ArchiveCompression::Gzip) {
if (archive_write_add_filter_gzip(writer.get()) != ARCHIVE_OK) {
return std::unexpected{
make_libarchive_error(writer.get(), "add gzip filter")};
}
if (options.reproducible) {
if (archive_write_set_filter_option(
writer.get(), "gzip", "timestamp", nullptr) !=
ARCHIVE_OK) {
return std::unexpected{make_libarchive_error(
writer.get(), "disable gzip timestamp header")};
}
}
} else { } else {
if (archive_write_add_filter_none(writer.get()) != ARCHIVE_OK) { if (archive_write_add_filter_none(writer.get()) != ARCHIVE_OK) {
return std::unexpected{ return std::unexpected{
@@ -2380,14 +2655,24 @@ namespace Void::Archive
const bool is_dir = (item.src->type == EntryType::Directory); const bool is_dir = (item.src->type == EntryType::Directory);
const std::string wire_path = const std::string wire_path =
is_dir ? (item.path + "/") : item.path; is_dir ? (item.path + "/") : item.path;
const std::uint32_t perm =
item.src->mode.has_value()
? (*item.src->mode & 0777U)
: (is_dir ? 0755U
: (item.src->executable ? 0755U : 0644U));
archive_entry_set_pathname(ae.get(), wire_path.c_str()); archive_entry_set_pathname(ae.get(), wire_path.c_str());
archive_entry_set_filetype(ae.get(), is_dir ? AE_IFDIR : AE_IFREG); archive_entry_set_filetype(ae.get(), is_dir ? AE_IFDIR : AE_IFREG);
archive_entry_set_perm( archive_entry_set_perm(ae.get(), static_cast<mode_t>(perm));
ae.get(), is_dir ? 0755 : (item.src->executable ? 0755 : 0644));
if (options.reproducible) { if (options.reproducible) {
archive_entry_set_mtime(ae.get(), 0, 0); archive_entry_set_mtime(
archive_entry_set_uid(ae.get(), 0); ae.get(),
archive_entry_set_gid(ae.get(), 0); static_cast<std::time_t>(
std::max<std::int64_t>(0, options.canonical_mtime)),
0);
archive_entry_set_uid(
ae.get(), static_cast<la_int64_t>(options.canonical_uid));
archive_entry_set_gid(
ae.get(), static_cast<la_int64_t>(options.canonical_gid));
archive_entry_set_uname(ae.get(), ""); archive_entry_set_uname(ae.get(), "");
archive_entry_set_gname(ae.get(), ""); archive_entry_set_gname(ae.get(), "");
} }
@@ -2473,6 +2758,12 @@ namespace Void::Archive
make_libarchive_error(writer.get(), "close archive writer")}; make_libarchive_error(writer.get(), "close archive writer")};
} }
return {}; return {};
#else
return std::unexpected{make_archive_error(
ArchiveErrorCode::unsupported_format,
"Archive::create_archive: compressed archives require "
"LibArchive backend")};
#endif
} }
Void::Result::Result<void> Void::Result::Result<void>
@@ -2491,6 +2782,20 @@ namespace Void::Archive
return sink->sync_and_close(); return sink->sync_and_close();
} }
Void::Result::Result<void> create(ByteSink& sink,
std::span<const CreateEntry> entries,
const CreationOptions& options)
{
return create_archive(sink, entries, options);
}
Void::Result::Result<void> create(const std::filesystem::path& output_path,
std::span<const CreateEntry> entries,
const CreationOptions& options)
{
return create_archive(output_path, entries, options);
}
// ── Isolated Child Decoder Profile ─────────────────────────────────────── // ── Isolated Child Decoder Profile ───────────────────────────────────────
Void::Result::Result<StagedTree> Void::Result::Result<StagedTree>
+16 -1
View File
@@ -1,4 +1,19 @@
set(_void_archive_ext_deps "")
set(_void_archive_has_libarchive 0)
if(NOT CMAKE_DISABLE_FIND_PACKAGE_LibArchive)
if(NOT TARGET LibArchive::LibArchive)
find_package(LibArchive QUIET)
endif()
if(TARGET LibArchive::LibArchive)
list(APPEND _void_archive_ext_deps LibArchive::LibArchive)
set(_void_archive_has_libarchive 1)
endif()
endif()
void_add_module(Archive void_add_module(Archive
INTERNAL_DEPS Functional Time System INTERNAL_DEPS Functional Time System
EXTERNAL_DEPS LibArchive::LibArchive EXTERNAL_DEPS ${_void_archive_ext_deps}
)
target_compile_definitions(Void_Archive PUBLIC
VOID_ARCHIVE_HAS_LIBARCHIVE=${_void_archive_has_libarchive}
) )
+275 -76
View File
@@ -7,108 +7,284 @@ namespace Void::Argparse
Parser::Parser(std::string program, std::string description) Parser::Parser(std::string program, std::string description)
: program_{std::move(program)}, description_{std::move(description)} : program_{std::move(program)}, description_{std::move(description)}
{}
Parser& Parser::flag(std::string_view lng, std::string_view sht,
std::string_view desc, bool& out)
{ {
flags_.push_back({std::string{lng}, std::string{sht}, std::string{desc}, &out}); }
Parser::~Parser() = default;
Parser::Parser(Parser&&) noexcept = default;
Parser& Parser::operator=(Parser&&) noexcept = default;
Parser& Parser::flag(std::string_view lng,
std::string_view sht,
std::string_view desc,
bool& out)
{
flags_.push_back(
{std::string{lng}, std::string{sht}, std::string{desc}, &out});
return *this; return *this;
} }
Parser& Parser::option(std::string_view lng, std::string_view sht, Parser& Parser::option(std::string_view lng,
std::string_view desc, std::optional<std::string>& out) std::string_view sht,
std::string_view desc,
std::optional<std::string>& out)
{ {
options_.push_back({std::string{lng}, std::string{sht}, std::string{desc}, {}, &out, nullptr}); options_.push_back(
{std::string{lng}, std::string{sht}, std::string{desc}, {}, &out, nullptr, nullptr});
return *this; return *this;
} }
Parser& Parser::option_default(std::string_view lng, std::string_view sht, Parser& Parser::option_many(std::string_view lng,
std::string_view desc, std::string& out, std::string_view sht,
std::string_view default_value) std::string_view desc,
std::vector<std::string>& out)
{
options_.push_back(
{std::string{lng}, std::string{sht}, std::string{desc}, {}, nullptr, nullptr, &out});
return *this;
}
Parser& Parser::option_default(std::string_view lng,
std::string_view sht,
std::string_view desc,
std::string& out,
std::string_view default_value)
{ {
out = std::string{default_value}; out = std::string{default_value};
options_.push_back({std::string{lng}, std::string{sht}, std::string{desc}, options_.push_back({std::string{lng},
std::string{default_value}, nullptr, &out}); std::string{sht},
std::string{desc},
std::string{default_value},
nullptr,
&out,
nullptr});
return *this; return *this;
} }
Parser& Parser::positional(std::string_view name, std::string_view desc, std::string& out) Parser& Parser::positional(std::string_view name,
std::string_view desc,
std::string& out)
{ {
positionals_.push_back({std::string{name}, std::string{desc}, &out}); positionals_.push_back({std::string{name}, std::string{desc}, &out});
return *this; return *this;
} }
std::expected<void, std::string> Parser& Parser::positional_many(std::string_view name,
Parser::parse(int argc, const char* const* argv) const std::string_view desc,
std::vector<std::string>& out,
bool required)
{ {
positional_many_ = MultiPosEntry{
std::string{name}, std::string{desc}, &out, required};
return *this;
}
Parser& Parser::subcommand(std::string name,
std::string description,
std::function<void()> on_selected)
{
const std::string sub_prog =
program_.empty() ? name : (program_ + " " + name);
auto sub_parser = std::make_unique<Parser>(sub_prog, std::move(description));
Parser* raw = sub_parser.get();
subcommands_.push_back(SubcommandEntry{
.name = std::move(name),
.parser = std::move(sub_parser),
.on_selected = std::move(on_selected),
});
return *raw;
}
Parser& Parser::require_subcommand(bool required) noexcept
{
has_explicit_require_sub_ = true;
require_subcommand_ = required;
return *this;
}
ParseResult Parser::parse_detailed(int argc, const char* const* argv) const
{
const Parser* active = this;
std::size_t pos_idx = 0; std::size_t pos_idx = 0;
bool after_double_dash = false;
std::vector<std::string> matched_path;
std::vector<const std::function<void()>*> callbacks;
auto match_flag_or_opt = [&](const Parser* p,
std::string_view arg,
int& i,
bool& matched,
std::string& err) -> bool {
for (const auto& f : p->flags_) {
if (arg == f.lng || (!f.sht.empty() && arg == f.sht)) {
*f.out = true;
matched = true;
return true;
}
}
for (const auto& opt : p->options_) {
std::string_view value;
bool found = false;
if (arg.size() > opt.lng.size() + 1 &&
arg.substr(0, opt.lng.size()) == opt.lng &&
arg[opt.lng.size()] == '=') {
value = arg.substr(opt.lng.size() + 1);
found = true;
} else if (arg == opt.lng ||
(!opt.sht.empty() && arg == opt.sht)) {
if (i + 1 >= argc) {
err = "option '" + std::string{arg} + "' requires a value";
return false;
}
value = argv[++i];
found = true;
}
if (found) {
const std::string val_str{value};
if (opt.out_opt) *opt.out_opt = val_str;
if (opt.out_str) *opt.out_str = val_str;
if (opt.out_many) opt.out_many->push_back(val_str);
matched = true;
return true;
}
}
matched = false;
return true;
};
for (int i = 1; i < argc; ++i) { for (int i = 1; i < argc; ++i) {
const std::string_view arg{argv[i]}; const std::string_view arg{argv[i]};
// Help if (!after_double_dash) {
if (arg == "--help" || arg == "-h") { if (arg == "--") {
return std::unexpected{help()}; after_double_dash = true;
} continue;
}
// Flag check if (arg == "--help" || arg == "-h") {
bool matched_flag = false; return ParseResult{
for (const auto& f : flags_) { .outcome = ParseOutcome::Help,
if (arg == f.lng || (!f.sht.empty() && arg == f.sht)) { .message = active->help(),
*f.out = true; .matched_command_path = std::move(matched_path),
matched_flag = true; };
break; }
bool matched = false;
std::string err;
if (!match_flag_or_opt(active, arg, i, matched, err)) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = std::move(err),
.matched_command_path = std::move(matched_path),
};
}
if (matched) {
continue;
}
if (arg.size() > 1 && arg[0] == '-') {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = "unknown option: " + std::string{arg},
.matched_command_path = std::move(matched_path),
};
}
if (pos_idx == 0 && !active->subcommands_.empty()) {
const SubcommandEntry* chosen = nullptr;
for (const auto& sub : active->subcommands_) {
if (sub.name == arg) {
chosen = &sub;
break;
}
}
if (chosen != nullptr) {
matched_path.push_back(chosen->name);
if (chosen->on_selected) {
callbacks.push_back(&chosen->on_selected);
}
active = chosen->parser.get();
pos_idx = 0;
continue;
}
if (active->positionals_.empty() &&
!active->positional_many_.has_value()) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = "unknown subcommand: " + std::string{arg},
.matched_command_path = std::move(matched_path),
};
}
} }
} }
if (matched_flag) continue;
// Option check: --key=value or --key value or -k value if (pos_idx < active->positionals_.size()) {
bool matched_opt = false; *active->positionals_[pos_idx++].out = std::string{arg};
for (const auto& opt : options_) { } else if (active->positional_many_.has_value() &&
std::string_view value; active->positional_many_->out != nullptr) {
bool found = false; active->positional_many_->out->push_back(std::string{arg});
} else {
// --key=value return ParseResult{
if (arg.size() > opt.lng.size() + 1 && .outcome = ParseOutcome::Error,
arg.substr(0, opt.lng.size()) == opt.lng && .message =
arg[opt.lng.size()] == '=') "unexpected positional argument: " + std::string{arg},
{ .matched_command_path = std::move(matched_path),
value = arg.substr(opt.lng.size() + 1); };
found = true;
}
// --key value or -k value
else if (arg == opt.lng || (!opt.sht.empty() && arg == opt.sht)) {
if (i + 1 >= argc)
return std::unexpected{"option '" + std::string{arg} + "' requires a value"};
value = argv[++i];
found = true;
}
if (found) {
const std::string val_str{value};
if (opt.out_opt) *opt.out_opt = val_str;
if (opt.out_str) *opt.out_str = val_str;
matched_opt = true;
break;
}
} }
if (matched_opt) continue;
// Unknown --/- prefixed arg
if (arg.size() > 1 && arg[0] == '-')
return std::unexpected{"unknown option: " + std::string{arg}};
// Positional
if (pos_idx >= positionals_.size())
return std::unexpected{"unexpected positional argument: " + std::string{arg}};
*positionals_[pos_idx++].out = std::string{arg};
} }
// Check required positionals if (!active->subcommands_.empty()) {
for (std::size_t j = pos_idx; j < positionals_.size(); ++j) const bool req = active->has_explicit_require_sub_
return std::unexpected{"missing required argument: <" + positionals_[j].name + ">"}; ? active->require_subcommand_
: true;
if (req) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = "missing subcommand for '" + active->program_ + "'",
.matched_command_path = std::move(matched_path),
};
}
}
for (std::size_t j = pos_idx; j < active->positionals_.size(); ++j) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = "missing required argument: <" +
active->positionals_[j].name + ">",
.matched_command_path = std::move(matched_path),
};
}
if (active->positional_many_.has_value() &&
active->positional_many_->required &&
active->positional_many_->out != nullptr &&
active->positional_many_->out->empty()) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = "missing required arguments: <" +
active->positional_many_->name + ">",
.matched_command_path = std::move(matched_path),
};
}
for (const auto* cb : callbacks) {
(*cb)();
}
return ParseResult{
.outcome = ParseOutcome::Ok,
.message = {},
.matched_command_path = std::move(matched_path),
};
}
std::expected<void, std::string> Parser::parse(int argc,
const char* const* argv) const
{
auto res = parse_detailed(argc, argv);
if (!res.ok()) {
return std::unexpected{std::move(res.message)};
}
return {}; return {};
} }
@@ -116,19 +292,42 @@ std::string Parser::help() const
{ {
std::ostringstream os; std::ostringstream os;
os << "Usage: " << program_; os << "Usage: " << program_;
for (const auto& f : flags_) os << " [" << f.lng << "]"; for (const auto& f : flags_) os << " [" << f.lng << "]";
for (const auto& o : options_) { for (const auto& o : options_) {
const std::string_view dn = std::string_view{o.lng}.substr(o.lng.size() > 2 ? 2 : 0); const std::string_view dn =
std::string_view{o.lng}.substr(o.lng.size() > 2 ? 2 : 0);
os << " [" << o.lng << " <" << dn << ">]"; os << " [" << o.lng << " <" << dn << ">]";
} }
if (!subcommands_.empty()) {
os << " <command>";
}
for (const auto& p : positionals_) os << " <" << p.name << ">"; for (const auto& p : positionals_) os << " <" << p.name << ">";
if (positional_many_.has_value()) {
os << (positional_many_->required ? " <" : " [")
<< positional_many_->name
<< (positional_many_->required ? "...>" : "...]");
}
os << "\n"; os << "\n";
if (!description_.empty()) os << "\n" << description_ << "\n"; if (!description_.empty()) os << "\n" << description_ << "\n";
if (!positionals_.empty()) { if (!subcommands_.empty()) {
os << "\nCommands:\n";
for (const auto& s : subcommands_) {
os << " " << s.name;
if (!s.parser->description_.empty()) {
os << " " << s.parser->description_;
}
os << "\n";
}
}
if (!positionals_.empty() || positional_many_.has_value()) {
os << "\nArguments:\n"; os << "\nArguments:\n";
for (const auto& p : positionals_) for (const auto& p : positionals_)
os << " <" << p.name << "> " << p.desc << "\n"; os << " <" << p.name << "> " << p.desc << "\n";
if (positional_many_.has_value()) {
os << " <" << positional_many_->name << "...> "
<< positional_many_->desc << "\n";
}
} }
if (!flags_.empty()) { if (!flags_.empty()) {
os << "\nFlags:\n"; os << "\nFlags:\n";
@@ -141,13 +340,13 @@ std::string Parser::help() const
if (!options_.empty()) { if (!options_.empty()) {
os << "\nOptions:\n"; os << "\nOptions:\n";
for (const auto& o : options_) { for (const auto& o : options_) {
// Derive a display name from the long option (strip leading --) const std::string_view dname =
const std::string_view dname = std::string_view{o.lng}.substr( std::string_view{o.lng}.substr(o.lng.size() > 2 ? 2 : 0);
o.lng.size() > 2 ? 2 : 0);
os << " " << o.lng; os << " " << o.lng;
if (!o.sht.empty()) os << ", " << o.sht; if (!o.sht.empty()) os << ", " << o.sht;
os << " <" << dname << ">"; os << " <" << dname << ">";
if (!o.def.empty()) os << " (default: " << o.def << ")"; if (!o.def.empty()) os << " (default: " << o.def << ")";
if (o.out_many != nullptr) os << " (repeatable)";
os << " " << o.desc << "\n"; os << " " << o.desc << "\n";
} }
} }
+895
View File
@@ -0,0 +1,895 @@
#include "BuiltinHash.hpp"
#include <algorithm>
#include <array>
#include <atomic>
#include <bit>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <utility>
#include <variant>
namespace Void::Crypto::Detail
{
namespace
{
[[nodiscard]] inline std::uint32_t load_be32(const std::byte* p) noexcept
{
return (static_cast<std::uint32_t>(std::to_integer<std::uint8_t>(p[0])) << 24U) |
(static_cast<std::uint32_t>(std::to_integer<std::uint8_t>(p[1])) << 16U) |
(static_cast<std::uint32_t>(std::to_integer<std::uint8_t>(p[2])) << 8U) |
static_cast<std::uint32_t>(std::to_integer<std::uint8_t>(p[3]));
}
inline void store_be32(std::byte* p, std::uint32_t v) noexcept
{
p[0] = static_cast<std::byte>((v >> 24U) & 0xFFU);
p[1] = static_cast<std::byte>((v >> 16U) & 0xFFU);
p[2] = static_cast<std::byte>((v >> 8U) & 0xFFU);
p[3] = static_cast<std::byte>(v & 0xFFU);
}
[[nodiscard]] inline std::uint64_t load_be64(const std::byte* p) noexcept
{
return (static_cast<std::uint64_t>(load_be32(p)) << 32U) |
static_cast<std::uint64_t>(load_be32(p + 4));
}
inline void store_be64(std::byte* p, std::uint64_t v) noexcept
{
store_be32(p, static_cast<std::uint32_t>((v >> 32U) & 0xFFFFFFFFU));
store_be32(p + 4, static_cast<std::uint32_t>(v & 0xFFFFFFFFU));
}
[[nodiscard]] inline std::uint64_t load_le64(const std::byte* p) noexcept
{
return static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[0])) |
(static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[1])) << 8U) |
(static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[2])) << 16U) |
(static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[3])) << 24U) |
(static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[4])) << 32U) |
(static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[5])) << 40U) |
(static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[6])) << 48U) |
(static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[7])) << 56U);
}
inline void store_le64(std::byte* p, std::uint64_t v) noexcept
{
for (std::size_t i = 0; i < 8; ++i) {
p[i] = static_cast<std::byte>((v >> (8U * i)) & 0xFFU);
}
}
// ── FIPS 180-4 SHA-1 ─────────────────────────────────────────────────
struct Sha1State {
std::array<std::uint32_t, 5> h{0x67452301U, 0xefcdab89U,
0x98badcfeU, 0x10325476U,
0xc3d2e1f0U};
std::array<std::byte, 64> buf{};
std::size_t buf_len{0};
std::uint64_t total_bytes{0};
void compress(const std::byte* block) noexcept
{
std::array<std::uint32_t, 80> w{};
for (std::size_t i = 0; i < 16; ++i) {
w[i] = load_be32(block + i * 4);
}
for (std::size_t i = 16; i < 80; ++i) {
w[i] = std::rotl(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^
w[i - 16],
1);
}
std::uint32_t a = h[0];
std::uint32_t b = h[1];
std::uint32_t c = h[2];
std::uint32_t d = h[3];
std::uint32_t e = h[4];
for (std::size_t i = 0; i < 80; ++i) {
std::uint32_t f = 0;
std::uint32_t k = 0;
if (i < 20) {
f = (b & c) | ((~b) & d);
k = 0x5a827999U;
} else if (i < 40) {
f = b ^ c ^ d;
k = 0x6ed9eba1U;
} else if (i < 60) {
f = (b & c) | (b & d) | (c & d);
k = 0x8f1bbcdcU;
} else {
f = b ^ c ^ d;
k = 0xca62c1d6U;
}
const std::uint32_t temp =
std::rotl(a, 5) + f + e + k + w[i];
e = d;
d = c;
c = std::rotl(b, 30);
b = a;
a = temp;
}
h[0] += a;
h[1] += b;
h[2] += c;
h[3] += d;
h[4] += e;
builtin_secure_wipe(std::as_writable_bytes(std::span{w}));
}
void update(std::span<const std::byte> data) noexcept
{
total_bytes += data.size();
std::size_t off = 0;
if (buf_len > 0) {
const std::size_t take =
std::min(data.size(), buf.size() - buf_len);
std::memcpy(buf.data() + buf_len, data.data(), take);
buf_len += take;
off += take;
if (buf_len == buf.size()) {
compress(buf.data());
buf_len = 0;
}
}
while (off + buf.size() <= data.size()) {
compress(data.data() + off);
off += buf.size();
}
if (off < data.size()) {
const std::size_t rem = data.size() - off;
std::memcpy(buf.data(), data.data() + off, rem);
buf_len = rem;
}
}
void finalize_into(std::span<std::byte> out20) noexcept
{
buf[buf_len++] = std::byte{0x80};
if (buf_len > 56) {
std::fill(buf.begin() + static_cast<std::ptrdiff_t>(buf_len),
buf.end(), std::byte{0});
compress(buf.data());
buf_len = 0;
}
std::fill(buf.begin() + static_cast<std::ptrdiff_t>(buf_len),
buf.begin() + 56, std::byte{0});
store_be64(buf.data() + 56, total_bytes << 3U);
compress(buf.data());
for (std::size_t i = 0; i < 5; ++i) {
store_be32(out20.data() + i * 4, h[i]);
}
wipe();
}
void wipe() noexcept
{
builtin_secure_wipe(std::as_writable_bytes(std::span{h}));
builtin_secure_wipe(buf);
buf_len = 0;
total_bytes = 0;
}
};
// ── FIPS 180-4 SHA-256 ───────────────────────────────────────────────
struct Sha256State {
static constexpr std::array<std::uint32_t, 64> kRound = {
0x428a2f98U, 0x71374491U, 0xb5c0fbcfU, 0xe9b5dba5U,
0x3956c25bU, 0x59f111f1U, 0x923f82a4U, 0xab1c5ed5U,
0xd807aa98U, 0x12835b01U, 0x243185beU, 0x550c7dc3U,
0x72be5d74U, 0x80deb1feU, 0x9bdc06a7U, 0xc19bf174U,
0xe49b69c1U, 0xefbe4786U, 0x0fc19dc6U, 0x240ca1ccU,
0x2de92c6fU, 0x4a7484aaU, 0x5cb0a9dcU, 0x76f988daU,
0x983e5152U, 0xa831c66dU, 0xb00327c8U, 0xbf597fc7U,
0xc6e00bf3U, 0xd5a79147U, 0x06ca6351U, 0x14292967U,
0x27b70a85U, 0x2e1b2138U, 0x4d2c6dfcU, 0x53380d13U,
0x650a7354U, 0x766a0abbU, 0x81c2c92eU, 0x92722c85U,
0xa2bfe8a1U, 0xa81a664bU, 0xc24b8b70U, 0xc76c51a3U,
0xd192e819U, 0xd6990624U, 0xf40e3585U, 0x106aa070U,
0x19a4c116U, 0x1e376c08U, 0x2748774cU, 0x34b0bcb5U,
0x391c0cb3U, 0x4ed8aa4aU, 0x5b9cca4fU, 0x682e6ff3U,
0x748f82eeU, 0x78a5636fU, 0x84c87814U, 0x8cc70208U,
0x90befffaU, 0xa4506cebU, 0xbef9a3f7U, 0xc67178f2U};
std::array<std::uint32_t, 8> h{0x6a09e667U, 0xbb67ae85U,
0x3c6ef372U, 0xa54ff53aU,
0x510e527fU, 0x9b05688cU,
0x1f83d9abU, 0x5be0cd19U};
std::array<std::byte, 64> buf{};
std::size_t buf_len{0};
std::uint64_t total_bytes{0};
void compress(const std::byte* block) noexcept
{
std::array<std::uint32_t, 64> w{};
for (std::size_t i = 0; i < 16; ++i) {
w[i] = load_be32(block + i * 4);
}
for (std::size_t i = 16; i < 64; ++i) {
const std::uint32_t s0 = std::rotr(w[i - 15], 7) ^
std::rotr(w[i - 15], 18) ^
(w[i - 15] >> 3U);
const std::uint32_t s1 = std::rotr(w[i - 2], 17) ^
std::rotr(w[i - 2], 19) ^
(w[i - 2] >> 10U);
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
}
std::uint32_t a = h[0];
std::uint32_t b = h[1];
std::uint32_t c = h[2];
std::uint32_t d = h[3];
std::uint32_t e = h[4];
std::uint32_t f = h[5];
std::uint32_t g = h[6];
std::uint32_t hv = h[7];
for (std::size_t i = 0; i < 64; ++i) {
const std::uint32_t S1 = std::rotr(e, 6) ^
std::rotr(e, 11) ^
std::rotr(e, 25);
const std::uint32_t ch = (e & f) ^ ((~e) & g);
const std::uint32_t temp1 =
hv + S1 + ch + kRound[i] + w[i];
const std::uint32_t S0 = std::rotr(a, 2) ^
std::rotr(a, 13) ^
std::rotr(a, 22);
const std::uint32_t maj =
(a & b) ^ (a & c) ^ (b & c);
const std::uint32_t temp2 = S0 + maj;
hv = g;
g = f;
f = e;
e = d + temp1;
d = c;
c = b;
b = a;
a = temp1 + temp2;
}
h[0] += a;
h[1] += b;
h[2] += c;
h[3] += d;
h[4] += e;
h[5] += f;
h[6] += g;
h[7] += hv;
builtin_secure_wipe(std::as_writable_bytes(std::span{w}));
}
void update(std::span<const std::byte> data) noexcept
{
total_bytes += data.size();
std::size_t off = 0;
if (buf_len > 0) {
const std::size_t take =
std::min(data.size(), buf.size() - buf_len);
std::memcpy(buf.data() + buf_len, data.data(), take);
buf_len += take;
off += take;
if (buf_len == buf.size()) {
compress(buf.data());
buf_len = 0;
}
}
while (off + buf.size() <= data.size()) {
compress(data.data() + off);
off += buf.size();
}
if (off < data.size()) {
const std::size_t rem = data.size() - off;
std::memcpy(buf.data(), data.data() + off, rem);
buf_len = rem;
}
}
void finalize_into(std::span<std::byte> out32) noexcept
{
buf[buf_len++] = std::byte{0x80};
if (buf_len > 56) {
std::fill(buf.begin() + static_cast<std::ptrdiff_t>(buf_len),
buf.end(), std::byte{0});
compress(buf.data());
buf_len = 0;
}
std::fill(buf.begin() + static_cast<std::ptrdiff_t>(buf_len),
buf.begin() + 56, std::byte{0});
store_be64(buf.data() + 56, total_bytes << 3U);
compress(buf.data());
for (std::size_t i = 0; i < 8; ++i) {
store_be32(out32.data() + i * 4, h[i]);
}
wipe();
}
void wipe() noexcept
{
builtin_secure_wipe(std::as_writable_bytes(std::span{h}));
builtin_secure_wipe(buf);
buf_len = 0;
total_bytes = 0;
}
};
// ── FIPS 180-4 SHA-512 ───────────────────────────────────────────────
struct Sha512State {
static constexpr std::array<std::uint64_t, 80> kRound = {
0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL,
0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL,
0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL,
0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL,
0xd807aa98a3030242ULL, 0x12835b0145706fbeULL,
0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL,
0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL,
0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL,
0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL,
0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL,
0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL,
0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL,
0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL,
0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL,
0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL,
0x06ca6351e003826fULL, 0x142929670a0e6e70ULL,
0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL,
0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL,
0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL,
0x81c2c92e47edaee6ULL, 0x92722c851482353bULL,
0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL,
0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL,
0xd192e819d6ef5218ULL, 0xd69906245565a910ULL,
0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL,
0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL,
0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL,
0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL,
0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL,
0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL,
0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL,
0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL,
0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL,
0xca273eceea26619cULL, 0xd186b8c721c0c207ULL,
0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL,
0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL,
0x113f9804bef90daeULL, 0x1b710b35131c471bULL,
0x28db77f523047d84ULL, 0x32caab7b40c72493ULL,
0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL,
0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL,
0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL};
std::array<std::uint64_t, 8> h{
0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL,
0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL,
0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL,
0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL};
std::array<std::byte, 128> buf{};
std::size_t buf_len{0};
std::uint64_t total_bytes{0};
void compress(const std::byte* block) noexcept
{
std::array<std::uint64_t, 80> w{};
for (std::size_t i = 0; i < 16; ++i) {
w[i] = load_be64(block + i * 8);
}
for (std::size_t i = 16; i < 80; ++i) {
const std::uint64_t s0 = std::rotr(w[i - 15], 1) ^
std::rotr(w[i - 15], 8) ^
(w[i - 15] >> 7U);
const std::uint64_t s1 = std::rotr(w[i - 2], 19) ^
std::rotr(w[i - 2], 61) ^
(w[i - 2] >> 6U);
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
}
std::uint64_t a = h[0];
std::uint64_t b = h[1];
std::uint64_t c = h[2];
std::uint64_t d = h[3];
std::uint64_t e = h[4];
std::uint64_t f = h[5];
std::uint64_t g = h[6];
std::uint64_t hv = h[7];
for (std::size_t i = 0; i < 80; ++i) {
const std::uint64_t S1 = std::rotr(e, 14) ^
std::rotr(e, 18) ^
std::rotr(e, 41);
const std::uint64_t ch = (e & f) ^ ((~e) & g);
const std::uint64_t temp1 =
hv + S1 + ch + kRound[i] + w[i];
const std::uint64_t S0 = std::rotr(a, 28) ^
std::rotr(a, 34) ^
std::rotr(a, 39);
const std::uint64_t maj =
(a & b) ^ (a & c) ^ (b & c);
const std::uint64_t temp2 = S0 + maj;
hv = g;
g = f;
f = e;
e = d + temp1;
d = c;
c = b;
b = a;
a = temp1 + temp2;
}
h[0] += a;
h[1] += b;
h[2] += c;
h[3] += d;
h[4] += e;
h[5] += f;
h[6] += g;
h[7] += hv;
builtin_secure_wipe(std::as_writable_bytes(std::span{w}));
}
void update(std::span<const std::byte> data) noexcept
{
total_bytes += data.size();
std::size_t off = 0;
if (buf_len > 0) {
const std::size_t take =
std::min(data.size(), buf.size() - buf_len);
std::memcpy(buf.data() + buf_len, data.data(), take);
buf_len += take;
off += take;
if (buf_len == buf.size()) {
compress(buf.data());
buf_len = 0;
}
}
while (off + buf.size() <= data.size()) {
compress(data.data() + off);
off += buf.size();
}
if (off < data.size()) {
const std::size_t rem = data.size() - off;
std::memcpy(buf.data(), data.data() + off, rem);
buf_len = rem;
}
}
void finalize_into(std::span<std::byte> out64) noexcept
{
buf[buf_len++] = std::byte{0x80};
if (buf_len > 112) {
std::fill(buf.begin() + static_cast<std::ptrdiff_t>(buf_len),
buf.end(), std::byte{0});
compress(buf.data());
buf_len = 0;
}
std::fill(buf.begin() + static_cast<std::ptrdiff_t>(buf_len),
buf.begin() + 112, std::byte{0});
store_be64(buf.data() + 112, total_bytes >> 61U);
store_be64(buf.data() + 120, total_bytes << 3U);
compress(buf.data());
for (std::size_t i = 0; i < 8; ++i) {
store_be64(out64.data() + i * 8, h[i]);
}
wipe();
}
void wipe() noexcept
{
builtin_secure_wipe(std::as_writable_bytes(std::span{h}));
builtin_secure_wipe(buf);
buf_len = 0;
total_bytes = 0;
}
};
// ── RFC 7693 BLAKE2b ─────────────────────────────────────────────────
struct Blake2bState {
static constexpr std::array<std::uint64_t, 8> kIv = {
0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL,
0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL,
0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL,
0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL};
static constexpr std::array<std::array<std::uint8_t, 16>, 12>
kSigma = {{
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
{14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3},
{11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4},
{7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8},
{9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13},
{2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9},
{12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11},
{13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10},
{6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5},
{10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0},
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
{14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3},
}};
std::array<std::uint64_t, 8> h{kIv};
std::array<std::uint64_t, 2> t{0, 0};
std::array<std::byte, 128> buf{};
std::size_t buf_len{0};
std::size_t out_len{64};
void init(std::size_t digest_len) noexcept
{
h = kIv;
out_len = digest_len;
h[0] ^= 0x01010000ULL ^ static_cast<std::uint64_t>(out_len);
t = {0, 0};
buf.fill(std::byte{0});
buf_len = 0;
}
void add_counter(std::uint64_t inc) noexcept
{
t[0] += inc;
if (t[0] < inc) {
++t[1];
}
}
void compress(const std::byte* block, bool is_last) noexcept
{
std::array<std::uint64_t, 16> m{};
for (std::size_t i = 0; i < 16; ++i) {
m[i] = load_le64(block + i * 8);
}
std::array<std::uint64_t, 16> v{};
for (std::size_t i = 0; i < 8; ++i) {
v[i] = h[i];
v[i + 8] = kIv[i];
}
v[12] ^= t[0];
v[13] ^= t[1];
if (is_last) {
v[14] = ~v[14];
}
auto mix = [&](std::size_t r, std::size_t p,
std::size_t ia, std::size_t ib,
std::size_t ic, std::size_t id) noexcept {
const auto s0 = kSigma[r][2 * p];
const auto s1 = kSigma[r][2 * p + 1];
v[ia] = v[ia] + v[ib] + m[s0];
v[id] = std::rotr(v[id] ^ v[ia], 32);
v[ic] = v[ic] + v[id];
v[ib] = std::rotr(v[ib] ^ v[ic], 24);
v[ia] = v[ia] + v[ib] + m[s1];
v[id] = std::rotr(v[id] ^ v[ia], 16);
v[ic] = v[ic] + v[id];
v[ib] = std::rotr(v[ib] ^ v[ic], 63);
};
for (std::size_t r = 0; r < 12; ++r) {
mix(r, 0, 0, 4, 8, 12);
mix(r, 1, 1, 5, 9, 13);
mix(r, 2, 2, 6, 10, 14);
mix(r, 3, 3, 7, 11, 15);
mix(r, 4, 0, 5, 10, 15);
mix(r, 5, 1, 6, 11, 12);
mix(r, 6, 2, 7, 8, 13);
mix(r, 7, 3, 4, 9, 14);
}
for (std::size_t i = 0; i < 8; ++i) {
h[i] ^= v[i] ^ v[i + 8];
}
builtin_secure_wipe(std::as_writable_bytes(std::span{m}));
builtin_secure_wipe(std::as_writable_bytes(std::span{v}));
}
void update(std::span<const std::byte> data) noexcept
{
if (data.empty()) {
return;
}
std::size_t off = 0;
if (buf_len > 0) {
const std::size_t take =
std::min(data.size(), buf.size() - buf_len);
std::memcpy(buf.data() + buf_len, data.data(), take);
buf_len += take;
off += take;
// Only flush a full buffer when more bytes follow so
// finalize() sees the true final block.
if (off < data.size() && buf_len == buf.size()) {
add_counter(128);
compress(buf.data(), false);
buf_len = 0;
}
}
while (off + buf.size() < data.size()) {
add_counter(128);
compress(data.data() + off, false);
off += buf.size();
}
if (off < data.size()) {
const std::size_t rem = data.size() - off;
std::memcpy(buf.data() + buf_len, data.data() + off,
rem);
buf_len += rem;
}
}
void finalize_into(std::span<std::byte> out) noexcept
{
add_counter(static_cast<std::uint64_t>(buf_len));
std::fill(buf.begin() + static_cast<std::ptrdiff_t>(buf_len),
buf.end(), std::byte{0});
compress(buf.data(), true);
std::array<std::byte, 64> full{};
for (std::size_t i = 0; i < 8; ++i) {
store_le64(full.data() + i * 8, h[i]);
}
std::memcpy(out.data(), full.data(), out_len);
builtin_secure_wipe(full);
wipe();
}
void wipe() noexcept
{
builtin_secure_wipe(std::as_writable_bytes(std::span{h}));
builtin_secure_wipe(std::as_writable_bytes(std::span{t}));
builtin_secure_wipe(buf);
buf_len = 0;
}
};
} // namespace
void builtin_secure_wipe(std::span<std::byte> buffer) noexcept
{
if (buffer.empty()) {
return;
}
volatile std::byte* p = buffer.data();
for (std::size_t i = 0; i < buffer.size(); ++i) {
p[i] = std::byte{0};
}
std::atomic_signal_fence(std::memory_order_seq_cst);
}
bool builtin_constant_time_equal(std::span<const std::byte> lhs,
std::span<const std::byte> rhs) noexcept
{
if (lhs.size() != rhs.size()) {
return false;
}
volatile unsigned char diff = 0;
for (std::size_t i = 0; i < lhs.size(); ++i) {
const auto a = static_cast<unsigned char>(lhs[i]);
const auto b = static_cast<unsigned char>(rhs[i]);
diff = static_cast<unsigned char>(diff | (a ^ b));
}
std::atomic_signal_fence(std::memory_order_seq_cst);
return diff == 0;
}
struct BuiltinHasher::State {
std::variant<std::monostate, Sha1State, Sha256State, Sha512State,
Blake2bState>
impl{};
void wipe() noexcept
{
std::visit(
[](auto& st) {
using T = std::decay_t<decltype(st)>;
if constexpr (!std::is_same_v<T, std::monostate>) {
st.wipe();
}
},
impl);
impl.template emplace<std::monostate>();
}
};
BuiltinHasher::~BuiltinHasher() noexcept { destroy(); }
BuiltinHasher::BuiltinHasher(BuiltinHasher&& other) noexcept
: m_state(std::exchange(other.m_state, nullptr))
{
}
BuiltinHasher& BuiltinHasher::operator=(BuiltinHasher&& other) noexcept
{
if (this != &other) {
destroy();
m_state = std::exchange(other.m_state, nullptr);
}
return *this;
}
void BuiltinHasher::destroy() noexcept
{
if (m_state != nullptr) {
m_state->wipe();
delete m_state;
m_state = nullptr;
}
}
bool BuiltinHasher::init(HashAlgorithm algorithm) noexcept
{
if (m_state == nullptr) {
m_state = new (std::nothrow) State();
if (m_state == nullptr) {
return false;
}
} else {
m_state->wipe();
}
switch (algorithm) {
case HashAlgorithm::Sha1:
m_state->impl.emplace<Sha1State>();
return true;
case HashAlgorithm::Sha256:
m_state->impl.emplace<Sha256State>();
return true;
case HashAlgorithm::Sha512:
m_state->impl.emplace<Sha512State>();
return true;
case HashAlgorithm::Blake2b256: {
auto& b = m_state->impl.emplace<Blake2bState>();
b.init(32);
return true;
}
case HashAlgorithm::Blake2b512: {
auto& b = m_state->impl.emplace<Blake2bState>();
b.init(64);
return true;
}
}
return false;
}
void BuiltinHasher::update(std::span<const std::byte> data) noexcept
{
if (m_state == nullptr || data.empty()) {
return;
}
std::visit(
[&](auto& st) {
using T = std::decay_t<decltype(st)>;
if constexpr (!std::is_same_v<T, std::monostate>) {
st.update(data);
}
},
m_state->impl);
}
Digest BuiltinHasher::finalize()
{
Digest out;
if (m_state == nullptr) {
return out;
}
std::visit(
[&](auto& st) {
using T = std::decay_t<decltype(st)>;
if constexpr (std::is_same_v<T, Sha1State>) {
out.resize(20);
st.finalize_into(out);
} else if constexpr (std::is_same_v<T, Sha256State>) {
out.resize(32);
st.finalize_into(out);
} else if constexpr (std::is_same_v<T, Sha512State>) {
out.resize(64);
st.finalize_into(out);
} else if constexpr (std::is_same_v<T, Blake2bState>) {
out.resize(st.out_len);
st.finalize_into(out);
}
},
m_state->impl);
return out;
}
void builtin_hmac_sha256(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
std::span<std::byte> output_32) noexcept
{
std::array<std::byte, 64> key_block{};
if (secret_key.size() > 64) {
Sha256State kh;
kh.update(secret_key);
kh.finalize_into(std::span{key_block}.subspan(0, 32));
} else if (!secret_key.empty()) {
std::memcpy(key_block.data(), secret_key.data(), secret_key.size());
}
std::array<std::byte, 64> ipad{};
std::array<std::byte, 64> opad{};
for (std::size_t i = 0; i < 64; ++i) {
ipad[i] = key_block[i] ^ std::byte{0x36};
opad[i] = key_block[i] ^ std::byte{0x5C};
}
std::array<std::byte, 32> inner_hash{};
{
Sha256State inner;
inner.update(ipad);
inner.update(message);
inner.finalize_into(inner_hash);
}
{
Sha256State outer;
outer.update(opad);
outer.update(inner_hash);
outer.finalize_into(output_32);
}
builtin_secure_wipe(key_block);
builtin_secure_wipe(ipad);
builtin_secure_wipe(opad);
builtin_secure_wipe(inner_hash);
}
void builtin_hkdf_sha256(std::span<const std::byte> secret_input,
std::span<const std::byte> salt,
std::span<const std::byte> context,
std::span<std::byte> secret_output) noexcept
{
std::array<std::byte, 32> zero_salt{};
const auto effective_salt =
salt.empty() ? std::span<const std::byte>{zero_salt} : salt;
std::array<std::byte, 32> prk{};
builtin_hmac_sha256(effective_salt, secret_input, prk);
std::array<std::byte, 32> t{};
std::size_t t_len = 0;
std::size_t written = 0;
std::uint8_t counter = 1;
while (written < secret_output.size()) {
std::array<std::byte, 64> ipad{};
std::array<std::byte, 64> opad{};
for (std::size_t i = 0; i < 32; ++i) {
ipad[i] = prk[i] ^ std::byte{0x36};
opad[i] = prk[i] ^ std::byte{0x5C};
}
for (std::size_t i = 32; i < 64; ++i) {
ipad[i] = std::byte{0x36};
opad[i] = std::byte{0x5C};
}
std::array<std::byte, 32> inner_hash{};
Sha256State inner;
inner.update(ipad);
if (t_len > 0) {
inner.update(std::span<const std::byte>{t.data(), t_len});
}
if (!context.empty()) {
inner.update(context);
}
const std::byte ctr_byte = static_cast<std::byte>(counter);
inner.update(std::span<const std::byte>{&ctr_byte, 1});
inner.finalize_into(inner_hash);
Sha256State outer;
outer.update(opad);
outer.update(inner_hash);
outer.finalize_into(t);
t_len = 32;
const std::size_t copy_n =
std::min<std::size_t>(32, secret_output.size() - written);
std::memcpy(secret_output.data() + written, t.data(), copy_n);
written += copy_n;
++counter;
builtin_secure_wipe(ipad);
builtin_secure_wipe(opad);
builtin_secure_wipe(inner_hash);
}
builtin_secure_wipe(prk);
builtin_secure_wipe(t);
}
} // namespace Void::Crypto::Detail
+49
View File
@@ -0,0 +1,49 @@
#pragma once
#include <Void/Crypto/Crypto.hpp>
#include <Void/Crypto/Types.hpp>
#include <cstddef>
#include <span>
namespace Void::Crypto::Detail
{
void builtin_secure_wipe(std::span<std::byte> buffer) noexcept;
[[nodiscard]] bool
builtin_constant_time_equal(std::span<const std::byte> lhs,
std::span<const std::byte> rhs) noexcept;
class BuiltinHasher
{
public:
BuiltinHasher() noexcept = default;
~BuiltinHasher() noexcept;
BuiltinHasher(BuiltinHasher&& other) noexcept;
BuiltinHasher& operator=(BuiltinHasher&& other) noexcept;
BuiltinHasher(const BuiltinHasher&) = delete;
BuiltinHasher& operator=(const BuiltinHasher&) = delete;
[[nodiscard]] bool init(HashAlgorithm algorithm) noexcept;
void update(std::span<const std::byte> data) noexcept;
[[nodiscard]] Digest finalize();
private:
struct State;
State* m_state{nullptr};
void destroy() noexcept;
};
void builtin_hmac_sha256(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
std::span<std::byte> output_32) noexcept;
void builtin_hkdf_sha256(std::span<const std::byte> secret_input,
std::span<const std::byte> salt,
std::span<const std::byte> context,
std::span<std::byte> secret_output) noexcept;
} // namespace Void::Crypto::Detail
+297 -24
View File
@@ -1,19 +1,24 @@
#include <Void/Crypto/Crypto.hpp> #include <Void/Crypto/Crypto.hpp>
#include "BuiltinHash.hpp"
#include <array> #include <array>
#include <cstdint> #include <cstdint>
#include <cstring> #include <cstring>
#include <format> #include <format>
#include <fstream> #include <fstream>
#include <limits> #include <limits>
#include <optional>
#include <utility> #include <utility>
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
#include <openssl/core_names.h> #include <openssl/core_names.h>
#include <openssl/crypto.h> #include <openssl/crypto.h>
#include <openssl/err.h> #include <openssl/err.h>
#include <openssl/evp.h> #include <openssl/evp.h>
#include <openssl/kdf.h> #include <openssl/kdf.h>
#include <openssl/params.h> #include <openssl/params.h>
#endif
namespace Void::Crypto namespace Void::Crypto
{ {
@@ -42,6 +47,36 @@ namespace Void::Crypto
std::format("{}: injected crypto backend fault", operation)); std::format("{}: injected crypto backend fault", operation));
} }
[[nodiscard]] bool spans_overlap(std::span<const std::byte> a,
std::span<const std::byte> b) noexcept
{
if (a.empty() || b.empty()) {
return false;
}
const auto a_begin = reinterpret_cast<std::uintptr_t>(a.data());
const auto a_end = a_begin + a.size();
const auto b_begin = reinterpret_cast<std::uintptr_t>(b.data());
const auto b_end = b_begin + b.size();
return a_begin < b_end && b_begin < a_end;
}
[[nodiscard]] bool use_builtin_hash(
HashAlgorithm algorithm, const ProviderOptions& provider) noexcept
{
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
if (provider.prefer_builtin ||
algorithm == HashAlgorithm::Blake2b256) {
return true;
}
return false;
#else
(void)algorithm;
(void)provider;
return true;
#endif
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
[[nodiscard]] const char* [[nodiscard]] const char*
algorithm_name(HashAlgorithm algorithm) noexcept algorithm_name(HashAlgorithm algorithm) noexcept
{ {
@@ -52,6 +87,10 @@ namespace Void::Crypto
return "SHA256"; return "SHA256";
case HashAlgorithm::Sha512: case HashAlgorithm::Sha512:
return "SHA512"; return "SHA512";
case HashAlgorithm::Blake2b256:
return nullptr;
case HashAlgorithm::Blake2b512:
return "BLAKE2B512";
} }
return nullptr; return nullptr;
} }
@@ -78,19 +117,6 @@ namespace Void::Crypto
code, std::format("{}: {}", operation, buffer.data())); code, std::format("{}: {}", operation, buffer.data()));
} }
[[nodiscard]] bool spans_overlap(std::span<const std::byte> a,
std::span<const std::byte> b) noexcept
{
if (a.empty() || b.empty()) {
return false;
}
const auto a_begin = reinterpret_cast<std::uintptr_t>(a.data());
const auto a_end = a_begin + a.size();
const auto b_begin = reinterpret_cast<std::uintptr_t>(b.data());
const auto b_end = b_begin + b.size();
return a_begin < b_end && b_begin < a_end;
}
using EvpMdPtr = std::unique_ptr<EVP_MD, decltype(&EVP_MD_free)>; using EvpMdPtr = std::unique_ptr<EVP_MD, decltype(&EVP_MD_free)>;
using EvpMdCtxPtr = using EvpMdCtxPtr =
std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>; std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>;
@@ -110,6 +136,7 @@ namespace Void::Crypto
? &kEmptyByte ? &kEmptyByte
: reinterpret_cast<const unsigned char*>(span.data()); : reinterpret_cast<const unsigned char*>(span.data());
} }
#endif
[[nodiscard]] Void::Result::Result<bool> [[nodiscard]] Void::Result::Result<bool>
verify_ed25519_impl(std::span<const std::byte> message, verify_ed25519_impl(std::span<const std::byte> message,
@@ -144,6 +171,12 @@ namespace Void::Crypto
return std::unexpected{std::move(*fault)}; return std::unexpected{std::move(*fault)};
} }
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
if (provider.prefer_builtin) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::verifyEd25519: Ed25519 requires OpenSSL backend")};
}
ERR_clear_error(); ERR_clear_error();
const char* propq = propq_or_null(provider); const char* propq = propq_or_null(provider);
EvpPkeyPtr key{EVP_PKEY_new_raw_public_key_ex( EvpPkeyPtr key{EVP_PKEY_new_raw_public_key_ex(
@@ -182,14 +215,33 @@ namespace Void::Crypto
} }
ERR_clear_error(); ERR_clear_error();
return result == 1; return result == 1;
#else
(void)provider;
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::verifyEd25519: built without OpenSSL backend")};
#endif
} }
} // namespace } // namespace
bool has_openssl_backend() noexcept
{
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
return true;
#else
return false;
#endif
}
void secure_wipe(std::span<std::byte> buffer) noexcept void secure_wipe(std::span<std::byte> buffer) noexcept
{ {
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
if (!buffer.empty()) { if (!buffer.empty()) {
OPENSSL_cleanse(buffer.data(), buffer.size()); OPENSSL_cleanse(buffer.data(), buffer.size());
} }
#else
Detail::builtin_secure_wipe(buffer);
#endif
} }
bool constant_time_equal(std::span<const std::byte> lhs, bool constant_time_equal(std::span<const std::byte> lhs,
@@ -201,7 +253,11 @@ namespace Void::Crypto
if (lhs.empty()) { if (lhs.empty()) {
return true; return true;
} }
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
return CRYPTO_memcmp(lhs.data(), rhs.data(), lhs.size()) == 0; return CRYPTO_memcmp(lhs.data(), rhs.data(), lhs.size()) == 0;
#else
return Detail::builtin_constant_time_equal(lhs, rhs);
#endif
} }
ScopedFaultGuard::ScopedFaultGuard(FaultConfig config) noexcept ScopedFaultGuard::ScopedFaultGuard(FaultConfig config) noexcept
@@ -218,8 +274,12 @@ namespace Void::Crypto
} }
struct Hasher::Impl { struct Hasher::Impl {
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
EvpMdCtxPtr context{nullptr, &EVP_MD_CTX_free}; EvpMdCtxPtr context{nullptr, &EVP_MD_CTX_free};
EvpMdPtr algorithm{nullptr, &EVP_MD_free}; EvpMdPtr algorithm{nullptr, &EVP_MD_free};
#endif
Detail::BuiltinHasher builtin{};
bool using_builtin{false};
HasherState state{HasherState::Ready}; HasherState state{HasherState::Ready};
}; };
@@ -244,18 +304,50 @@ namespace Void::Crypto
Void::Result::Result<Hasher> Void::Result::Result<Hasher>
Hasher::create(HashAlgorithm algorithm, const ProviderOptions& provider) Hasher::create(HashAlgorithm algorithm, const ProviderOptions& provider)
{ {
const char* md_name = algorithm_name(algorithm); switch (algorithm) {
if (md_name == nullptr) { case HashAlgorithm::Sha1:
return std::unexpected{make_crypto_error( case HashAlgorithm::Sha256:
CryptoErrorCode::unsupported_algorithm, case HashAlgorithm::Sha512:
"Crypto::Hasher: unsupported algorithm")}; case HashAlgorithm::Blake2b256:
case HashAlgorithm::Blake2b512:
break;
default:
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Hasher: unsupported algorithm")};
} }
if (auto fault = maybe_inject_fault(FaultOperation::hash_create, if (auto fault = maybe_inject_fault(FaultOperation::hash_create,
"Crypto::Hasher::create"); "Crypto::Hasher::create");
fault.has_value()) { fault.has_value()) {
return std::unexpected{std::move(*fault)}; return std::unexpected{std::move(*fault)};
} }
if (use_builtin_hash(algorithm, provider)) {
if (!provider.property_query.empty()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::provider_error,
"Crypto::Hasher: property_query unavailable on built-in "
"backend")};
}
auto impl = std::make_unique<Impl>();
if (!impl->builtin.init(algorithm)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher: built-in initialization failed")};
}
impl->using_builtin = true;
impl->state = HasherState::Ready;
return Hasher{std::move(impl)};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
const char* md_name = algorithm_name(algorithm);
if (md_name == nullptr) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Hasher: unsupported OpenSSL digest algorithm")};
}
ERR_clear_error(); ERR_clear_error();
auto impl = std::make_unique<Impl>(); auto impl = std::make_unique<Impl>();
impl->algorithm = EvpMdPtr{ impl->algorithm = EvpMdPtr{
@@ -278,8 +370,14 @@ namespace Void::Crypto
CryptoErrorCode::provider_error, CryptoErrorCode::provider_error,
"Crypto::Hasher: digest initialization failed")}; "Crypto::Hasher: digest initialization failed")};
} }
impl->using_builtin = false;
impl->state = HasherState::Ready; impl->state = HasherState::Ready;
return Hasher{std::move(impl)}; return Hasher{std::move(impl)};
#else
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher: OpenSSL backend unavailable")};
#endif
} }
Void::Result::Result<void> Hasher::update(std::span<const std::byte> data) Void::Result::Result<void> Hasher::update(std::span<const std::byte> data)
@@ -301,6 +399,12 @@ namespace Void::Crypto
m_impl->state = HasherState::Failed; m_impl->state = HasherState::Failed;
return std::unexpected{std::move(*fault)}; return std::unexpected{std::move(*fault)};
} }
if (m_impl->using_builtin) {
m_impl->builtin.update(data);
m_impl->state = HasherState::Updating;
return {};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
if (!data.empty() && if (!data.empty() &&
EVP_DigestUpdate(m_impl->context.get(), data.data(), EVP_DigestUpdate(m_impl->context.get(), data.data(),
data.size()) != 1) { data.size()) != 1) {
@@ -311,6 +415,12 @@ namespace Void::Crypto
} }
m_impl->state = HasherState::Updating; m_impl->state = HasherState::Updating;
return {}; return {};
#else
m_impl->state = HasherState::Failed;
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher::update: invalid backend")};
#endif
} }
Void::Result::Result<void> Hasher::update(std::string_view data) Void::Result::Result<void> Hasher::update(std::string_view data)
@@ -337,6 +447,12 @@ namespace Void::Crypto
m_impl->state = HasherState::Failed; m_impl->state = HasherState::Failed;
return std::unexpected{std::move(*fault)}; return std::unexpected{std::move(*fault)};
} }
if (m_impl->using_builtin) {
Digest digest = m_impl->builtin.finalize();
m_impl->state = HasherState::Finalized;
return digest;
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
const int digest_size = EVP_MD_get_size(m_impl->algorithm.get()); const int digest_size = EVP_MD_get_size(m_impl->algorithm.get());
if (digest_size <= 0) { if (digest_size <= 0) {
m_impl->state = HasherState::Failed; m_impl->state = HasherState::Failed;
@@ -357,6 +473,12 @@ namespace Void::Crypto
m_impl->state = HasherState::Finalized; m_impl->state = HasherState::Finalized;
digest.resize(written); digest.resize(written);
return digest; return digest;
#else
m_impl->state = HasherState::Failed;
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher::finalize: invalid backend")};
#endif
} }
auto hash(HashAlgorithm algorithm, std::span<const std::byte> data) auto hash(HashAlgorithm algorithm, std::span<const std::byte> data)
@@ -388,18 +510,31 @@ namespace Void::Crypto
auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path) auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path)
-> Void::Result::Result<Digest> -> Void::Result::Result<Digest>
{ {
return hashFile(algorithm, path, ProviderOptions{}); return hash_file(algorithm, path, ProviderOptions{});
} }
auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path, auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path,
const ProviderOptions& provider) const ProviderOptions& provider)
-> Void::Result::Result<Digest> -> Void::Result::Result<Digest>
{
return hash_file(algorithm, path, provider);
}
auto hash_file(HashAlgorithm algorithm, const std::filesystem::path& path)
-> Void::Result::Result<Digest>
{
return hash_file(algorithm, path, ProviderOptions{});
}
auto hash_file(HashAlgorithm algorithm, const std::filesystem::path& path,
const ProviderOptions& provider)
-> Void::Result::Result<Digest>
{ {
std::ifstream input{path, std::ios::binary}; std::ifstream input{path, std::ios::binary};
if (!input.is_open()) { if (!input.is_open()) {
return std::unexpected{make_crypto_error( return std::unexpected{make_crypto_error(
CryptoErrorCode::io_error, CryptoErrorCode::io_error,
std::format("Crypto::hashFile: cannot open '{}'", std::format("Crypto::hash_file: cannot open '{}'",
path.string()))}; path.string()))};
} }
auto hasher = Hasher::create(algorithm, provider); auto hasher = Hasher::create(algorithm, provider);
@@ -422,7 +557,7 @@ namespace Void::Crypto
if (input.bad() || (!input.eof() && input.fail())) { if (input.bad() || (!input.eof() && input.fail())) {
return std::unexpected{make_crypto_error( return std::unexpected{make_crypto_error(
CryptoErrorCode::io_error, CryptoErrorCode::io_error,
std::format("Crypto::hashFile: I/O error reading '{}'", std::format("Crypto::hash_file: I/O error reading '{}'",
path.string()))}; path.string()))};
} }
return hasher->finalize(); return hasher->finalize();
@@ -452,21 +587,63 @@ namespace Void::Crypto
{ {
return hash(HashAlgorithm::Sha512, data); return hash(HashAlgorithm::Sha512, data);
} }
Void::Result::Result<Digest> blake2b256(std::span<const std::byte> data)
{
return hash(HashAlgorithm::Blake2b256, data);
}
Void::Result::Result<Digest> blake2b256(std::string_view data)
{
return hash(HashAlgorithm::Blake2b256, data);
}
Void::Result::Result<Digest> blake2b512(std::span<const std::byte> data)
{
return hash(HashAlgorithm::Blake2b512, data);
}
Void::Result::Result<Digest> blake2b512(std::string_view data)
{
return hash(HashAlgorithm::Blake2b512, data);
}
Void::Result::Result<Digest> sha1File(const std::filesystem::path& path) Void::Result::Result<Digest> sha1File(const std::filesystem::path& path)
{ {
return hashFile(HashAlgorithm::Sha1, path); return hash_file(HashAlgorithm::Sha1, path);
} }
Void::Result::Result<Digest> sha256File(const std::filesystem::path& path) Void::Result::Result<Digest> sha256File(const std::filesystem::path& path)
{ {
return hashFile(HashAlgorithm::Sha256, path); return hash_file(HashAlgorithm::Sha256, path);
} }
Void::Result::Result<Digest> sha512File(const std::filesystem::path& path) Void::Result::Result<Digest> sha512File(const std::filesystem::path& path)
{ {
return hashFile(HashAlgorithm::Sha512, path); return hash_file(HashAlgorithm::Sha512, path);
}
Void::Result::Result<Digest> sha1_file(const std::filesystem::path& path)
{
return hash_file(HashAlgorithm::Sha1, path);
}
Void::Result::Result<Digest> sha256_file(const std::filesystem::path& path)
{
return hash_file(HashAlgorithm::Sha256, path);
}
Void::Result::Result<Digest> sha512_file(const std::filesystem::path& path)
{
return hash_file(HashAlgorithm::Sha512, path);
}
Void::Result::Result<Digest>
blake2b256_file(const std::filesystem::path& path)
{
return hash_file(HashAlgorithm::Blake2b256, path);
}
Void::Result::Result<Digest>
blake2b512_file(const std::filesystem::path& path)
{
return hash_file(HashAlgorithm::Blake2b512, path);
} }
struct Ed25519PrivateKey::Impl { struct Ed25519PrivateKey::Impl {
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
EvpPkeyPtr pkey{nullptr, &EVP_PKEY_free}; EvpPkeyPtr pkey{nullptr, &EVP_PKEY_free};
#else
std::uint8_t unused{0};
#endif
}; };
Ed25519PrivateKey::Ed25519PrivateKey(std::unique_ptr<Impl> impl) noexcept Ed25519PrivateKey::Ed25519PrivateKey(std::unique_ptr<Impl> impl) noexcept
@@ -481,7 +658,11 @@ namespace Void::Crypto
bool Ed25519PrivateKey::valid() const noexcept bool Ed25519PrivateKey::valid() const noexcept
{ {
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
return m_impl != nullptr && m_impl->pkey != nullptr; return m_impl != nullptr && m_impl->pkey != nullptr;
#else
return false;
#endif
} }
Void::Result::Result<Ed25519PrivateKey> Void::Result::Result<Ed25519PrivateKey>
@@ -492,6 +673,12 @@ namespace Void::Crypto
fault.has_value()) { fault.has_value()) {
return std::unexpected{std::move(*fault)}; return std::unexpected{std::move(*fault)};
} }
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
if (provider.prefer_builtin) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Ed25519PrivateKey::generate requires OpenSSL backend")};
}
ERR_clear_error(); ERR_clear_error();
EvpPkeyPtr key{ EvpPkeyPtr key{
EVP_PKEY_Q_keygen(nullptr, propq_or_null(provider), "ED25519"), EVP_PKEY_Q_keygen(nullptr, propq_or_null(provider), "ED25519"),
@@ -504,6 +691,13 @@ namespace Void::Crypto
auto impl = std::make_unique<Impl>(); auto impl = std::make_unique<Impl>();
impl->pkey = std::move(key); impl->pkey = std::move(key);
return Ed25519PrivateKey{std::move(impl)}; return Ed25519PrivateKey{std::move(impl)};
#else
(void)provider;
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Ed25519PrivateKey::generate: built without OpenSSL "
"backend")};
#endif
} }
Void::Result::Result<Ed25519PrivateKey> Void::Result::Result<Ed25519PrivateKey>
@@ -523,6 +717,13 @@ namespace Void::Crypto
fault.has_value()) { fault.has_value()) {
return std::unexpected{std::move(*fault)}; return std::unexpected{std::move(*fault)};
} }
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
if (provider.prefer_builtin) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Ed25519PrivateKey::from_raw_seed requires OpenSSL "
"backend")};
}
ERR_clear_error(); ERR_clear_error();
EvpPkeyPtr key{EVP_PKEY_new_raw_private_key_ex( EvpPkeyPtr key{EVP_PKEY_new_raw_private_key_ex(
nullptr, "ED25519", propq_or_null(provider), nullptr, "ED25519", propq_or_null(provider),
@@ -536,6 +737,13 @@ namespace Void::Crypto
auto impl = std::make_unique<Impl>(); auto impl = std::make_unique<Impl>();
impl->pkey = std::move(key); impl->pkey = std::move(key);
return Ed25519PrivateKey{std::move(impl)}; return Ed25519PrivateKey{std::move(impl)};
#else
(void)provider;
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Ed25519PrivateKey::from_raw_seed: built without OpenSSL "
"backend")};
#endif
} }
Void::Result::Result<Ed25519PublicKey> Ed25519PrivateKey::public_key() const Void::Result::Result<Ed25519PublicKey> Ed25519PrivateKey::public_key() const
@@ -546,6 +754,7 @@ namespace Void::Crypto
"Crypto::Ed25519PrivateKey::public_key: invalid or moved-from " "Crypto::Ed25519PrivateKey::public_key: invalid or moved-from "
"key")}; "key")};
} }
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
Ed25519PublicKey pub; Ed25519PublicKey pub;
std::size_t len = pub.bytes.size(); std::size_t len = pub.bytes.size();
if (EVP_PKEY_get_raw_public_key( if (EVP_PKEY_get_raw_public_key(
@@ -558,6 +767,12 @@ namespace Void::Crypto
"Crypto::Ed25519PrivateKey::public_key failed")}; "Crypto::Ed25519PrivateKey::public_key failed")};
} }
return pub; return pub;
#else
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Ed25519PrivateKey::public_key: built without OpenSSL "
"backend")};
#endif
} }
Void::Result::Result<Ed25519Seed> Ed25519PrivateKey::export_raw_seed() const Void::Result::Result<Ed25519Seed> Ed25519PrivateKey::export_raw_seed() const
@@ -568,6 +783,7 @@ namespace Void::Crypto
"Crypto::Ed25519PrivateKey::export_raw_seed: invalid or " "Crypto::Ed25519PrivateKey::export_raw_seed: invalid or "
"moved-from key")}; "moved-from key")};
} }
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
std::array<std::byte, Ed25519SeedSize> raw{}; std::array<std::byte, Ed25519SeedSize> raw{};
std::size_t len = raw.size(); std::size_t len = raw.size();
if (EVP_PKEY_get_raw_private_key( if (EVP_PKEY_get_raw_private_key(
@@ -582,6 +798,12 @@ namespace Void::Crypto
auto result = Ed25519Seed::from_bytes(raw); auto result = Ed25519Seed::from_bytes(raw);
secure_wipe(raw); secure_wipe(raw);
return result; return result;
#else
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Ed25519PrivateKey::export_raw_seed: built without OpenSSL "
"backend")};
#endif
} }
Void::Result::Result<Ed25519Signature> Void::Result::Result<Ed25519Signature>
@@ -607,6 +829,12 @@ namespace Void::Crypto
return std::unexpected{std::move(*fault)}; return std::unexpected{std::move(*fault)};
} }
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
if (provider.prefer_builtin) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::sign_ed25519 requires OpenSSL backend")};
}
ERR_clear_error(); ERR_clear_error();
EvpMdCtxPtr context{EVP_MD_CTX_new(), &EVP_MD_CTX_free}; EvpMdCtxPtr context{EVP_MD_CTX_new(), &EVP_MD_CTX_free};
if (!context) { if (!context) {
@@ -635,6 +863,12 @@ namespace Void::Crypto
"Crypto::sign_ed25519 failed")}; "Crypto::sign_ed25519 failed")};
} }
return signature; return signature;
#else
(void)provider;
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::sign_ed25519: built without OpenSSL backend")};
#endif
} }
Void::Result::Result<bool> verifyEd25519(std::span<const std::byte> message, Void::Result::Result<bool> verifyEd25519(std::span<const std::byte> message,
@@ -682,6 +916,19 @@ namespace Void::Crypto
return std::unexpected{std::move(*fault)}; return std::unexpected{std::move(*fault)};
} }
if (use_builtin_hash(HashAlgorithm::Sha256, provider)) {
if (!provider.property_query.empty()) {
secure_wipe(output);
return std::unexpected{make_crypto_error(
CryptoErrorCode::provider_error,
"Crypto::hmac_sha256_into: property_query unavailable on "
"built-in backend")};
}
Detail::builtin_hmac_sha256(secret_key, message, output);
return {};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
ERR_clear_error(); ERR_clear_error();
EvpMacPtr mac{EVP_MAC_fetch(nullptr, "HMAC", propq_or_null(provider)), EvpMacPtr mac{EVP_MAC_fetch(nullptr, "HMAC", propq_or_null(provider)),
&EVP_MAC_free}; &EVP_MAC_free};
@@ -732,6 +979,12 @@ namespace Void::Crypto
"Crypto::hmac_sha256_into: EVP_MAC_final failed")}; "Crypto::hmac_sha256_into: EVP_MAC_final failed")};
} }
return {}; return {};
#else
secure_wipe(output);
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::hmac_sha256_into: OpenSSL backend unavailable")};
#endif
} }
Void::Result::Result<Digest> hmac_sha256(std::span<const std::byte> secret_key, Void::Result::Result<Digest> hmac_sha256(std::span<const std::byte> secret_key,
@@ -780,6 +1033,20 @@ namespace Void::Crypto
return std::unexpected{std::move(*fault)}; return std::unexpected{std::move(*fault)};
} }
if (use_builtin_hash(HashAlgorithm::Sha256, provider)) {
if (!provider.property_query.empty()) {
secure_wipe(secret_output);
return std::unexpected{make_crypto_error(
CryptoErrorCode::provider_error,
"Crypto::hkdf_sha256: property_query unavailable on "
"built-in backend")};
}
Detail::builtin_hkdf_sha256(secret_input, salt, context,
secret_output);
return {};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
ERR_clear_error(); ERR_clear_error();
EvpKdfPtr kdf{EVP_KDF_fetch(nullptr, "HKDF", propq_or_null(provider)), EvpKdfPtr kdf{EVP_KDF_fetch(nullptr, "HKDF", propq_or_null(provider)),
&EVP_KDF_free}; &EVP_KDF_free};
@@ -825,6 +1092,12 @@ namespace Void::Crypto
"Crypto::hkdf_sha256: EVP_KDF_derive failed")}; "Crypto::hkdf_sha256: EVP_KDF_derive failed")};
} }
return {}; return {};
#else
secure_wipe(secret_output);
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::hkdf_sha256: OpenSSL backend unavailable")};
#endif
} }
} // namespace Void::Crypto } // namespace Void::Crypto
+16 -1
View File
@@ -1,6 +1,21 @@
set(_void_crypto_ext_deps "")
set(_void_crypto_has_openssl 0)
if(NOT CMAKE_DISABLE_FIND_PACKAGE_OpenSSL)
if(NOT TARGET OpenSSL::Crypto)
find_package(OpenSSL QUIET)
endif()
if(TARGET OpenSSL::Crypto)
list(APPEND _void_crypto_ext_deps OpenSSL::Crypto)
set(_void_crypto_has_openssl 1)
endif()
endif()
void_add_module(Crypto void_add_module(Crypto
INTERNAL_DEPS Functional INTERNAL_DEPS Functional
EXTERNAL_DEPS OpenSSL::Crypto EXTERNAL_DEPS ${_void_crypto_ext_deps}
EXCLUDE_HEADERS EXCLUDE_HEADERS
Void/Crypto/AsyncHash.hpp Void/Crypto/AsyncHash.hpp
) )
target_compile_definitions(Void_Crypto PUBLIC
VOID_CRYPTO_HAS_OPENSSL=${_void_crypto_has_openssl}
)
+1009 -108
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+34
View File
@@ -260,6 +260,21 @@ namespace Void::Net
return find_header(headers, name); return find_header(headers, name);
} }
ServerResponse ServerResponse::from_file(std::filesystem::path path,
std::string content_type,
std::uint16_t status)
{
if (content_type.empty()) {
content_type = std::string{content_type_for(path)};
}
return ServerResponse{
.status = status,
.headers = {Header{"Content-Type", std::move(content_type)}},
.body = {},
.file_body = std::move(path),
};
}
std::optional<std::string_view> std::optional<std::string_view>
ServerResponse::header(std::string_view name) const noexcept ServerResponse::header(std::string_view name) const noexcept
{ {
@@ -334,6 +349,25 @@ namespace Void::Net
return std::optional<ServerResponse>{std::move(*response)}; return std::optional<ServerResponse>{std::move(*response)};
} }
std::vector<Method> Router::allowed_methods(std::string_view path) const
{
if (path.empty() || !path.starts_with('/')) {
return {};
}
const auto segments = split_path(path_only(path));
std::vector<Method> methods;
{
std::shared_lock lock{mutex_};
for (const auto& route : routes_) {
if (match_route(route.segments, segments).has_value() &&
std::ranges::find(methods, route.method) == methods.end()) {
methods.push_back(route.method);
}
}
}
return methods;
}
std::size_t Router::size() const std::size_t Router::size() const
{ {
std::shared_lock lock{mutex_}; std::shared_lock lock{mutex_};
+10
View File
@@ -9,3 +9,13 @@ void_add_module(Net
OpenSSL::Crypto OpenSSL::Crypto
Threads::Threads Threads::Threads
) )
if(VOID_ENABLE_TSAN AND TARGET Void_Net)
# Boost.Asio 1.84's std_fenced_block calls std::atomic_thread_fence, which
# GCC warns is unsupported under -fsanitize=thread (-Werror=tsan). Keep
# hardware fences intact and scope the diagnostic suppression solely to
# Http.cpp so HttpServer.cpp and all other TUs keep full -Werror=tsan.
set_source_files_properties("${CMAKE_CURRENT_LIST_DIR}/Http.cpp"
PROPERTIES COMPILE_OPTIONS "$<$<CXX_COMPILER_ID:GNU>:-Wno-tsan>"
)
endif()
+833
View File
@@ -0,0 +1,833 @@
#include <Void/System/DirectoryWatcher.hpp>
#include <algorithm>
#include <array>
#include <cerrno>
#include <chrono>
#include <deque>
#include <filesystem>
#include <format>
#include <map>
#include <mutex>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#if defined(__linux__)
#include <poll.h>
#include <sys/eventfd.h>
#include <sys/inotify.h>
#include <unistd.h>
#endif
namespace Void::FileSystem
{
#if defined(__linux__)
namespace
{
constexpr std::uint32_t kWatchMask =
IN_CREATE | IN_DELETE | IN_MODIFY | IN_CLOSE_WRITE | IN_MOVED_FROM |
IN_MOVED_TO | IN_ATTRIB | IN_DELETE_SELF | IN_MOVE_SELF | IN_EXCL_UNLINK |
IN_ONLYDIR;
[[nodiscard]] bool is_subpath_or_equal(const std::filesystem::path& candidate,
const std::filesystem::path& prefix)
{
const std::string c = candidate.lexically_normal().generic_string();
const std::string p = prefix.lexically_normal().generic_string();
if (c == p) {
return true;
}
if (p.empty()) {
return false;
}
const std::size_t plen = p.size();
return c.size() > plen && c.compare(0, plen, p) == 0 && c[plen] == '/';
}
[[nodiscard]] std::filesystem::path
rebase_path(const std::filesystem::path& p,
const std::filesystem::path& old_prefix,
const std::filesystem::path& new_prefix)
{
const std::string ps = p.lexically_normal().generic_string();
const std::string os = old_prefix.lexically_normal().generic_string();
if (ps == os) {
return new_prefix;
}
if (ps.size() > os.size() && ps.compare(0, os.size(), os) == 0 &&
ps[os.size()] == '/') {
return new_prefix / std::filesystem::path{ps.substr(os.size() + 1U)};
}
return p;
}
} // namespace
struct DirectoryWatcher::Impl {
struct PendingMove {
std::filesystem::path path{};
bool is_directory{false};
std::chrono::steady_clock::time_point expires_at{};
};
Void::System::OwnedFd inotify_fd{};
Void::System::OwnedFd wake_fd{};
std::filesystem::path root{};
DirectoryWatcherOptions options{};
mutable std::mutex mutex{};
std::unordered_map<int, std::filesystem::path> wd_to_path{};
std::map<std::filesystem::path, int> path_to_wd{};
std::unordered_map<std::uint32_t, PendingMove> pending_moves{};
std::deque<DirectoryEvent> queue{};
bool rescan_emitted{false};
~Impl() noexcept
{
std::lock_guard lock{mutex};
for (const auto& [wd, _] : wd_to_path) {
if (inotify_fd.valid()) {
(void)::inotify_rm_watch(inotify_fd.get(), wd);
}
}
wd_to_path.clear();
path_to_wd.clear();
}
[[nodiscard]] bool should_ignore(const std::filesystem::path& p,
bool is_dir) const
{
if (options.ignore) {
return options.ignore(p, is_dir);
}
return false;
}
void push_event_locked(DirectoryEvent ev)
{
if (ev.kind == DirectoryEventKind::RescanRequired) {
if (rescan_emitted) {
return;
}
rescan_emitted = true;
queue.push_back(std::move(ev));
return;
}
if (queue.size() >= options.max_queued_events) {
if (!rescan_emitted) {
rescan_emitted = true;
queue.push_back(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = root,
.old_path = {},
.is_directory = true,
.detail = "DirectoryWatcher event queue full",
});
}
return;
}
queue.push_back(std::move(ev));
}
void remove_watch_by_wd_locked(int wd, bool call_rm)
{
auto it = wd_to_path.find(wd);
if (it == wd_to_path.end()) {
return;
}
path_to_wd.erase(it->second);
wd_to_path.erase(it);
if (call_rm && inotify_fd.valid()) {
(void)::inotify_rm_watch(inotify_fd.get(), wd);
}
}
void remove_subtree_watches_locked(const std::filesystem::path& prefix)
{
std::vector<int> wds;
for (const auto& [wd, p] : wd_to_path) {
if (is_subpath_or_equal(p, prefix)) {
wds.push_back(wd);
}
}
for (int wd : wds) {
remove_watch_by_wd_locked(wd, true);
}
}
void rewrite_subtree_watches_locked(const std::filesystem::path& old_prefix,
const std::filesystem::path& new_prefix)
{
std::vector<std::pair<int, std::filesystem::path>> updates;
for (const auto& [wd, p] : wd_to_path) {
if (is_subpath_or_equal(p, old_prefix)) {
updates.emplace_back(wd, rebase_path(p, old_prefix, new_prefix));
}
}
for (const auto& [wd, new_p] : updates) {
auto old_it = wd_to_path.find(wd);
if (old_it != wd_to_path.end()) {
path_to_wd.erase(old_it->second);
old_it->second = new_p;
path_to_wd[new_p] = wd;
}
}
}
void attach_single_dir_locked(const std::filesystem::path& dir_path)
{
const std::filesystem::path norm = dir_path.lexically_normal();
if (norm != root && should_ignore(norm, true)) {
return;
}
if (path_to_wd.contains(norm)) {
return;
}
if (wd_to_path.size() >= options.max_watches) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = norm,
.old_path = {},
.is_directory = true,
.detail = "DirectoryWatcher max_watches exceeded",
});
return;
}
const int wd =
::inotify_add_watch(inotify_fd.get(), norm.c_str(), kWatchMask);
if (wd < 0) {
const int err = errno;
if (err == ENOSPC || err == ENOMEM) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = norm,
.old_path = {},
.is_directory = true,
.detail = std::format(
"inotify_add_watch exhausted watches (errno={})", err),
});
}
return;
}
// inotify_add_watch may return an existing wd if directory inode aliased.
if (auto existing = wd_to_path.find(wd); existing != wd_to_path.end()) {
if (existing->second != norm) {
path_to_wd.erase(existing->second);
existing->second = norm;
}
} else {
wd_to_path.emplace(wd, norm);
}
path_to_wd[norm] = wd;
}
void attach_subtree_locked(const std::filesystem::path& dir_path,
bool emit_existing_children)
{
const std::filesystem::path norm = dir_path.lexically_normal();
if (norm != root && should_ignore(norm, true)) {
return;
}
std::error_code ec;
const auto st = std::filesystem::symlink_status(norm, ec);
if (ec || std::filesystem::is_symlink(st) ||
!std::filesystem::is_directory(st)) {
return;
}
attach_single_dir_locked(norm);
std::vector<std::filesystem::path> stack{norm};
while (!stack.empty()) {
const std::filesystem::path cur = std::move(stack.back());
stack.pop_back();
ec.clear();
std::filesystem::directory_iterator it{
cur,
std::filesystem::directory_options::skip_permission_denied,
ec};
if (ec) {
continue;
}
for (const auto& entry : it) {
std::error_code st_ec;
const auto est = entry.symlink_status(st_ec);
if (st_ec || std::filesystem::is_symlink(est)) {
continue;
}
const bool is_dir = std::filesystem::is_directory(est);
const std::filesystem::path ep =
entry.path().lexically_normal();
if (should_ignore(ep, is_dir)) {
continue;
}
if (emit_existing_children) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Created,
.path = ep,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
if (is_dir) {
attach_single_dir_locked(ep);
stack.push_back(ep);
}
}
}
}
void flush_expired_moves_locked(std::chrono::steady_clock::time_point now,
bool force_all)
{
for (auto it = pending_moves.begin(); it != pending_moves.end();) {
if (force_all || now >= it->second.expires_at) {
const auto p = it->second.path;
const bool is_dir = it->second.is_directory;
if (is_dir) {
remove_subtree_watches_locked(p);
}
if (!should_ignore(p, is_dir)) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Deleted,
.path = p,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
it = pending_moves.erase(it);
} else {
++it;
}
}
}
void process_inotify_event_locked(const struct inotify_event* ev)
{
if ((ev->mask & IN_Q_OVERFLOW) != 0U) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = root,
.old_path = {},
.is_directory = true,
.detail = "inotify kernel event queue overflow (IN_Q_OVERFLOW)",
});
return;
}
if ((ev->mask & IN_IGNORED) != 0U) {
remove_watch_by_wd_locked(ev->wd, false);
return;
}
const auto dir_it = wd_to_path.find(ev->wd);
if (dir_it == wd_to_path.end()) {
return;
}
const std::filesystem::path base = dir_it->second;
const bool is_dir = (ev->mask & IN_ISDIR) != 0U;
if ((ev->mask & (IN_DELETE_SELF | IN_MOVE_SELF)) != 0U && ev->len == 0U) {
if (base == root) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = root,
.old_path = {},
.is_directory = true,
.detail = "watched root directory deleted or moved",
});
remove_watch_by_wd_locked(ev->wd, false);
} else if ((ev->mask & IN_DELETE_SELF) != 0U) {
remove_watch_by_wd_locked(ev->wd, false);
}
return;
}
const std::string name =
(ev->len > 0U && ev->name[0] != '\0') ? std::string{ev->name}
: std::string{};
const std::filesystem::path full_path =
name.empty() ? base : (base / name).lexically_normal();
if ((ev->mask & IN_MOVED_FROM) != 0U) {
if (ev->cookie != 0U) {
pending_moves.insert_or_assign(
ev->cookie,
PendingMove{
.path = full_path,
.is_directory = is_dir,
.expires_at = std::chrono::steady_clock::now() +
options.rename_pair_window,
});
} else {
if (is_dir) {
remove_subtree_watches_locked(full_path);
}
if (!should_ignore(full_path, is_dir)) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Deleted,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
}
return;
}
if ((ev->mask & IN_MOVED_TO) != 0U) {
if (ev->cookie != 0U) {
if (auto mit = pending_moves.find(ev->cookie);
mit != pending_moves.end()) {
const std::filesystem::path old_path =
std::move(mit->second.path);
pending_moves.erase(mit);
const bool old_ignored = should_ignore(old_path, is_dir);
const bool new_ignored = should_ignore(full_path, is_dir);
if (is_dir) {
if (new_ignored) {
remove_subtree_watches_locked(old_path);
} else {
rewrite_subtree_watches_locked(old_path, full_path);
attach_subtree_locked(full_path, false);
}
}
if (!old_ignored && !new_ignored) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Renamed,
.path = full_path,
.old_path = old_path,
.is_directory = is_dir,
.detail = {},
});
} else if (!old_ignored && new_ignored) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Deleted,
.path = old_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
} else if (old_ignored && !new_ignored) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Created,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
return;
}
}
if (should_ignore(full_path, is_dir)) {
return;
}
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Created,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
if (is_dir) {
attach_subtree_locked(full_path, true);
}
return;
}
if (should_ignore(full_path, is_dir)) {
return;
}
if ((ev->mask & IN_CREATE) != 0U) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Created,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
if (is_dir) {
attach_subtree_locked(full_path, true);
}
}
if ((ev->mask & IN_DELETE) != 0U) {
if (is_dir) {
remove_subtree_watches_locked(full_path);
}
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Deleted,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
if ((ev->mask & (IN_MODIFY | IN_CLOSE_WRITE)) != 0U) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Modified,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
if ((ev->mask & IN_ATTRIB) != 0U) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::AttributeChanged,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
}
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
drain_inotify_locked()
{
alignas(struct inotify_event) std::array<char, 16384> buf{};
for (;;) {
const ssize_t n =
::read(inotify_fd.get(), buf.data(), buf.size());
if (n > 0) {
ssize_t offset = 0;
while (offset < n) {
const auto* ev =
reinterpret_cast<const struct inotify_event*>(
buf.data() + offset);
process_inotify_event_locked(ev);
offset += static_cast<ssize_t>(
sizeof(struct inotify_event) + ev->len);
}
continue;
}
if (n == 0) {
break;
}
if (errno == EINTR) {
continue;
}
if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"FileSystem::DirectoryWatcher: read(inotify) failed",
err)};
}
return {};
}
void drain_wake_locked() noexcept
{
std::uint64_t val = 0;
while (::read(wake_fd.get(), &val, sizeof(val)) > 0 ||
(errno == EINTR)) {
}
}
};
DirectoryWatcher::DirectoryWatcher(std::unique_ptr<Impl> impl) noexcept
: impl_(std::move(impl))
{
}
DirectoryWatcher::~DirectoryWatcher() noexcept = default;
DirectoryWatcher::DirectoryWatcher(DirectoryWatcher&&) noexcept = default;
DirectoryWatcher&
DirectoryWatcher::operator=(DirectoryWatcher&&) noexcept = default;
Void::Result::Result<DirectoryWatcher, Void::Result::Error>
DirectoryWatcher::create(const std::filesystem::path& root,
DirectoryWatcherOptions options)
{
if (root.empty()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::DirectoryWatcher::create: root cannot be empty")};
}
std::error_code ec;
const auto st = std::filesystem::status(root, ec);
if (ec || !std::filesystem::is_directory(st)) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::not_found,
std::format(
"FileSystem::DirectoryWatcher::create: '{}' is not a directory",
root.string()))};
}
const int ifd = ::inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
if (ifd < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"FileSystem::DirectoryWatcher::create: inotify_init1 failed",
err)};
}
Void::System::OwnedFd owned_ifd{ifd};
const int efd = ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
if (efd < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"FileSystem::DirectoryWatcher::create: eventfd failed",
err)};
}
Void::System::OwnedFd owned_efd{efd};
auto impl = std::make_unique<Impl>();
impl->inotify_fd = std::move(owned_ifd);
impl->wake_fd = std::move(owned_efd);
impl->root = std::filesystem::weakly_canonical(root, ec);
if (ec || impl->root.empty()) {
impl->root = root.lexically_normal();
}
impl->options = std::move(options);
{
std::lock_guard lock{impl->mutex};
impl->attach_subtree_locked(impl->root, false);
}
return DirectoryWatcher{std::move(impl)};
}
Void::Result::Result<std::vector<DirectoryEvent>, Void::Result::Error>
DirectoryWatcher::poll(std::chrono::milliseconds timeout)
{
if (!impl_) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::DirectoryWatcher::poll: moved-from watcher")};
}
const auto start = std::chrono::steady_clock::now();
const auto end_time = start + std::max(std::chrono::milliseconds{0}, timeout);
int ifd = -1;
int efd = -1;
{
std::lock_guard lock{impl_->mutex};
if (auto dr = impl_->drain_inotify_locked(); !dr.has_value()) {
return std::unexpected{std::move(dr.error())};
}
impl_->flush_expired_moves_locked(std::chrono::steady_clock::now(),
timeout.count() <= 0);
if (!impl_->queue.empty() && impl_->pending_moves.empty()) {
std::vector<DirectoryEvent> out;
out.reserve(impl_->queue.size());
while (!impl_->queue.empty()) {
out.push_back(std::move(impl_->queue.front()));
impl_->queue.pop_front();
}
return out;
}
ifd = impl_->inotify_fd.get();
efd = impl_->wake_fd.get();
}
if (timeout.count() > 0) {
for (;;) {
const auto now = std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point wait_until = end_time;
{
std::lock_guard lock{impl_->mutex};
for (const auto& [_, pm] : impl_->pending_moves) {
wait_until = std::min(wait_until, pm.expires_at);
}
}
if (now >= wait_until) {
std::lock_guard lock{impl_->mutex};
impl_->flush_expired_moves_locked(now, false);
if (now >= end_time ||
(!impl_->queue.empty() && impl_->pending_moves.empty())) {
break;
}
continue;
}
const auto rem_ms = std::max<long long>(
1,
std::chrono::duration_cast<std::chrono::milliseconds>(
wait_until - now)
.count());
std::array<struct pollfd, 2> pfds{{
{ifd, POLLIN, 0},
{efd, POLLIN, 0},
}};
const int rc =
::poll(pfds.data(), pfds.size(), static_cast<int>(rem_ms));
if (rc < 0) {
if (errno == EINTR) {
continue;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"FileSystem::DirectoryWatcher::poll: poll failed",
err)};
}
std::lock_guard lock{impl_->mutex};
if (auto dr = impl_->drain_inotify_locked(); !dr.has_value()) {
return std::unexpected{std::move(dr.error())};
}
const bool woken = (pfds[1].revents & POLLIN) != 0;
if (woken) {
impl_->drain_wake_locked();
}
impl_->flush_expired_moves_locked(std::chrono::steady_clock::now(),
false);
if (woken ||
(!impl_->queue.empty() && impl_->pending_moves.empty())) {
break;
}
}
}
std::lock_guard lock{impl_->mutex};
std::vector<DirectoryEvent> out;
out.reserve(impl_->queue.size());
while (!impl_->queue.empty()) {
out.push_back(std::move(impl_->queue.front()));
impl_->queue.pop_front();
}
return out;
}
Void::Result::Result<void, Void::Result::Error> DirectoryWatcher::rescan()
{
if (!impl_) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::DirectoryWatcher::rescan: moved-from watcher")};
}
std::lock_guard lock{impl_->mutex};
for (const auto& [wd, _] : impl_->wd_to_path) {
(void)::inotify_rm_watch(impl_->inotify_fd.get(), wd);
}
impl_->wd_to_path.clear();
impl_->path_to_wd.clear();
impl_->pending_moves.clear();
impl_->queue.clear();
impl_->rescan_emitted = false;
impl_->attach_subtree_locked(impl_->root, false);
return {};
}
void DirectoryWatcher::wake() noexcept
{
if (!impl_ || !impl_->wake_fd.valid()) {
return;
}
const std::uint64_t one = 1;
while (::write(impl_->wake_fd.get(), &one, sizeof(one)) < 0 &&
errno == EINTR) {
}
}
void DirectoryWatcher::simulate_overflow_for_test()
{
if (!impl_) {
return;
}
{
std::lock_guard lock{impl_->mutex};
impl_->push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = impl_->root,
.old_path = {},
.is_directory = true,
.detail = "simulated IN_Q_OVERFLOW",
});
}
wake();
}
const std::filesystem::path& DirectoryWatcher::root() const noexcept
{
static const std::filesystem::path kEmpty{};
return impl_ ? impl_->root : kEmpty;
}
std::size_t DirectoryWatcher::watch_count() const noexcept
{
if (!impl_) {
return 0;
}
std::lock_guard lock{impl_->mutex};
return impl_->wd_to_path.size();
}
int DirectoryWatcher::native_handle() const noexcept
{
return impl_ ? impl_->inotify_fd.get() : -1;
}
#else
struct DirectoryWatcher::Impl {
std::filesystem::path root{};
};
DirectoryWatcher::DirectoryWatcher(std::unique_ptr<Impl> impl) noexcept
: impl_(std::move(impl))
{
}
DirectoryWatcher::~DirectoryWatcher() noexcept = default;
DirectoryWatcher::DirectoryWatcher(DirectoryWatcher&&) noexcept = default;
DirectoryWatcher&
DirectoryWatcher::operator=(DirectoryWatcher&&) noexcept = default;
Void::Result::Result<DirectoryWatcher, Void::Result::Error>
DirectoryWatcher::create(const std::filesystem::path&,
DirectoryWatcherOptions)
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::DirectoryWatcher: inotify watcher is Linux-only")};
}
Void::Result::Result<std::vector<DirectoryEvent>, Void::Result::Error>
DirectoryWatcher::poll(std::chrono::milliseconds)
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::DirectoryWatcher: unsupported platform")};
}
Void::Result::Result<void, Void::Result::Error> DirectoryWatcher::rescan()
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::DirectoryWatcher: unsupported platform")};
}
void DirectoryWatcher::wake() noexcept {}
void DirectoryWatcher::simulate_overflow_for_test() {}
const std::filesystem::path& DirectoryWatcher::root() const noexcept
{
static const std::filesystem::path kEmpty{};
return impl_ ? impl_->root : kEmpty;
}
std::size_t DirectoryWatcher::watch_count() const noexcept { return 0; }
int DirectoryWatcher::native_handle() const noexcept { return -1; }
#endif
} // namespace Void::FileSystem
+192 -54
View File
@@ -40,6 +40,7 @@ Child::Child(Child&&) noexcept = default;
Child& Child::operator=(Child&&) noexcept = default; Child& Child::operator=(Child&&) noexcept = default;
bool Child::valid() const noexcept { return false; } bool Child::valid() const noexcept { return false; }
bool Child::running() const noexcept { return false; } bool Child::running() const noexcept { return false; }
bool Child::process_group_alive() const noexcept { return false; }
long long Child::pid() const noexcept { return -1; } long long Child::pid() const noexcept { return -1; }
long long Child::pgid() const noexcept { return -1; } long long Child::pgid() const noexcept { return -1; }
bool Child::owns_process_group() const noexcept { return false; } bool Child::owns_process_group() const noexcept { return false; }
@@ -142,6 +143,13 @@ Void::Result::Result<void, Void::Result::Error> reexec(
return Void::Result::fail("Process::reexec: not implemented on Windows"); return Void::Result::fail("Process::reexec: not implemented on Windows");
} }
Void::Result::Result<void, Void::Result::Error> enable_subreaper() noexcept
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"Process::enable_subreaper: not supported on Windows")};
}
} // namespace Void::Process } // namespace Void::Process
#else // POSIX #else // POSIX
@@ -150,6 +158,9 @@ Void::Result::Result<void, Void::Result::Error> reexec(
#include <fcntl.h> #include <fcntl.h>
#include <poll.h> #include <poll.h>
#include <signal.h> #include <signal.h>
#if defined(__linux__) && __has_include(<sys/prctl.h>)
#include <sys/prctl.h>
#endif
#include <sys/stat.h> #include <sys/stat.h>
#include <sys/syscall.h> #include <sys/syscall.h>
#include <sys/wait.h> #include <sys/wait.h>
@@ -468,26 +479,102 @@ void write_child_failure(int err_fd, int phase, int err) noexcept
return st; return st;
} }
[[nodiscard]] bool is_process_group_alive(pid_t pgid) noexcept
{
if (pgid <= 0) {
return false;
}
for (;;) {
if (::kill(-pgid, 0) == 0) {
return true;
}
if (errno == EINTR) {
continue;
}
return errno == EPERM;
}
}
void reap_group_nonblocking(pid_t pid,
pid_t pgid,
bool owns_group,
bool& reaped,
ExitStatus& cached,
int& out_errno) noexcept
{
out_errno = 0;
if (!reaped && pid > 0) {
int raw = 0;
for (;;) {
const pid_t w = ::waitpid(pid, &raw, WNOHANG);
if (w == pid) {
cached = decode_wait_status(raw);
reaped = true;
break;
}
if (w == 0) {
break;
}
if (errno == EINTR) {
continue;
}
if (errno == ECHILD) {
reaped = true;
break;
}
out_errno = errno;
break;
}
}
if (owns_group && pgid > 0) {
int raw = 0;
for (;;) {
const pid_t w = ::waitpid(-pgid, &raw, WNOHANG);
if (w > 0) {
if (w == pid && !reaped) {
cached = decode_wait_status(raw);
reaped = true;
}
continue;
}
if (w == 0) {
break;
}
if (errno == EINTR) {
continue;
}
break;
}
}
}
[[nodiscard]] bool signal_target(pid_t pid, [[nodiscard]] bool signal_target(pid_t pid,
pid_t pgid, pid_t pgid,
bool owns_group, bool owns_group,
bool leader_reaped,
int sig, int sig,
int& out_errno) noexcept int& out_errno) noexcept
{ {
bool delivered = false;
out_errno = 0;
if (owns_group && pgid > 0) { if (owns_group && pgid > 0) {
if (::kill(-pgid, sig) == 0) { if (::kill(-pgid, sig) == 0) {
return true; delivered = true;
} } else {
out_errno = errno; out_errno = errno;
if (out_errno != ESRCH && out_errno != EPERM) { if (out_errno != ESRCH && out_errno != EPERM) {
return false; return false;
}
} }
} }
if (::kill(pid, sig) == 0) { if (!leader_reaped && pid > 0) {
return true; if (::kill(pid, sig) == 0) {
delivered = true;
} else {
out_errno = errno;
}
} }
out_errno = errno; return delivered;
return false;
} }
[[nodiscard]] std::optional<std::string> [[nodiscard]] std::optional<std::string>
@@ -706,6 +793,13 @@ Child& Child::operator=(Child&& other) noexcept
bool Child::valid() const noexcept { return pid_ > 0; } bool Child::valid() const noexcept { return pid_ > 0; }
bool Child::running() const noexcept { return pid_ > 0 && !reaped_; } bool Child::running() const noexcept { return pid_ > 0 && !reaped_; }
bool Child::process_group_alive() const noexcept
{
if (owns_group_ && pgid_ > 0) {
return is_process_group_alive(static_cast<pid_t>(pgid_));
}
return running();
}
long long Child::pid() const noexcept { return pid_; } long long Child::pid() const noexcept { return pid_; }
long long Child::pgid() const noexcept { return pgid_; } long long Child::pgid() const noexcept { return pgid_; }
bool Child::owns_process_group() const noexcept { return owns_group_; } bool Child::owns_process_group() const noexcept { return owns_group_; }
@@ -738,7 +832,7 @@ Void::Result::Result<void, Void::Result::Error> Child::send_signal(int sig) noex
Void::System::SystemErrorCode::invalid_argument, Void::System::SystemErrorCode::invalid_argument,
"Process::Child::send_signal: invalid child")}; "Process::Child::send_signal: invalid child")};
} }
if (reaped_) { if (reaped_ && (!owns_group_ || !process_group_alive())) {
return std::unexpected{Void::System::make_system_error( return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::busy, Void::System::SystemErrorCode::busy,
"Process::Child::send_signal: child already reaped")}; "Process::Child::send_signal: child already reaped")};
@@ -747,6 +841,7 @@ Void::Result::Result<void, Void::Result::Error> Child::send_signal(int sig) noex
if (!signal_target(static_cast<pid_t>(pid_), if (!signal_target(static_cast<pid_t>(pid_),
static_cast<pid_t>(pgid_), static_cast<pid_t>(pgid_),
owns_group_, owns_group_,
reaped_,
sig, sig,
err)) { err)) {
return std::unexpected{Void::System::make_system_error( return std::unexpected{Void::System::make_system_error(
@@ -798,35 +893,37 @@ Void::Result::Result<ExitStatus, Void::Result::Error>
Void::System::SystemErrorCode::invalid_argument, Void::System::SystemErrorCode::invalid_argument,
"Process::Child::terminate: invalid child")}; "Process::Child::terminate: invalid child")};
} }
if (reaped_) {
const pid_t target_pid = static_cast<pid_t>(pid_);
const pid_t target_pgid = static_cast<pid_t>(pgid_);
const bool group_owned = owns_group_ && target_pgid > 0;
auto group_finished = [&]() noexcept -> bool {
int reap_err = 0;
reap_group_nonblocking(
target_pid, target_pgid, group_owned, reaped_, cached_status_, reap_err);
if (!reaped_) {
return false;
}
return !group_owned || !is_process_group_alive(target_pgid);
};
if (group_finished()) {
return cached_status_; return cached_status_;
} }
const auto effective_grace = const auto effective_grace =
(grace.count() >= 0) ? grace : kill_grace_; (grace.count() >= 0) ? grace : kill_grace_;
if (auto polled = try_wait(); !polled.has_value()) {
return std::unexpected{polled.error()};
} else if (polled->has_value()) {
return **polled;
}
int sig_err = 0; int sig_err = 0;
(void)signal_target(static_cast<pid_t>(pid_), (void)signal_target(
static_cast<pid_t>(pgid_), target_pid, target_pgid, group_owned, reaped_, SIGTERM, sig_err);
owns_group_,
SIGTERM,
sig_err);
const auto grace_deadline = const auto grace_deadline =
std::chrono::steady_clock::now() + effective_grace; std::chrono::steady_clock::now() + effective_grace;
while (std::chrono::steady_clock::now() < grace_deadline) { while (std::chrono::steady_clock::now() < grace_deadline) {
auto polled = try_wait(); if (group_finished()) {
if (!polled.has_value()) { return cached_status_;
return std::unexpected{polled.error()};
}
if (polled->has_value()) {
return **polled;
} }
const auto rem = std::chrono::duration_cast<std::chrono::milliseconds>( const auto rem = std::chrono::duration_cast<std::chrono::milliseconds>(
grace_deadline - std::chrono::steady_clock::now()); grace_deadline - std::chrono::steady_clock::now());
@@ -834,38 +931,61 @@ Void::Result::Result<ExitStatus, Void::Result::Error>
break; break;
} }
std::this_thread::sleep_for( std::this_thread::sleep_for(
std::min(rem, std::chrono::milliseconds{10})); std::min(rem, std::chrono::milliseconds{5}));
} }
if (auto polled = try_wait(); !polled.has_value()) { if (group_finished()) {
return std::unexpected{polled.error()}; return cached_status_;
} else if (polled->has_value()) {
return **polled;
} }
(void)signal_target(static_cast<pid_t>(pid_), (void)signal_target(
static_cast<pid_t>(pgid_), target_pid, target_pgid, group_owned, reaped_, SIGKILL, sig_err);
owns_group_,
SIGKILL,
sig_err);
int raw = 0; if (!reaped_) {
for (;;) { int raw = 0;
const pid_t w = ::waitpid(static_cast<pid_t>(pid_), &raw, 0); for (;;) {
if (w == static_cast<pid_t>(pid_)) { const pid_t w = ::waitpid(target_pid, &raw, 0);
cached_status_ = decode_wait_status(raw); if (w == target_pid) {
reaped_ = true; cached_status_ = decode_wait_status(raw);
return cached_status_; reaped_ = true;
break;
}
if (errno == EINTR) {
continue;
}
if (errno == ECHILD) {
reaped_ = true;
break;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"Process::Child::terminate: final waitpid failed",
err)};
} }
if (errno == EINTR) {
continue;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"Process::Child::terminate: final waitpid failed",
err)};
} }
if (group_owned) {
const auto kill_ceiling =
std::chrono::steady_clock::now() + std::chrono::seconds{5};
while (!group_finished()) {
if (std::chrono::steady_clock::now() >= kill_ceiling) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::timed_out,
"Process::Child::terminate: process group members failed "
"to exit after SIGKILL")};
}
(void)signal_target(target_pid,
target_pgid,
group_owned,
reaped_,
SIGKILL,
sig_err);
std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
}
return cached_status_;
} }
Void::Result::Result<ExitStatus, Void::Result::Error> Child::wait_blocking( Void::Result::Result<ExitStatus, Void::Result::Error> Child::wait_blocking(
@@ -950,7 +1070,7 @@ void Child::reset_and_reap() noexcept
stdin_.reset(); stdin_.reset();
stdout_.reset(); stdout_.reset();
stderr_.reset(); stderr_.reset();
if (pid_ > 0 && !reaped_) { if (pid_ > 0 && (!reaped_ || process_group_alive())) {
(void)terminate(kill_grace_); (void)terminate(kill_grace_);
} }
pid_ = -1; pid_ = -1;
@@ -1643,6 +1763,24 @@ Void::Result::Result<void, Void::Result::Error>
err)}; err)};
} }
Void::Result::Result<void, Void::Result::Error> enable_subreaper() noexcept
{
#if defined(__linux__) && defined(PR_SET_CHILD_SUBREAPER)
if (::prctl(PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"Process::enable_subreaper: prctl(PR_SET_CHILD_SUBREAPER) failed",
err)};
}
return {};
#else
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"Process::enable_subreaper: PR_SET_CHILD_SUBREAPER unavailable on this platform")};
#endif
}
} // namespace Void::Process } // namespace Void::Process
#endif // _WIN32 #endif // _WIN32
+3
View File
@@ -133,6 +133,9 @@ if(_all_generated)
if(TARGET OpenSSL::Crypto) if(TARGET OpenSSL::Crypto)
target_link_libraries(VoidTests PRIVATE OpenSSL::Crypto) target_link_libraries(VoidTests PRIVATE OpenSSL::Crypto)
endif() endif()
if(TARGET OpenSSL::SSL)
target_link_libraries(VoidTests PRIVATE OpenSSL::SSL)
endif()
if(TARGET SQLite3::SQLite3) if(TARGET SQLite3::SQLite3)
target_link_libraries(VoidTests PRIVATE SQLite3::SQLite3) target_link_libraries(VoidTests PRIVATE SQLite3::SQLite3)
endif() endif()
+54
View File
@@ -194,6 +194,57 @@ int mode_ignore_sigterm(int argc, char** argv)
return 0; return 0;
} }
int mode_grandchild_ignore_sigterm(int argc, char** argv)
{
if (argc < 3) {
return usage_error("grandchild-ignore-sigterm requires <marker_file>");
}
const char* marker_path = argv[2];
int ready_p[2]{-1, -1};
if (::pipe(ready_p) != 0) {
return 1;
}
const pid_t gc = ::fork();
if (gc < 0) {
(void)::close(ready_p[0]);
(void)::close(ready_p[1]);
return 1;
}
if (gc == 0) {
(void)::close(ready_p[0]);
std::signal(SIGTERM, SIG_IGN);
const int mfd = ::open(marker_path, O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0644);
if (mfd < 0) {
(void)::close(ready_p[1]);
::_exit(1);
}
static constexpr char kTick[] = "tick\n";
(void)write_all_fd(mfd, kTick, sizeof(kTick) - 1);
static constexpr char kReady[] = "ready\n";
(void)write_all_fd(STDOUT_FILENO, kReady, sizeof(kReady) - 1);
const char one = '1';
(void)write_all_fd(ready_p[1], &one, 1);
(void)::close(ready_p[1]);
(void)::close(STDIN_FILENO);
(void)::close(STDOUT_FILENO);
(void)::close(STDERR_FILENO);
for (int iter = 0; iter < 500; ++iter) {
std::this_thread::sleep_for(std::chrono::milliseconds{10});
(void)write_all_fd(mfd, kTick, sizeof(kTick) - 1);
}
(void)::close(mfd);
::_exit(0);
}
(void)::close(ready_p[1]);
char dummy = 0;
bool eof = false;
(void)read_exact_fd(ready_p[0], &dummy, 1, eof);
(void)::close(ready_p[0]);
::_exit(0);
}
int mode_simultaneous_io(int argc, char** argv) int mode_simultaneous_io(int argc, char** argv)
{ {
if (argc != 3) { if (argc != 3) {
@@ -485,6 +536,9 @@ int main(int argc, char** argv)
if (mode == "ignore-sigterm") { if (mode == "ignore-sigterm") {
return mode_ignore_sigterm(argc, argv); return mode_ignore_sigterm(argc, argv);
} }
if (mode == "grandchild-ignore-sigterm") {
return mode_grandchild_ignore_sigterm(argc, argv);
}
if (mode == "simultaneous-io") { if (mode == "simultaneous-io") {
return mode_simultaneous_io(argc, argv); return mode_simultaneous_io(argc, argv);
} }
+5 -1
View File
@@ -12,8 +12,12 @@ int main()
.content = {std::byte{'h'}, std::byte{'i'}}, .content = {std::byte{'h'}, std::byte{'i'}},
}, },
}}; }};
Void::Archive::CreationOptions opts;
opts.compression = Void::Archive::has_libarchive_backend()
? Void::Archive::ArchiveCompression::Zstd
: Void::Archive::ArchiveCompression::None;
Void::Archive::VectorByteSink sink; Void::Archive::VectorByteSink sink;
if (!Void::Archive::create_archive(sink, entries).has_value()) { if (!Void::Archive::create(sink, entries, opts).has_value()) {
return 1; return 1;
} }
Void::Archive::SpanByteSource src{sink.bytes()}; Void::Archive::SpanByteSource src{sink.bytes()};
+23 -13
View File
@@ -9,23 +9,33 @@ int main()
if (!digest.has_value() || digest->size() != 32) { if (!digest.has_value() || digest->size() != 32) {
return 1; return 1;
} }
auto key = Void::Crypto::Ed25519PrivateKey::generate(); auto b2 = Void::Crypto::blake2b256("abc");
if (!key.has_value()) { if (!b2.has_value() || b2->size() != 32) {
return 2; return 6;
}
auto pub = key->public_key();
if (!pub.has_value()) {
return 3;
} }
const std::array<std::byte, 4> msg{std::byte{1}, std::byte{2}, std::byte{3}, const std::array<std::byte, 4> msg{std::byte{1}, std::byte{2}, std::byte{3},
std::byte{4}}; std::byte{4}};
auto sig = Void::Crypto::sign_ed25519(msg, *key); auto mac = Void::Crypto::hmac_sha256(msg, msg);
if (!sig.has_value()) { if (!mac.has_value() || mac->size() != Void::Crypto::HmacSha256Size) {
return 4; return 7;
} }
auto ok = Void::Crypto::verify_ed25519(msg, *sig, *pub); if (Void::Crypto::has_openssl_backend()) {
if (!ok.has_value() || !*ok) { auto key = Void::Crypto::Ed25519PrivateKey::generate();
return 5; if (!key.has_value()) {
return 2;
}
auto pub = key->public_key();
if (!pub.has_value()) {
return 3;
}
auto sig = Void::Crypto::sign_ed25519(msg, *key);
if (!sig.has_value()) {
return 4;
}
auto ok = Void::Crypto::verify_ed25519(msg, *sig, *pub);
if (!ok.has_value() || !*ok) {
return 5;
}
} }
return 0; return 0;
} }
+8
View File
@@ -292,6 +292,14 @@ if(_has_fsm)
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
endif() endif()
has_modules(_has_net Net Functional Text)
if(_has_net)
run_consumer(NetOnly "${install_prefix}" "NetOnly"
-DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
endif()
# Foundation consumer with Core-formatting bridge and zero external packages. # Foundation consumer with Core-formatting bridge and zero external packages.
has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core) has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core)
if(_has_foundation) if(_has_foundation)
+11
View File
@@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 4.0)
project(VoidNetOnlyConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS Net)
add_executable(void_net_only_consumer main.cpp)
target_link_libraries(void_net_only_consumer PRIVATE Void::Net)
target_compile_features(void_net_only_consumer PRIVATE cxx_std_26)
enable_testing()
add_test(NAME NetOnlyConsumer COMMAND void_net_only_consumer)
+31
View File
@@ -0,0 +1,31 @@
#include <Void/Net/Http.hpp>
#include <Void/Net/HttpServer.hpp>
#include <string>
int main()
{
Void::Net::HttpServer server;
if (!server
.add_route(Void::Net::Method::Get, "/ping",
[](const Void::Net::ServerRequest&) {
return Void::Result::ok(Void::Net::ServerResponse{
.status = 200, .body = "pong"});
})
.has_value()) {
return 1;
}
if (!server.start().has_value() || server.bound_port() == 0) {
return 2;
}
auto client = Void::Net::HttpClient::secure();
if (!client.verify_tls()) {
return 3;
}
auto resp = client.get(server.base_url() + "/ping");
server.shutdown();
if (!resp.has_value() || resp->status != 200 || resp->body != "pong") {
return 4;
}
return 0;
}
@@ -0,0 +1,12 @@
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
VOID_TEST(NativeGxx, from_dir_a_first)
{
Void::Testing::expect_eq(10 + 5, 15);
}
VOID_TEST(NativeGxx, duplicate_name_test)
{
Void::Testing::expect(true);
}
@@ -0,0 +1,12 @@
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
VOID_TEST(NativeGxx, from_dir_b_first)
{
Void::Testing::expect_eq(6 * 7, 42);
}
VOID_TEST(NativeGxx, duplicate_name_test)
{
Void::Testing::expect_eq(1, 1);
}
+101 -14
View File
@@ -3,8 +3,10 @@
#include <Void/Testing/Assert.hpp> #include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp> #include <Void/Testing/Test.hpp>
#include <algorithm>
#include <array> #include <array>
#include <atomic> #include <atomic>
#include <cstring>
#include <filesystem> #include <filesystem>
#include <fstream> #include <fstream>
#include <memory> #include <memory>
@@ -13,23 +15,95 @@
#include <string_view> #include <string_view>
#include <system_error> #include <system_error>
#include <thread> #include <thread>
#include <vector>
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
#include <archive.h> #include <archive.h>
#include <archive_entry.h> #include <archive_entry.h>
#endif
namespace namespace
{ {
enum class FixtureEntryType { Regular, Directory, Symlink };
struct ArchiveEntry { struct ArchiveEntry {
std::string_view path; std::string_view path;
std::string_view contents; std::string_view contents;
unsigned int type{AE_IFREG}; FixtureEntryType type{FixtureEntryType::Regular};
std::string_view link; std::string_view link;
}; };
void write_archive(const std::filesystem::path &path, void write_octal(std::span<char> dst, std::uint64_t val)
std::span<const ArchiveEntry>
entries)
{ {
dst.back() = '\0';
std::size_t pos = dst.size() - 1;
while (pos > 0) {
--pos;
dst[pos] = static_cast<char>('0' + (val & 7ULL));
val >>= 3ULL;
}
}
void write_raw_tar(const std::filesystem::path& path,
std::span<const ArchiveEntry> entries)
{
std::ofstream out{path, std::ios::binary | std::ios::trunc};
Void::Testing::require(out.is_open());
for (const auto& spec : entries) {
std::array<char, 512> hdr{};
std::memcpy(hdr.data(), spec.path.data(),
std::min<std::size_t>(spec.path.size(), 100));
const std::uint32_t perm =
spec.type == FixtureEntryType::Directory ? 0755U : 0644U;
write_octal(std::span{hdr}.subspan(100, 8), perm);
write_octal(std::span{hdr}.subspan(108, 8), 0);
write_octal(std::span{hdr}.subspan(116, 8), 0);
const std::uint64_t sz =
spec.type == FixtureEntryType::Regular ? spec.contents.size()
: 0ULL;
write_octal(std::span{hdr}.subspan(124, 12), sz);
write_octal(std::span{hdr}.subspan(136, 12), 0);
std::fill(hdr.begin() + 148, hdr.begin() + 156, ' ');
hdr[156] = spec.type == FixtureEntryType::Directory
? '5'
: (spec.type == FixtureEntryType::Symlink ? '2' : '0');
if (!spec.link.empty()) {
std::memcpy(hdr.data() + 157, spec.link.data(),
std::min<std::size_t>(spec.link.size(), 100));
}
std::memcpy(hdr.data() + 257, "ustar\0", 6);
hdr[263] = '0';
hdr[264] = '0';
std::uint32_t sum = 0;
for (const char ch : hdr) {
sum += static_cast<unsigned char>(ch);
}
write_octal(std::span{hdr}.subspan(148, 7), sum);
hdr[155] = ' ';
out.write(hdr.data(), hdr.size());
if (spec.type == FixtureEntryType::Regular && !spec.contents.empty()) {
out.write(spec.contents.data(),
static_cast<std::streamsize>(spec.contents.size()));
const std::size_t rem = spec.contents.size() % 512U;
if (rem != 0) {
std::array<char, 512> pad{};
out.write(pad.data(),
static_cast<std::streamsize>(512U - rem));
}
}
}
std::array<char, 1024> eof{};
out.write(eof.data(), eof.size());
out.close();
Void::Testing::require(out.good());
}
void write_archive(const std::filesystem::path& path,
std::span<const ArchiveEntry> entries)
{
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
using Writer = std::unique_ptr<archive, decltype(&archive_write_free)>; using Writer = std::unique_ptr<archive, decltype(&archive_write_free)>;
using Entry = using Entry =
std::unique_ptr<archive_entry, decltype(&archive_entry_free)>; std::unique_ptr<archive_entry, decltype(&archive_entry_free)>;
@@ -47,14 +121,21 @@ namespace
writer.get(), path.c_str()) == ARCHIVE_OK); writer.get(), path.c_str()) == ARCHIVE_OK);
#endif #endif
for (const auto &specification : entries) { for (const auto& specification : entries) {
Entry entry{archive_entry_new(), &archive_entry_free}; Entry entry{archive_entry_new(), &archive_entry_free};
const std::string entryPath{specification.path}; const std::string entryPath{specification.path};
archive_entry_set_pathname(entry.get(), entryPath.c_str()); archive_entry_set_pathname(entry.get(), entryPath.c_str());
archive_entry_set_filetype(entry.get(), specification.type); const unsigned int ae_type =
specification.type == FixtureEntryType::Directory
? AE_IFDIR
: (specification.type == FixtureEntryType::Symlink
? AE_IFLNK
: AE_IFREG);
archive_entry_set_filetype(entry.get(), ae_type);
archive_entry_set_perm( archive_entry_set_perm(
entry.get(), specification.type == AE_IFDIR ? 0755 : 0644); entry.get(),
if (specification.type == AE_IFREG) { specification.type == FixtureEntryType::Directory ? 0755 : 0644);
if (specification.type == FixtureEntryType::Regular) {
archive_entry_set_size( archive_entry_set_size(
entry.get(), entry.get(),
static_cast<la_int64_t>(specification.contents.size())); static_cast<la_int64_t>(specification.contents.size()));
@@ -78,18 +159,22 @@ namespace
ARCHIVE_OK); ARCHIVE_OK);
} }
Void::Testing::require(archive_write_close(writer.get()) == ARCHIVE_OK); Void::Testing::require(archive_write_close(writer.get()) == ARCHIVE_OK);
#else
write_raw_tar(path, entries);
#endif
} }
void write_archive(const std::filesystem::path &path, void write_archive(const std::filesystem::path& path,
std::string_view entryPath, std::string_view contents, std::string_view entryPath, std::string_view contents,
unsigned int type = AE_IFREG, std::string_view link = {}) FixtureEntryType type = FixtureEntryType::Regular,
std::string_view link = {})
{ {
const std::array entries{ArchiveEntry{entryPath, contents, type, link}}; const std::array entries{ArchiveEntry{entryPath, contents, type, link}};
write_archive(path, entries); write_archive(path, entries);
} }
[[nodiscard]] bool [[nodiscard]] bool
extraction_file_visible(const std::filesystem::path &destination) extraction_file_visible(const std::filesystem::path& destination)
{ {
std::error_code error; std::error_code error;
if (std::filesystem::exists(destination / "anchor", error)) { if (std::filesystem::exists(destination / "anchor", error)) {
@@ -129,8 +214,9 @@ Void::Testing::Test archive_accepts_explicit_directory_entries()
Void::FileSystem::TempDir temporary{"void_archive_"}; Void::FileSystem::TempDir temporary{"void_archive_"};
const auto source = temporary / "directory.tar.zst"; const auto source = temporary / "directory.tar.zst";
const auto destination = temporary / "output"; const auto destination = temporary / "output";
const std::array entries{ArchiveEntry{"bin/", {}, AE_IFDIR}, const std::array entries{
ArchiveEntry{"bin/tool", "payload"}}; ArchiveEntry{"bin/", {}, FixtureEntryType::Directory},
ArchiveEntry{"bin/tool", "payload"}};
write_archive(source, entries); write_archive(source, entries);
auto extracted = Void::Archive::extract(source, destination); auto extracted = Void::Archive::extract(source, destination);
@@ -154,7 +240,8 @@ Void::Testing::Test archive_rejects_traversal_and_links()
Void::Testing::expect( Void::Testing::expect(
!std::filesystem::exists(temporary.path() / "escape")); !std::filesystem::exists(temporary.path() / "escape"));
const auto symlink = temporary / "symlink.tar.zst"; const auto symlink = temporary / "symlink.tar.zst";
write_archive(symlink, "link", {}, AE_IFLNK, "/tmp/escape"); write_archive(symlink, "link", {}, FixtureEntryType::Symlink,
"/tmp/escape");
Void::Testing::expect( Void::Testing::expect(
!Void::Archive::extract(symlink, temporary / "out2").has_value()); !Void::Archive::extract(symlink, temporary / "out2").has_value());
const auto trailingFile = temporary / "trailing-file.tar.zst"; const auto trailingFile = temporary / "trailing-file.tar.zst";
+227 -16
View File
@@ -3,12 +3,16 @@
#include <Void/Testing/Assert.hpp> #include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp> #include <Void/Testing/Test.hpp>
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
#include <archive.h> #include <archive.h>
#include <archive_entry.h> #include <archive_entry.h>
#endif
#include <algorithm>
#include <array> #include <array>
#include <chrono> #include <chrono>
#include <cstddef> #include <cstddef>
#include <cstring>
#include <filesystem> #include <filesystem>
#include <fstream> #include <fstream>
#include <memory> #include <memory>
@@ -16,6 +20,8 @@
#include <string> #include <string>
#include <string_view> #include <string_view>
#include <sys/stat.h> #include <sys/stat.h>
#include <thread>
#include <tuple>
#include <vector> #include <vector>
namespace namespace
@@ -39,6 +45,72 @@ namespace
std::istreambuf_iterator<char>{}}; std::istreambuf_iterator<char>{}};
} }
void write_octal(std::span<std::byte> dst, std::uint64_t val)
{
dst.back() = std::byte{0};
std::size_t pos = dst.size() - 1;
while (pos > 0) {
--pos;
dst[pos] = static_cast<std::byte>('0' + (val & 7ULL));
val >>= 3ULL;
}
}
std::vector<std::byte> make_raw_tar_ustar(
std::span<const std::tuple<std::string_view, std::string_view, char,
std::string_view>>
entries)
{
std::vector<std::byte> out;
for (const auto& [path, content, typeflag, link] : entries) {
std::array<std::byte, 512> hdr{};
std::memcpy(hdr.data(), path.data(),
std::min<std::size_t>(path.size(), 100));
write_octal(std::span{hdr}.subspan(100, 8),
typeflag == '5' ? 0755ULL : 0644ULL);
write_octal(std::span{hdr}.subspan(108, 8), 0);
write_octal(std::span{hdr}.subspan(116, 8), 0);
const std::uint64_t sz = (typeflag == '0') ? content.size() : 0ULL;
write_octal(std::span{hdr}.subspan(124, 12), sz);
write_octal(std::span{hdr}.subspan(136, 12), 0);
std::fill(hdr.begin() + 148, hdr.begin() + 156, std::byte{' '});
hdr[156] = static_cast<std::byte>(typeflag);
if (!link.empty()) {
std::memcpy(hdr.data() + 157, link.data(),
std::min<std::size_t>(link.size(), 100));
}
std::memcpy(hdr.data() + 257, "ustar\0", 6);
hdr[263] = std::byte{'0'};
hdr[264] = std::byte{'0'};
std::uint32_t sum = 0;
for (const std::byte b : hdr) {
sum += static_cast<std::uint8_t>(b);
}
write_octal(std::span{hdr}.subspan(148, 7), sum);
hdr[155] = std::byte{' '};
out.insert(out.end(), hdr.begin(), hdr.end());
if (typeflag == '0' && !content.empty()) {
const auto cb =
std::as_bytes(std::span{content.data(), content.size()});
out.insert(out.end(), cb.begin(), cb.end());
const std::size_t rem = content.size() % 512U;
if (rem != 0) {
out.resize(out.size() + (512U - rem), std::byte{0});
}
}
}
out.resize(out.size() + 1024U, std::byte{0});
return out;
}
ArchiveCompression default_test_compression() noexcept
{
return has_libarchive_backend() ? ArchiveCompression::Zstd
: ArchiveCompression::None;
}
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
std::vector<std::byte> make_raw_tar( std::vector<std::byte> make_raw_tar(
std::span<const std::tuple<std::string_view, std::string_view, std::span<const std::tuple<std::string_view, std::string_view,
unsigned int, std::string_view>> unsigned int, std::string_view>>
@@ -95,6 +167,7 @@ namespace
Void::Testing::require(archive_write_close(writer.get()) == ARCHIVE_OK); Void::Testing::require(archive_write_close(writer.get()) == ARCHIVE_OK);
return out; return out;
} }
#endif
} // namespace } // namespace
Void::Testing::Test archive_reader_reproducible_skip_and_forensic_listing() Void::Testing::Test archive_reader_reproducible_skip_and_forensic_listing()
@@ -116,7 +189,7 @@ Void::Testing::Test archive_reader_reproducible_skip_and_forensic_listing()
VectorByteSink sink_a; VectorByteSink sink_a;
VectorByteSink sink_b; VectorByteSink sink_b;
CreationOptions copts{.compression = ArchiveCompression::Zstd, CreationOptions copts{.compression = default_test_compression(),
.reproducible = true}; .reproducible = true};
Void::Testing::require(create_archive(sink_a, order_a, copts).has_value()); Void::Testing::require(create_archive(sink_a, order_a, copts).has_value());
Void::Testing::require(create_archive(sink_b, order_b, copts).has_value()); Void::Testing::require(create_archive(sink_b, order_b, copts).has_value());
@@ -173,8 +246,26 @@ Void::Testing::Test archive_reader_reproducible_skip_and_forensic_listing()
Void::Testing::expect(zero_entries.validate().has_value()); Void::Testing::expect(zero_entries.validate().has_value());
} }
// 4. File-as-parent conflict rejected cleanly (both orderings). // 4. File-as-parent conflict rejected cleanly (pure USTAR works with and
// without LibArchive; additionally exercise zstd when LibArchive exists).
{ {
const std::array<
std::tuple<std::string_view, std::string_view, char,
std::string_view>,
2>
conflict_ustar{{
{"foo", "file-bytes", '0', ""},
{"foo/child", "nested", '0', ""},
}};
const auto raw_ustar = make_raw_tar_ustar(conflict_ustar);
SpanByteSource src{raw_ustar};
auto listed = list_entries(src, {}, false);
Void::Testing::require(!listed.has_value());
Void::Testing::expect_eq(
listed.error().code().value,
static_cast<std::int32_t>(ArchiveErrorCode::unsafe_entry));
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
const std::array< const std::array<
std::tuple<std::string_view, std::string_view, unsigned int, std::tuple<std::string_view, std::string_view, unsigned int,
std::string_view>, std::string_view>,
@@ -184,26 +275,27 @@ Void::Testing::Test archive_reader_reproducible_skip_and_forensic_listing()
{"foo/child", "nested", AE_IFREG, ""}, {"foo/child", "nested", AE_IFREG, ""},
}}; }};
const auto raw = make_raw_tar(conflict_entries); const auto raw = make_raw_tar(conflict_entries);
SpanByteSource src{raw}; SpanByteSource src_la{raw};
auto listed = list_entries(src, {}, false); auto listed_la = list_entries(src_la, {}, false);
Void::Testing::require(!listed.has_value()); Void::Testing::require(!listed_la.has_value());
Void::Testing::expect_eq( Void::Testing::expect_eq(
listed.error().code().value, listed_la.error().code().value,
static_cast<std::int32_t>(ArchiveErrorCode::unsafe_entry)); static_cast<std::int32_t>(ArchiveErrorCode::unsafe_entry));
#endif
} }
// 5. Normal vs forensic listing + sanitized diagnostics. // 5. Normal vs forensic listing + sanitized diagnostics.
{ {
const std::array< const std::array<
std::tuple<std::string_view, std::string_view, unsigned int, std::tuple<std::string_view, std::string_view, char,
std::string_view>, std::string_view>,
3> 3>
mixed{{ mixed_ustar{{
{"safe.txt", "ok", AE_IFREG, ""}, {"safe.txt", "ok", '0', ""},
{"bad\nlink", "", AE_IFLNK, "/etc/passwd"}, {"bad\nlink", "", '2', "/etc/passwd"},
{"../escape", "nope", AE_IFREG, ""}, {"../escape", "nope", '0', ""},
}}; }};
const auto raw = make_raw_tar(mixed); const auto raw = make_raw_tar_ustar(mixed_ustar);
SpanByteSource src1{raw}; SpanByteSource src1{raw};
Void::Testing::expect(!list_entries(src1, {}, false).has_value()); Void::Testing::expect(!list_entries(src1, {}, false).has_value());
@@ -226,10 +318,123 @@ Void::Testing::Test archive_reader_reproducible_skip_and_forensic_listing()
std::string{"a\\nb\\rc"}); std::string{"a\\nb\\rc"});
} }
Void::Testing::Test archive_create_formats_builtin_ustar_pax_and_gzip()
{
Void::FileSystem::TempDir tmp{"void_archive_formats_"};
// Built-in pure-C++ USTAR/PAX creation works regardless of LibArchive,
// handles long PAX paths (>120 bytes), custom canonical metadata, and
// produces byte-identical output across runs and entry permutations.
const std::string long_path =
"very/deep/nested/package/hierarchy/with/many/subdirectories/"
"extending/well/past/one/hundred/bytes/component/artifact.txt";
const std::array<CreateEntry, 3> entries_a{{
CreateEntry{.path = long_path,
.type = EntryType::RegularFile,
.executable = false,
.content = to_bytes("pax-long-path-content")},
CreateEntry{.path = "bin/tool",
.type = EntryType::RegularFile,
.executable = false,
.content = to_bytes("tool-bytes"),
.mode = 0755U},
CreateEntry{.path = "bin/", .type = EntryType::Directory},
}};
const std::array<CreateEntry, 3> entries_b{
entries_a[2], entries_a[0], entries_a[1]};
CreationOptions builtin_opts{
.compression = ArchiveCompression::None,
.reproducible = true,
.canonical_mtime = 1700000000,
.canonical_uid = 1000,
.canonical_gid = 1000,
.prefer_builtin_tar = true,
};
VectorByteSink raw1;
VectorByteSink raw2;
Void::Testing::require(create(raw1, entries_a, builtin_opts).has_value());
Void::Testing::require(create(raw2, entries_b, builtin_opts).has_value());
Void::Testing::expect_eq(raw1.bytes(), raw2.bytes());
const auto tar_file = tmp / "builtin.tar";
Void::Testing::require(create(tar_file, entries_a, builtin_opts).has_value());
auto extracted = extract(tar_file, tmp / "unpacked_tar");
Void::Testing::require(extracted.has_value());
Void::Testing::expect_eq(read_file_str(tmp / "unpacked_tar" / long_path),
std::string{"pax-long-path-content"});
Void::Testing::expect_eq(read_file_str(tmp / "unpacked_tar/bin/tool"),
std::string{"tool-bytes"});
struct stat st_tool{};
Void::Testing::require(::stat((tmp / "unpacked_tar/bin/tool").c_str(),
&st_tool) == 0);
Void::Testing::expect_eq(st_tool.st_mode & 0777, mode_t{0755});
// Staged extraction over built-in tar also succeeds (exercising
// LibArchive interop when LibArchive is linked, or built-in Reader when
// LibArchive is absent).
auto staged_tar = extract_staged(tar_file, tmp / "staged_tar");
Void::Testing::require(staged_tar.has_value());
auto pub_tar = staged_tar->publish("v1");
Void::Testing::require(pub_tar.has_value());
Void::Testing::expect_eq(
read_file_str(tmp / "staged_tar/v1" / long_path),
std::string{"pax-long-path-content"});
if (has_libarchive_backend()) {
CreationOptions gzip_opts{
.compression = ArchiveCompression::Gzip,
.reproducible = true,
.canonical_mtime = 1700000000,
};
VectorByteSink gz1;
VectorByteSink gz2;
Void::Testing::require(create(gz1, entries_a, gzip_opts).has_value());
std::this_thread::sleep_for(std::chrono::milliseconds{15});
Void::Testing::require(create(gz2, entries_b, gzip_opts).has_value());
Void::Testing::expect_eq(gz1.bytes(), gz2.bytes());
const auto gz_path = tmp / "bundle.tar.gz";
Void::Testing::require(
create(gz_path, entries_a, gzip_opts).has_value());
auto gz_ext = extract(gz_path, tmp / "unpacked_gz");
Void::Testing::require(gz_ext.has_value());
Void::Testing::expect_eq(read_file_str(tmp / "unpacked_gz" / long_path),
std::string{"pax-long-path-content"});
auto gz_staged = extract_staged(gz_path, tmp / "staged_gz");
Void::Testing::require(gz_staged.has_value());
Void::Testing::require(gz_staged->publish("v1").has_value());
Void::Testing::expect_eq(
read_file_str(tmp / "staged_gz/v1/bin/tool"),
std::string{"tool-bytes"});
} else {
VectorByteSink unused;
auto zst_err =
create(unused, entries_a,
CreationOptions{.compression = ArchiveCompression::Zstd});
Void::Testing::require(!zst_err.has_value());
Void::Testing::expect_eq(
zst_err.error().code().value,
static_cast<std::int32_t>(ArchiveErrorCode::unsupported_format));
auto gz_err =
create(unused, entries_a,
CreationOptions{.compression = ArchiveCompression::Gzip});
Void::Testing::require(!gz_err.has_value());
Void::Testing::expect_eq(
gz_err.error().code().value,
static_cast<std::int32_t>(ArchiveErrorCode::unsupported_format));
}
}
Void::Testing::Test archive_staged_extraction_atomic_publish_unknown_and_cleanup() Void::Testing::Test archive_staged_extraction_atomic_publish_unknown_and_cleanup()
{ {
Void::FileSystem::TempDir tmp{"void_archive_staged_"}; Void::FileSystem::TempDir tmp{"void_archive_staged_"};
const auto archive_path = tmp / "pkg.tar.zst"; const auto archive_path =
tmp / (has_libarchive_backend() ? "pkg.tar.zst" : "pkg.tar");
const auto parent_dir = tmp / "versions"; const auto parent_dir = tmp / "versions";
std::filesystem::create_directories(parent_dir); std::filesystem::create_directories(parent_dir);
@@ -243,7 +448,9 @@ Void::Testing::Test archive_staged_extraction_atomic_publish_unknown_and_cleanup
.executable = false, .executable = false,
.content = to_bytes("key=val")}, .content = to_bytes("key=val")},
}}; }};
Void::Testing::require(create_archive(archive_path, entries).has_value()); const CreationOptions create_opts{.compression = default_test_compression()};
Void::Testing::require(
create_archive(archive_path, entries, create_opts).has_value());
// 1. Staged extraction + atomic no-replace publication + safe modes. // 1. Staged extraction + atomic no-replace publication + safe modes.
std::size_t progress_calls = 0; std::size_t progress_calls = 0;
@@ -344,7 +551,8 @@ Void::Testing::Test archive_isolated_worker_extracts_verifies_and_publishes()
{ {
#ifdef VOID_ARCHIVE_WORKER_PATH #ifdef VOID_ARCHIVE_WORKER_PATH
Void::FileSystem::TempDir tmp{"void_archive_iso_"}; Void::FileSystem::TempDir tmp{"void_archive_iso_"};
const auto archive_path = tmp / "untrusted.tar.zst"; const auto archive_path =
tmp / (has_libarchive_backend() ? "untrusted.tar.zst" : "untrusted.tar");
const auto parent_dir = tmp / "out"; const auto parent_dir = tmp / "out";
std::filesystem::create_directories(parent_dir); std::filesystem::create_directories(parent_dir);
@@ -358,7 +566,10 @@ Void::Testing::Test archive_isolated_worker_extracts_verifies_and_publishes()
.executable = false, .executable = false,
.content = to_bytes("verified-by-parent")}, .content = to_bytes("verified-by-parent")},
}}; }};
Void::Testing::require(create_archive(archive_path, entries).has_value()); Void::Testing::require(
create_archive(archive_path, entries,
CreationOptions{.compression = default_test_compression()})
.has_value());
IsolationOptions iso{}; IsolationOptions iso{};
iso.worker_executable = VOID_ARCHIVE_WORKER_PATH; iso.worker_executable = VOID_ARCHIVE_WORKER_PATH;
@@ -187,3 +187,89 @@ Void::Testing::Test argparse_help_contains_names()
Void::Testing::expect(h.find("--output") != std::string::npos); Void::Testing::expect(h.find("--output") != std::string::npos);
Void::Testing::expect(h.find("A description.") != std::string::npos); Void::Testing::expect(h.find("A description.") != std::string::npos);
} }
Void::Testing::Test argparse_subcommands_option_many_and_distinct_outcomes()
{
bool verbose = false;
std::vector<std::string> targets;
std::vector<std::string> profiles;
std::string compdb_mode;
bool build_selected = false;
bool use_selected = false;
Parser root{"vbs", "Void Build System"};
root.flag("--verbose", "-v", "verbose output", verbose);
auto& build_cmd =
root.subcommand("build", "Build project", [&] { build_selected = true; });
build_cmd.option_many("--target", "-t", "targets", targets);
build_cmd.option_many("--profile", "-p", "profiles", profiles);
auto& compdb_cmd = root.subcommand("compdb", "Compile database commands");
auto& use_cmd =
compdb_cmd.subcommand("use", "Select compdb", [&] { use_selected = true; });
use_cmd.positional("mode", "compdb mode", compdb_mode);
// 1. Subcommand + repeatable option_many
{
const Args a{{"vbs", "-v", "build", "--target", "app", "--target=lib",
"-p", "debug", "--profile", "release"}};
const auto res = root.parse_detailed(a.argc, a.argv);
Void::Testing::require(res.ok());
Void::Testing::expect(verbose);
Void::Testing::expect(build_selected);
Void::Testing::expect(!use_selected);
Void::Testing::expect_eq(res.matched_command_path.size(), std::size_t{1});
Void::Testing::expect_eq(res.matched_command_path[0],
std::string{"build"});
Void::Testing::expect_eq(targets.size(), std::size_t{2});
Void::Testing::expect_eq(targets[0], std::string{"app"});
Void::Testing::expect_eq(targets[1], std::string{"lib"});
Void::Testing::expect_eq(profiles.size(), std::size_t{2});
Void::Testing::expect_eq(profiles[0], std::string{"debug"});
Void::Testing::expect_eq(profiles[1], std::string{"release"});
}
// 2. Nested subcommands ("vbs compdb use active")
{
build_selected = false;
use_selected = false;
const Args a{{"vbs", "compdb", "use", "active"}};
const auto res = root.parse_detailed(a.argc, a.argv);
Void::Testing::require(res.ok());
Void::Testing::expect(!build_selected);
Void::Testing::expect(use_selected);
Void::Testing::expect_eq(res.matched_command_path.size(), std::size_t{2});
Void::Testing::expect_eq(res.matched_command_path[0],
std::string{"compdb"});
Void::Testing::expect_eq(res.matched_command_path[1], std::string{"use"});
Void::Testing::expect_eq(compdb_mode, std::string{"active"});
}
// 3. Help is ParseOutcome::Help (distinct from ParseOutcome::Error)
{
const Args a{{"vbs", "--help"}};
const auto res = root.parse_detailed(a.argc, a.argv);
Void::Testing::expect(res.is_help());
Void::Testing::expect(!res.is_error());
Void::Testing::expect(res.message.find("Commands:") != std::string::npos);
const Args sub_help{{"vbs", "build", "--help"}};
const auto sres = root.parse_detailed(sub_help.argc, sub_help.argv);
Void::Testing::expect(sres.is_help());
Void::Testing::expect(sres.message.find("--target") != std::string::npos);
}
// 4. Missing or unknown subcommand is ParseOutcome::Error without running callbacks
{
build_selected = false;
const Args missing_sub{{"vbs"}};
const auto mres = root.parse_detailed(missing_sub.argc, missing_sub.argv);
Void::Testing::expect(mres.is_error());
const Args bad_sub{{"vbs", "unknowncmd"}};
const auto bres = root.parse_detailed(bad_sub.argc, bad_sub.argv);
Void::Testing::expect(bres.is_error());
Void::Testing::expect(!build_selected);
}
}
+153 -3
View File
@@ -6,6 +6,7 @@
#include <array> #include <array>
#include <fstream> #include <fstream>
#include <string>
namespace namespace
{ {
@@ -20,19 +21,122 @@ Void::Testing::Test crypto_known_hash_vectors()
auto sha1 = Void::Crypto::sha1("abc"); auto sha1 = Void::Crypto::sha1("abc");
auto sha256 = Void::Crypto::sha256("abc"); auto sha256 = Void::Crypto::sha256("abc");
auto sha512 = Void::Crypto::sha512("abc"); auto sha512 = Void::Crypto::sha512("abc");
auto b2_256 = Void::Crypto::blake2b256("abc");
auto b2_512 = Void::Crypto::blake2b512("abc");
Void::Testing::require(sha1.has_value()); Void::Testing::require(sha1.has_value());
Void::Testing::require(sha256.has_value()); Void::Testing::require(sha256.has_value());
Void::Testing::require(sha512.has_value()); Void::Testing::require(sha512.has_value());
Void::Testing::require(b2_256.has_value());
Void::Testing::require(b2_512.has_value());
Void::Testing::expect_eq( Void::Testing::expect_eq(
hex(*sha1), std::string{"a9993e364706816aba3e25717850c26c9cd0d89d"}); hex(*sha1), std::string{"a9993e364706816aba3e25717850c26c9cd0d89d"});
Void::Testing::expect_eq(hex(*sha256), Void::Testing::expect_eq(
std::string{"ba7816bf8f01cfea414140de5dae2223b0036" hex(*sha256),
"1a396177a9cb410ff61f20015ad"}); std::string{"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f"
"20015ad"});
Void::Testing::expect_eq( Void::Testing::expect_eq(
hex(*sha512), hex(*sha512),
std::string{ std::string{
"ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a21" "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a21"
"92992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"}); "92992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"});
Void::Testing::expect_eq(
hex(*b2_256),
std::string{"bddd813c634239723171ef3fee98579b94964e3bb1cb3e427262c8c06"
"8d52319"});
Void::Testing::expect_eq(
hex(*b2_512),
std::string{
"ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d"
"87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923"});
// NIST CAVP multi-block & empty vectors on built-in backend and OpenSSL
// backend (when available).
const Void::Crypto::ProviderOptions builtin_opts{.prefer_builtin = true};
const auto empty_bytes = std::span<const std::byte>{};
auto b_sha256_empty =
Void::Crypto::hash(Void::Crypto::HashAlgorithm::Sha256, empty_bytes,
builtin_opts);
Void::Testing::require(b_sha256_empty.has_value());
Void::Testing::expect_eq(
hex(*b_sha256_empty),
std::string{"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7"
"852b855"});
constexpr std::string_view k448 =
"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq";
auto b_sha256_448 = Void::Crypto::hash(
Void::Crypto::HashAlgorithm::Sha256,
std::as_bytes(std::span{k448.data(), k448.size()}), builtin_opts);
Void::Testing::require(b_sha256_448.has_value());
Void::Testing::expect_eq(
hex(*b_sha256_448),
std::string{"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd41"
"9db06c1"});
constexpr std::string_view k896 =
"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno"
"ijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu";
auto b_sha512_896 = Void::Crypto::hash(
Void::Crypto::HashAlgorithm::Sha512,
std::as_bytes(std::span{k896.data(), k896.size()}), builtin_opts);
Void::Testing::require(b_sha512_896.has_value());
Void::Testing::expect_eq(
hex(*b_sha512_896),
std::string{
"8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb688901850"
"1d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909"});
auto b_b2_256_empty =
Void::Crypto::hash(Void::Crypto::HashAlgorithm::Blake2b256, empty_bytes,
builtin_opts);
auto b_b2_512_empty =
Void::Crypto::hash(Void::Crypto::HashAlgorithm::Blake2b512, empty_bytes,
builtin_opts);
Void::Testing::require(b_b2_256_empty.has_value());
Void::Testing::require(b_b2_512_empty.has_value());
Void::Testing::expect_eq(
hex(*b_b2_256_empty),
std::string{"0e5751c026e543b2e8ab2eb06099daa1d1e5df47778f7787faab45cdf"
"12fe3a8"});
Void::Testing::expect_eq(
hex(*b_b2_512_empty),
std::string{
"786a02f742015903c6c6fd852552d272912f4740e15847618a86e217f71f5419d2"
"5e1031afee585313896444934eb04b903a685b1448b755d56f701afe9be2ce"});
// 1,000,000 x 'a' FIPS 180-4 SHA-256 test vector on built-in backend.
{
auto h = Void::Crypto::Hasher::create(Void::Crypto::HashAlgorithm::Sha256,
builtin_opts);
Void::Testing::require(h.has_value());
const std::string chunk(1000, 'a');
for (int i = 0; i < 1000; ++i) {
Void::Testing::require(h->update(chunk).has_value());
}
auto big = h->finalize();
Void::Testing::require(big.has_value());
Void::Testing::expect_eq(
hex(*big),
std::string{"cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39c"
"cc7112cd0"});
}
// Verify OpenSSL & built-in parity when OpenSSL is linked.
if (Void::Crypto::has_openssl_backend()) {
for (const auto alg : {Void::Crypto::HashAlgorithm::Sha1,
Void::Crypto::HashAlgorithm::Sha256,
Void::Crypto::HashAlgorithm::Sha512,
Void::Crypto::HashAlgorithm::Blake2b512}) {
auto d_ossl = Void::Crypto::hash(
alg, std::as_bytes(std::span{k896.data(), k896.size()}));
auto d_builtin = Void::Crypto::hash(
alg, std::as_bytes(std::span{k896.data(), k896.size()}),
builtin_opts);
Void::Testing::require(d_ossl.has_value());
Void::Testing::require(d_builtin.has_value());
Void::Testing::expect_eq(*d_ossl, *d_builtin);
}
}
} }
Void::Testing::Test crypto_streaming_and_file_hash_match() Void::Testing::Test crypto_streaming_and_file_hash_match()
@@ -50,8 +154,45 @@ Void::Testing::Test crypto_streaming_and_file_hash_match()
const auto path = temporary / "data"; const auto path = temporary / "data";
std::ofstream{path, std::ios::binary} << "abc"; std::ofstream{path, std::ios::binary} << "abc";
auto file = Void::Crypto::sha256File(path); auto file = Void::Crypto::sha256File(path);
auto file_snake = Void::Crypto::sha256_file(path);
Void::Testing::require(file.has_value()); Void::Testing::require(file.has_value());
Void::Testing::require(file_snake.has_value());
Void::Testing::expect_eq(*file, *streamed); Void::Testing::expect_eq(*file, *streamed);
Void::Testing::expect_eq(*file_snake, *streamed);
// Odd-size streaming checks across block boundaries for built-in SHA-256 &
// BLAKE2b (1, 7, 63, 64, 65, 127, 128, 129, 257).
const std::string sample(300, 'x');
const Void::Crypto::ProviderOptions builtin_opts{.prefer_builtin = true};
for (const auto alg : {Void::Crypto::HashAlgorithm::Sha256,
Void::Crypto::HashAlgorithm::Sha512,
Void::Crypto::HashAlgorithm::Blake2b256,
Void::Crypto::HashAlgorithm::Blake2b512}) {
auto one_shot = Void::Crypto::hash(
alg, std::as_bytes(std::span{sample.data(), sample.size()}),
builtin_opts);
Void::Testing::require(one_shot.has_value());
for (const std::size_t step : {1U, 7U, 63U, 64U, 65U, 127U, 128U, 129U}) {
auto sh = Void::Crypto::Hasher::create(alg, builtin_opts);
Void::Testing::require(sh.has_value());
for (std::size_t off = 0; off < sample.size(); off += step) {
const auto len = std::min(step, sample.size() - off);
Void::Testing::require(
sh->update(std::string_view{sample}.substr(off, len))
.has_value());
}
auto fin = sh->finalize();
Void::Testing::require(fin.has_value());
Void::Testing::expect_eq(*fin, *one_shot);
}
}
auto b2_256_f = Void::Crypto::blake2b256_file(path);
auto b2_512_f = Void::Crypto::blake2b512_file(path);
Void::Testing::require(b2_256_f.has_value());
Void::Testing::require(b2_512_f.has_value());
Void::Testing::expect_eq(*b2_256_f, *Void::Crypto::blake2b256("abc"));
Void::Testing::expect_eq(*b2_512_f, *Void::Crypto::blake2b512("abc"));
} }
Void::Testing::Test crypto_ed25519_rfc8032_vector() Void::Testing::Test crypto_ed25519_rfc8032_vector()
@@ -67,6 +208,15 @@ Void::Testing::Test crypto_ed25519_rfc8032_vector()
std::as_bytes(std::span{publicText->data(), publicText->size()}); std::as_bytes(std::span{publicText->data(), publicText->size()});
const auto signature = const auto signature =
std::as_bytes(std::span{signatureText->data(), signatureText->size()}); std::as_bytes(std::span{signatureText->data(), signatureText->size()});
if (!Void::Crypto::has_openssl_backend()) {
auto unavail = Void::Crypto::verifyEd25519({}, signature, publicKey);
Void::Testing::require(!unavail.has_value());
Void::Testing::expect_eq(
unavail.error().code().value,
static_cast<std::int32_t>(
Void::Crypto::CryptoErrorCode::unsupported_algorithm));
return;
}
auto valid = Void::Crypto::verifyEd25519({}, signature, publicKey); auto valid = Void::Crypto::verifyEd25519({}, signature, publicKey);
Void::Testing::require(valid.has_value()); Void::Testing::require(valid.has_value());
Void::Testing::expect(*valid); Void::Testing::expect(*valid);
@@ -123,6 +123,35 @@ Void::Testing::Test crypto_ed25519_signing_vectors_and_boundaries()
{ {
using namespace Void::Crypto; using namespace Void::Crypto;
if (!has_openssl_backend()) {
auto gen_unavail = Ed25519PrivateKey::generate();
Void::Testing::require(!gen_unavail.has_value());
Void::Testing::expect_eq(
gen_unavail.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::unsupported_algorithm));
const std::array<std::byte, Ed25519PublicKeySize> dummy_pub{};
const std::array<std::byte, Ed25519SignatureSize> dummy_sig{};
for (const std::size_t bad_key_len : {0U, 1U, 31U, 33U, 64U}) {
std::vector<std::byte> bad_key(bad_key_len, std::byte{0x11});
auto r = verifyEd25519({}, dummy_sig, bad_key);
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(
r.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::invalid_key_size));
}
for (const std::size_t bad_sig_len : {0U, 1U, 63U, 65U}) {
std::vector<std::byte> bad_sig(bad_sig_len, std::byte{0x22});
auto r = verifyEd25519({}, bad_sig, dummy_pub);
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(
r.error().code().value,
static_cast<std::int32_t>(
CryptoErrorCode::invalid_signature_size));
}
return;
}
struct Rfc8032Vector { struct Rfc8032Vector {
std::string_view seed_hex; std::string_view seed_hex;
std::string_view pub_hex; std::string_view pub_hex;
@@ -357,6 +386,30 @@ Void::Testing::Test crypto_hmac_sha256_and_hkdf_sha256_vectors_and_guards()
[](std::byte b) { return b == std::byte{0x00}; })); [](std::byte b) { return b == std::byte{0x00}; }));
} }
// Also verify built-in HMAC-SHA-256 and HKDF-SHA-256 produce identical
// outputs without OpenSSL.
{
const ProviderOptions builtin_opts{.prefer_builtin = true};
const std::vector<std::byte> key(20, std::byte{0x0b});
auto mac = hmac_sha256(key, as_bytes("Hi There"), builtin_opts);
Void::Testing::require(mac.has_value());
Void::Testing::expect_eq(
to_hex(*mac),
std::string{"b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e93"
"76c2e32cff7"});
const std::vector<std::byte> ikm(22, std::byte{0x0b});
const auto salt = from_hex("000102030405060708090a0b0c");
const auto info = from_hex("f0f1f2f3f4f5f6f7f8f9");
std::array<std::byte, 42> okm{};
auto r = hkdf_sha256(ikm, salt, info, okm, builtin_opts);
Void::Testing::require(r.has_value());
Void::Testing::expect_eq(
to_hex(okm),
std::string{"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02"
"d56ecc4c5bf34007208d5b887185865"});
}
// constant_time_equal checks // constant_time_equal checks
const auto a = from_hex("01020304"); const auto a = from_hex("01020304");
const auto b = from_hex("01020304"); const auto b = from_hex("01020304");
+66
View File
@@ -152,3 +152,69 @@ Void::Testing::Test strict_json_decodes_valid_unicode_pairs()
Void::Testing::expect( Void::Testing::expect(
!Void::Json::Strict::parse(R"("\uD83D")").has_value()); !Void::Json::Strict::parse(R"("\uD83D")").has_value());
} }
Void::Testing::Test strict_json_validates_utf8_in_parse_and_serialize()
{
// Valid 1, 2, 3, and 4-byte scalars including boundaries U+D7FF, U+E000, U+10FFFF
const std::string valid_json =
std::string{R"({"ascii":"hello","latin":")"} + "\xC3\xA9" +
R"(","euro":")" + "\xE2\x82\xAC" + R"(","emoji":")" +
"\xF0\x9F\x98\x80" + R"(","hi_bmp":")" + "\xED\x9F\xBF" +
R"(","priv":")" + "\xEE\x80\x80" + R"(","max_cp":")" +
"\xF4\x8F\xBF\xBF" + R"("})";
const auto parsed = Void::Json::Strict::parse(valid_json);
Void::Testing::require(parsed.has_value());
const auto serialized = Void::Json::Strict::serialize(*parsed);
Void::Testing::require(serialized.has_value());
const auto reparsed = Void::Json::Strict::parse(*serialized);
Void::Testing::require(reparsed.has_value());
// Invalid UTF-8 sequences in string values and object keys
const std::array<std::string, 10> invalid_payloads{
std::string{"\"\xFF\""}, // invalid lead 0xFF
std::string{"\"\x80\""}, // stray continuation byte
std::string{"\"\xBF\""}, // stray continuation byte
std::string{"\"\xC0\xAF\""}, // overlong 2-byte '/'
std::string{"\"\xC1\x81\""}, // overlong 2-byte 'A'
std::string{"\"\xE0\x9F\x80\""}, // overlong 3-byte
std::string{"\"\xED\xA0\x80\""}, // UTF-8 encoded U+D800
std::string{"\"\xED\xBF\xBF\""}, // UTF-8 encoded U+DFFF
std::string{"\"\xF4\x90\x80\x80\""}, // > U+10FFFF (U+110000)
std::string{"{\"\xFF\":\"val\"}"}, // invalid UTF-8 in object key
};
for (const auto& payload : invalid_payloads) {
const auto res = Void::Json::Strict::parse(payload);
Void::Testing::expect(!res.has_value());
Void::Testing::expect(!Void::Json::Strict::is_valid_utf8(payload));
}
// Truncated multi-byte sequences inside strings
Void::Testing::expect(
!Void::Json::Strict::parse(std::string{"\"\xC3\""}).has_value());
Void::Testing::expect(
!Void::Json::Strict::parse(std::string{"\"\xF0\x9F\x98\""})
.has_value());
// Serialization must also reject corrupt UTF-8 in Values or keys
const Void::Json::Strict::Value bad_val{std::string{"ok\xED\xA0\x80"}};
Void::Testing::expect(
!Void::Json::Strict::serialize(bad_val).has_value());
Void::Json::Strict::Value::Object bad_key_obj;
bad_key_obj.emplace(std::string{"bad\xFFkey"},
Void::Json::Strict::Value{1});
Void::Testing::expect(
!Void::Json::Strict::serialize(
Void::Json::Strict::Value{std::move(bad_key_obj)})
.has_value());
// Control char escaping & round-trip in serialize()
const Void::Json::Strict::Value ctrl{std::string{"a\nb\tc\x01\"\\"}};
const auto escaped = Void::Json::Strict::serialize(ctrl);
Void::Testing::require(escaped.has_value());
const auto ctrl_back = Void::Json::Strict::parse(*escaped);
Void::Testing::require(ctrl_back.has_value());
Void::Testing::expect_eq(std::get<std::string>(ctrl_back->value),
std::string{"a\nb\tc\x01\"\\"});
}
+235
View File
@@ -0,0 +1,235 @@
#include <Void/Data/Toml.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <cmath>
#include <cstdint>
#include <limits>
#include <string>
Void::Testing::Test toml_parses_scalars_multilines_and_numbers()
{
constexpr std::string_view kDoc = R"toml(
# Comment line
title = "Void Build"
literal_win = 'C:\Users\Void'
multi_basic = """
Hello \
world ""escaped"" \u0041 \U0001F600!"""
multi_quotes = """here are two ""quotes"" and two at end "" """
five_quotes = """say """""
multi_lit = '''
line1\nraw
line2 'ok' ''ok''
'''
flag_t = true
flag_f = false
dec_pos = +42
dec_neg = -1_000_000
hex_num = 0xDEAD_BEEF
oct_num = 0o755
bin_num = 0b1101_0110
min_i64 = -9223372036854775808
max_i64 = 9223372036854775807
flt = -1.25e+2
flt_zero = 0.0
inf_pos = +inf
inf_neg = -inf
not_a_num = nan
)toml";
const auto parsed = Void::Data::Toml::parse(kDoc);
Void::Testing::require(parsed.has_value());
const auto& root = parsed->root;
Void::Testing::require(root.find("title") != nullptr);
Void::Testing::expect_eq(
*root.find("title")->as_string(), std::string{"Void Build"});
Void::Testing::expect(root.find("title")->origin.line >= 3U);
Void::Testing::expect_eq(
*root.find("literal_win")->as_string(), std::string{R"(C:\Users\Void)"});
Void::Testing::expect_eq(
*root.find("multi_basic")->as_string(),
std::string{"Hello world \"\"escaped\"\" A \xF0\x9F\x98\x80!"});
Void::Testing::expect_eq(
*root.find("five_quotes")->as_string(), std::string{"say \"\""});
Void::Testing::expect_eq(
*root.find("multi_lit")->as_string(),
std::string{"line1\\nraw\nline2 'ok' ''ok''\n"});
Void::Testing::expect_eq(*root.find("flag_t")->as_bool(), true);
Void::Testing::expect_eq(*root.find("flag_f")->as_bool(), false);
Void::Testing::expect_eq(*root.find("dec_pos")->as_integer(),
std::int64_t{42});
Void::Testing::expect_eq(*root.find("dec_neg")->as_integer(),
std::int64_t{-1000000});
Void::Testing::expect_eq(*root.find("hex_num")->as_integer(),
std::int64_t{0xDEADBEEFLL});
Void::Testing::expect_eq(*root.find("oct_num")->as_integer(),
std::int64_t{0755});
Void::Testing::expect_eq(*root.find("bin_num")->as_integer(),
std::int64_t{0b11010110});
Void::Testing::expect_eq(*root.find("min_i64")->as_integer(),
std::numeric_limits<std::int64_t>::min());
Void::Testing::expect_eq(*root.find("max_i64")->as_integer(),
std::numeric_limits<std::int64_t>::max());
Void::Testing::expect_eq(*root.find("flt")->as_float(), -125.0);
Void::Testing::expect_eq(*root.find("flt_zero")->as_float(), 0.0);
Void::Testing::expect(std::isinf(*root.find("inf_pos")->as_float()) &&
*root.find("inf_pos")->as_float() > 0.0);
Void::Testing::expect(std::isinf(*root.find("inf_neg")->as_float()) &&
*root.find("inf_neg")->as_float() < 0.0);
Void::Testing::expect(std::isnan(*root.find("not_a_num")->as_float()));
}
Void::Testing::Test toml_parses_datetimes_tables_inline_and_arrays_of_tables()
{
constexpr std::string_view kDoc = R"toml(
odt_utc = 1979-05-27T07:32:00Z
odt_space = 1979-05-27 07:32:00.123456-07:00
ldt = 2000-02-29T12:00:00
ld = 2026-11-26
lt = 08:15:30.5
name.first = "Ada"
name."last.part" = "Lovelace"
inline_pt = { x = 1, y = 2, nested.z = "ok" }
arr = [
1,
"two", # comment inside array
{ k = true },
]
[server]
host = "127.0.0.1"
ports = [8080, 8443]
[server.tls]
enabled = true
[[products]]
name = "Hammer"
sku = 738594937
[[products]] # empty entry in middle is allowed
[[products]]
name = "Nail"
sku = 284758393
color = ["gray", "steel"]
[products.meta]
origin = "local"
)toml";
const auto parsed = Void::Data::Toml::parse(kDoc);
Void::Testing::require(parsed.has_value());
const auto& root = parsed->root;
const auto* odt = root.find("odt_utc")->as_datetime();
Void::Testing::require(odt != nullptr);
Void::Testing::expect_eq(odt->to_string(),
std::string{"1979-05-27T07:32:00Z"});
const auto* odt2 = root.find("odt_space")->as_datetime();
Void::Testing::require(odt2 != nullptr);
Void::Testing::expect_eq(
odt2->to_string(), std::string{"1979-05-27T07:32:00.123456-07:00"});
const auto* ldt = root.find("ldt")->as_datetime();
Void::Testing::require(ldt != nullptr);
Void::Testing::expect_eq(ldt->date.year, 2000);
Void::Testing::expect_eq(ldt->date.month, 2);
Void::Testing::expect_eq(ldt->date.day, 29);
const auto* name_tbl = root.find("name")->as_table();
Void::Testing::require(name_tbl != nullptr);
Void::Testing::expect_eq(*name_tbl->find("first")->as_string(),
std::string{"Ada"});
Void::Testing::expect_eq(*name_tbl->find("last.part")->as_string(),
std::string{"Lovelace"});
const auto* inline_pt = root.find("inline_pt")->as_table();
Void::Testing::require(inline_pt != nullptr);
Void::Testing::expect(inline_pt->is_inline);
Void::Testing::expect_eq(*inline_pt->find("x")->as_integer(),
std::int64_t{1});
Void::Testing::expect_eq(
*inline_pt->find("nested")->as_table()->find("z")->as_string(),
std::string{"ok"});
const auto* aot = root.find("products")->as_array_of_tables();
Void::Testing::require(aot != nullptr);
Void::Testing::expect_eq(aot->tables.size(), std::size_t{3});
Void::Testing::expect_eq(*aot->tables[0].find("name")->as_string(),
std::string{"Hammer"});
Void::Testing::expect(aot->tables[1].empty());
Void::Testing::expect_eq(*aot->tables[2].find("name")->as_string(),
std::string{"Nail"});
Void::Testing::expect_eq(
*aot->tables[2].find("meta")->as_table()->find("origin")->as_string(),
std::string{"local"});
// Deterministic canonical serialize & round-trip idempotence
const std::string out1 = Void::Data::Toml::serialize(*parsed);
const auto reparsed = Void::Data::Toml::parse(out1);
Void::Testing::require(reparsed.has_value());
const std::string out2 = Void::Data::Toml::serialize(*reparsed);
Void::Testing::expect_eq(out1, out2);
}
Void::Testing::Test toml_reports_exact_origin_and_rejects_errors()
{
// Line 1: ok, Line 2: ok, Line 3: duplicate key starts at col 1
constexpr std::string_view kDupKey = "a = 1\nb = 2\na = 3\n";
const auto e1 = Void::Data::Toml::parse(kDupKey);
Void::Testing::require(!e1.has_value());
Void::Testing::expect_eq(e1.error().origin.line, std::size_t{3});
Void::Testing::expect_eq(e1.error().origin.column, std::size_t{1});
// Duplicate [table]
constexpr std::string_view kDupTable = "[pkg]\nname = \"x\"\n\n[pkg]\n";
const auto e2 = Void::Data::Toml::parse(kDupTable);
Void::Testing::require(!e2.has_value());
Void::Testing::expect_eq(e2.error().origin.line, std::size_t{4});
// Defining explicit [table] after dotted key
const auto e3 = Void::Data::Toml::parse("a.b = 1\n[a]\n");
Void::Testing::expect(!e3.has_value());
// Extending inline table
const auto e4 = Void::Data::Toml::parse("t = { a = 1 }\nt.b = 2\n");
Void::Testing::expect(!e4.has_value());
// Multiline inline table forbidden in TOML 1.0
const auto e5 = Void::Data::Toml::parse("t = {\n a = 1\n}\n");
Void::Testing::expect(!e5.has_value());
// Trailing comma in inline table forbidden in TOML 1.0
const auto e6 = Void::Data::Toml::parse("t = { a = 1, }\n");
Void::Testing::expect(!e6.has_value());
// Invalid calendar date (non-leap year 1900-02-29)
const auto e7 = Void::Data::Toml::parse("d = 1900-02-29\n");
Void::Testing::expect(!e7.has_value());
// Invalid 6-quote basic string close
const auto e8 = Void::Data::Toml::parse("s = \"\"\"hello\"\"\"\"\"\"\n");
Void::Testing::expect(!e8.has_value());
// Invalid UTF-8 byte
const auto e9 = Void::Data::Toml::parse(std::string{"s = \"\xFF\"\n"});
Void::Testing::expect(!e9.has_value());
// Subtable before parent table IS valid per TOML 1.0
const auto super_after =
Void::Data::Toml::parse("[a.b]\nx = 1\n[a]\ny = 2\n");
Void::Testing::require(super_after.has_value());
Void::Testing::expect_eq(
*super_after->root.find("a")->as_table()->find("y")->as_integer(),
std::int64_t{2});
}
+360 -10
View File
@@ -1,19 +1,34 @@
#include <Void/Crypto/Crypto.hpp>
#include <Void/Net/Http.hpp> #include <Void/Net/Http.hpp>
#include <Void/Net/HttpServer.hpp>
#include <Void/System/TempDir.hpp>
#include <Void/Testing/Assert.hpp> #include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp> #include <Void/Testing/Test.hpp>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/ssl.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <arpa/inet.h>
#include <atomic> #include <atomic>
#include <filesystem>
#include <fstream>
#include <netinet/in.h> #include <netinet/in.h>
#include <stop_token>
#include <string> #include <string>
#include <sys/socket.h> #include <sys/socket.h>
#include <thread> #include <thread>
#include <unistd.h> #include <unistd.h>
#include <vector>
namespace namespace
{ {
// Minimal one-shot HTTP/1.1 server on a chosen loopback port. Accepts one // Minimal one-shot HTTP/1.1 server on a chosen loopback port. Accepts one
// connection, reads the request (ignored beyond headers), and replies with // connection, reads the request (ignored beyond headers), and replies with
// a fixed 200 body. Runs on a detached helper thread; the test joins it. // a fixed 200 body.
struct OneShotServer { struct OneShotServer {
int fd = -1; int fd = -1;
std::uint16_t port = 0; std::uint16_t port = 0;
@@ -29,7 +44,7 @@ namespace
sockaddr_in addr{}; sockaddr_in addr{};
addr.sin_family = AF_INET; addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr.sin_port = 0; // ephemeral addr.sin_port = 0;
::bind(fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)); ::bind(fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr));
socklen_t len = sizeof(addr); socklen_t len = sizeof(addr);
::getsockname(fd, reinterpret_cast<sockaddr*>(&addr), &len); ::getsockname(fd, reinterpret_cast<sockaddr*>(&addr), &len);
@@ -59,6 +74,126 @@ namespace
if (fd >= 0) ::close(fd); if (fd >= 0) ::close(fd);
} }
}; };
struct GeneratedCert {
std::filesystem::path cert_file;
std::filesystem::path key_file;
};
GeneratedCert generate_self_signed_cert(const std::filesystem::path& dir,
const char* san_value,
const char* tag)
{
using PkeyPtr = std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)>;
using X509Ptr = std::unique_ptr<X509, decltype(&X509_free)>;
using ExtPtr =
std::unique_ptr<X509_EXTENSION, decltype(&X509_EXTENSION_free)>;
PkeyPtr pkey{EVP_RSA_gen(2048), &EVP_PKEY_free};
Void::Testing::require(static_cast<bool>(pkey));
X509Ptr cert{X509_new(), &X509_free};
Void::Testing::require(static_cast<bool>(cert));
X509_set_version(cert.get(), 2);
ASN1_INTEGER_set(X509_get_serialNumber(cert.get()), 1);
X509_gmtime_adj(X509_get_notBefore(cert.get()), -60);
X509_gmtime_adj(X509_get_notAfter(cert.get()), 3600);
X509_set_pubkey(cert.get(), pkey.get());
X509_NAME* name = X509_get_subject_name(cert.get());
X509_NAME_add_entry_by_txt(
name, "CN", MBSTRING_ASC,
reinterpret_cast<const unsigned char*>("127.0.0.1"), -1, -1, 0);
X509_set_issuer_name(cert.get(), name);
X509V3_CTX ctx{};
X509V3_set_ctx_nodb(&ctx);
X509V3_set_ctx(&ctx, cert.get(), cert.get(), nullptr, nullptr, 0);
ExtPtr ext{X509V3_EXT_conf_nid(nullptr, &ctx, NID_subject_alt_name,
const_cast<char*>(san_value)),
&X509_EXTENSION_free};
Void::Testing::require(static_cast<bool>(ext));
Void::Testing::require(X509_add_ext(cert.get(), ext.get(), -1) == 1);
Void::Testing::require(
X509_sign(cert.get(), pkey.get(), EVP_sha256()) > 0);
const auto cert_path = dir / (std::string{"cert_"} + tag + ".pem");
const auto key_path = dir / (std::string{"key_"} + tag + ".pem");
FILE* cf = std::fopen(cert_path.c_str(), "wb");
Void::Testing::require(cf != nullptr);
Void::Testing::require(PEM_write_X509(cf, cert.get()) == 1);
std::fclose(cf);
FILE* kf = std::fopen(key_path.c_str(), "wb");
Void::Testing::require(kf != nullptr);
Void::Testing::require(PEM_write_PrivateKey(kf, pkey.get(), nullptr,
nullptr, 0, nullptr,
nullptr) == 1);
std::fclose(kf);
return GeneratedCert{cert_path, key_path};
}
struct OneShotTlsServer {
int fd = -1;
std::uint16_t port = 0;
SSL_CTX* ctx = nullptr;
std::thread worker;
OneShotTlsServer(const GeneratedCert& creds, std::string body)
{
ctx = SSL_CTX_new(TLS_server_method());
Void::Testing::require(ctx != nullptr);
Void::Testing::require(
SSL_CTX_use_certificate_file(ctx, creds.cert_file.c_str(),
SSL_FILETYPE_PEM) == 1);
Void::Testing::require(
SSL_CTX_use_PrivateKey_file(ctx, creds.key_file.c_str(),
SSL_FILETYPE_PEM) == 1);
fd = ::socket(AF_INET, SOCK_STREAM, 0);
int yes = 1;
::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr.sin_port = 0;
Void::Testing::require(
::bind(fd, reinterpret_cast<sockaddr*>(&addr),
sizeof(addr)) == 0);
socklen_t len = sizeof(addr);
::getsockname(fd, reinterpret_cast<sockaddr*>(&addr), &len);
port = ntohs(addr.sin_port);
Void::Testing::require(::listen(fd, 1) == 0);
worker = std::thread([this, body = std::move(body)]() {
const int conn = ::accept(fd, nullptr, nullptr);
if (conn < 0) return;
SSL* ssl = SSL_new(ctx);
SSL_set_fd(ssl, conn);
if (SSL_accept(ssl) == 1) {
char buf[2048];
(void)SSL_read(ssl, buf, sizeof(buf));
const std::string resp =
"HTTP/1.1 200 OK\r\nContent-Length: " +
std::to_string(body.size()) +
"\r\nConnection: close\r\n\r\n" + body;
(void)SSL_write(ssl, resp.data(),
static_cast<int>(resp.size()));
SSL_shutdown(ssl);
}
SSL_free(ssl);
::close(conn);
});
}
~OneShotTlsServer()
{
if (worker.joinable()) worker.join();
if (fd >= 0) ::close(fd);
if (ctx != nullptr) SSL_CTX_free(ctx);
}
};
} // namespace } // namespace
Void::Testing::Test http_client_get_localhost_round_trip() Void::Testing::Test http_client_get_localhost_round_trip()
@@ -74,7 +209,6 @@ Void::Testing::Test http_client_get_localhost_round_trip()
Void::Testing::expect_eq(resp->status, static_cast<std::uint16_t>(200)); Void::Testing::expect_eq(resp->status, static_cast<std::uint16_t>(200));
Void::Testing::expect_eq(resp->body, std::string{"hello from void"}); Void::Testing::expect_eq(resp->body, std::string{"hello from void"});
Void::Testing::expect(resp->ok()); Void::Testing::expect(resp->ok());
// Request line reached the server with the right target.
Void::Testing::expect(server.last_request.find("GET /ping HTTP/1.1") != Void::Testing::expect(server.last_request.find("GET /ping HTTP/1.1") !=
std::string::npos); std::string::npos);
} }
@@ -106,16 +240,12 @@ Void::Testing::Test http_client_invalid_url_is_error()
Void::Testing::Test http_client_connection_refused_is_error() Void::Testing::Test http_client_connection_refused_is_error()
{ {
Void::Net::HttpClient client; Void::Net::HttpClient client;
// Port 1 on loopback: nothing listening.
const auto resp = client.get("http://127.0.0.1:1/"); const auto resp = client.get("http://127.0.0.1:1/");
Void::Testing::expect(!resp.has_value()); Void::Testing::expect(!resp.has_value());
} }
Void::Testing::Test http_client_timeout_bounds_a_stalled_server() Void::Testing::Test http_client_timeout_bounds_a_stalled_server()
{ {
// A server that accepts and then never responds. Without an enforced
// Request::timeout the sync read blocks forever (Asio's sync emulation
// poll()s on would-block with no deadline).
struct StallServer { struct StallServer {
int fd = -1; int fd = -1;
std::uint16_t port = 0; std::uint16_t port = 0;
@@ -138,14 +268,14 @@ Void::Testing::Test http_client_timeout_bounds_a_stalled_server()
::listen(fd, 1); ::listen(fd, 1);
worker = std::thread([this] { worker = std::thread([this] {
conn = ::accept(fd, nullptr, nullptr); conn = ::accept(fd, nullptr, nullptr);
// Never write a byte; hold the connection open.
}); });
} }
~StallServer() ~StallServer()
{ {
if (conn >= 0) ::close(conn); if (fd >= 0) ::shutdown(fd, SHUT_RDWR);
if (worker.joinable()) worker.join(); if (worker.joinable()) worker.join();
if (conn >= 0) ::close(conn);
if (fd >= 0) ::close(fd); if (fd >= 0) ::close(fd);
} }
}; };
@@ -161,6 +291,226 @@ Void::Testing::Test http_client_timeout_bounds_a_stalled_server()
const auto elapsed = std::chrono::steady_clock::now() - start; const auto elapsed = std::chrono::steady_clock::now() - start;
Void::Testing::expect(!resp.has_value()); Void::Testing::expect(!resp.has_value());
// Well under the old "forever": the deadline tripped around 1s.
Void::Testing::expect(elapsed < std::chrono::seconds{5}); Void::Testing::expect(elapsed < std::chrono::seconds{5});
} }
Void::Testing::Test http_client_streaming_upload_download_quota_and_cancel()
{
Void::FileSystem::TempDir tmp{"void_http_stream_"};
const auto upload_src = tmp / "upload_4mib.bin";
const auto server_stored = tmp / "server_copy.bin";
const auto dl_dst = tmp / "downloaded.bin";
const auto dl_quota_fail = tmp / "should_not_exist.bin";
// Generate deterministic 4 MiB test file.
constexpr std::size_t kSize = 4ULL * 1024ULL * 1024ULL;
std::string expected_data(kSize, '\0');
for (std::size_t i = 0; i < kSize; ++i) {
expected_data[i] = static_cast<char>((i * 131U) & 0xFFU);
}
{
std::ofstream out{upload_src, std::ios::binary | std::ios::trunc};
Void::Testing::require(out.is_open());
out.write(expected_data.data(),
static_cast<std::streamsize>(expected_data.size()));
out.close();
}
auto expected_digest = Void::Crypto::sha256_file(upload_src);
Void::Testing::require(expected_digest.has_value());
Void::Net::HttpServer server;
Void::Testing::require(
server
.add_streaming_route(
Void::Net::Method::Put, "/blob",
[&](const Void::Net::ServerRequest&,
Void::Net::BodyReader& reader) -> Void::Net::RouteResult {
auto n = reader.read_to_file(server_stored);
if (!n.has_value()) {
return std::unexpected{std::move(n.error())};
}
return Void::Net::ServerResponse{
.status = 201, .body = std::to_string(*n)};
})
.has_value());
Void::Testing::require(
server
.add_route(Void::Net::Method::Get, "/blob",
[&](const Void::Net::ServerRequest&) {
return Void::Result::ok(
Void::Net::ServerResponse::from_file(
server_stored));
})
.has_value());
std::atomic<bool> slow_entered{false};
std::atomic<bool> release_hang{false};
Void::Testing::require(
server
.add_route(Void::Net::Method::Get, "/hang",
[&](const Void::Net::ServerRequest&) {
slow_entered.store(true, std::memory_order_release);
for (int i = 0;
i < 600 &&
!release_hang.load(std::memory_order_acquire);
++i) {
std::this_thread::sleep_for(
std::chrono::milliseconds{5});
}
return Void::Result::ok(
Void::Net::ServerResponse{.status = 200,
.body = "late"});
})
.has_value());
Void::Testing::require(server.start().has_value());
const std::string base = server.base_url();
auto client = Void::Net::HttpClient::secure();
Void::Testing::expect(client.verify_tls());
// 1. Streaming 4 MiB upload with progress callback.
std::uint64_t last_up = 0;
std::size_t up_callbacks = 0;
Void::Net::UploadOptions up_opts;
up_opts.on_progress = [&](const Void::Net::TransferProgress& p) {
Void::Testing::expect(p.bytes_transferred >= last_up);
last_up = p.bytes_transferred;
++up_callbacks;
};
auto up_res = client.upload_file(base + "/blob", upload_src, up_opts);
Void::Testing::require(up_res.has_value());
Void::Testing::expect_eq(up_res->status, std::uint16_t{201});
Void::Testing::expect_eq(last_up, static_cast<std::uint64_t>(kSize));
Void::Testing::expect(up_callbacks > 1U);
// 2. Streaming 4 MiB download with on_chunk incremental SHA-256 verification.
auto chunk_hasher =
Void::Crypto::Hasher::create(Void::Crypto::HashAlgorithm::Sha256);
Void::Testing::require(chunk_hasher.has_value());
std::uint64_t last_dn = 0;
Void::Net::DownloadOptions dl_opts;
dl_opts.max_bytes = kSize;
dl_opts.on_chunk = [&](std::span<const std::byte> data) {
Void::Testing::require(chunk_hasher->update(data).has_value());
};
dl_opts.on_progress = [&](const Void::Net::TransferProgress& p) {
Void::Testing::expect(p.bytes_transferred >= last_dn);
last_dn = p.bytes_transferred;
};
auto dl_res = client.download_to_file(base + "/blob", dl_dst, dl_opts);
Void::Testing::require(dl_res.has_value());
Void::Testing::expect_eq(dl_res->status, std::uint16_t{200});
Void::Testing::expect_eq(dl_res->bytes_written,
static_cast<std::uint64_t>(kSize));
auto streamed_digest = chunk_hasher->finalize();
Void::Testing::require(streamed_digest.has_value());
Void::Testing::expect_eq(*streamed_digest, *expected_digest);
auto file_digest = Void::Crypto::sha256_file(dl_dst);
Void::Testing::require(file_digest.has_value());
Void::Testing::expect_eq(*file_digest, *expected_digest);
// 3. Quota overflow aborts cleanly with quota_exceeded and leaves no file.
Void::Net::DownloadOptions tight_opts;
tight_opts.max_bytes = 1024U * 1024U; // < 4 MiB
auto quota_err =
client.download_to_file(base + "/blob", dl_quota_fail, tight_opts);
Void::Testing::require(!quota_err.has_value());
Void::Testing::expect_eq(
quota_err.error().code().value,
static_cast<std::int32_t>(Void::Net::NetErrorCode::quota_exceeded));
Void::Testing::expect(!std::filesystem::exists(dl_quota_fail));
// 4. std::stop_token cancels an in-flight stalled download promptly.
{
std::stop_source stop_src;
Void::Net::DownloadOptions cancel_opts;
cancel_opts.stop = stop_src.get_token();
std::jthread killer([&]() {
while (!slow_entered.load(std::memory_order_acquire)) {
std::this_thread::sleep_for(std::chrono::milliseconds{2});
}
std::this_thread::sleep_for(std::chrono::milliseconds{30});
stop_src.request_stop();
});
const auto t0 = std::chrono::steady_clock::now();
auto c_res = client.download_to_file(
base + "/hang", tmp / "cancelled.bin", cancel_opts);
const auto elapsed = std::chrono::steady_clock::now() - t0;
killer.join();
Void::Testing::require(!c_res.has_value());
Void::Testing::expect_eq(
c_res.error().code().value,
static_cast<std::int32_t>(Void::Net::NetErrorCode::cancelled));
Void::Testing::expect(elapsed < std::chrono::seconds{2});
Void::Testing::expect(!std::filesystem::exists(tmp / "cancelled.bin"));
release_hang.store(true, std::memory_order_release);
}
server.shutdown();
}
Void::Testing::Test http_client_secure_tls_verification_and_redaction()
{
// 1. Authorization & secret header redaction in diagnostics.
Void::Net::Request req;
req.method = Void::Net::Method::Get;
req.url = "https://user:superpass@registry.example/v1/pkg";
req.headers = {
{"Authorization", "Bearer top-secret-token-value"},
{"Proxy-Authorization", "Basic dXNlcjpwYXNz"},
{"Cookie", "session=secret-cookie"},
{"Accept", "application/json"},
};
const std::string diag =
Void::Net::HttpClient::format_request_diagnostics(req);
Void::Testing::expect(diag.find("top-secret-token-value") ==
std::string::npos);
Void::Testing::expect(diag.find("dXNlcjpwYXNz") == std::string::npos);
Void::Testing::expect(diag.find("secret-cookie") == std::string::npos);
Void::Testing::expect(diag.find("superpass") == std::string::npos);
Void::Testing::expect(diag.find("<redacted>") != std::string::npos);
Void::Testing::expect(diag.find("application/json") != std::string::npos);
// 2. Local TLS server verification checks.
Void::FileSystem::TempDir tmp{"void_http_tls_"};
const auto good_cert =
generate_self_signed_cert(tmp.path(), "IP:127.0.0.1", "good");
const auto bad_san_cert =
generate_self_signed_cert(tmp.path(), "DNS:wrong.invalid", "badsan");
// a) Untrusted self-signed cert is rejected by default on secure().
{
OneShotTlsServer tls_srv{good_cert, "tls-secret"};
auto client = Void::Net::HttpClient::secure();
auto r = client.get(
"https://127.0.0.1:" + std::to_string(tls_srv.port) + "/ok");
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(
r.error().code().value,
static_cast<std::int32_t>(Void::Net::NetErrorCode::tls_error));
}
// b) Trusted CA + matching IP:127.0.0.1 SAN succeeds.
{
OneShotTlsServer tls_srv{good_cert, "tls-verified-ok"};
auto client = Void::Net::HttpClient::secure();
client.set_ca_file(good_cert.cert_file.string());
auto r = client.get(
"https://127.0.0.1:" + std::to_string(tls_srv.port) + "/ok");
Void::Testing::require(r.has_value());
Void::Testing::expect_eq(r->status, std::uint16_t{200});
Void::Testing::expect_eq(r->body, std::string{"tls-verified-ok"});
}
// c) Trusted CA + mismatched SAN (DNS:wrong.invalid != 127.0.0.1) fails.
{
OneShotTlsServer tls_srv{bad_san_cert, "should-fail"};
auto client = Void::Net::HttpClient::secure();
client.set_ca_file(bad_san_cert.cert_file.string());
auto r = client.get(
"https://127.0.0.1:" + std::to_string(tls_srv.port) + "/bad");
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(
r.error().code().value,
static_cast<std::int32_t>(Void::Net::NetErrorCode::tls_error));
}
}
+393
View File
@@ -0,0 +1,393 @@
#include <Void/Net/Http.hpp>
#include <Void/Net/HttpServer.hpp>
#include <Void/System/TempDir.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <array>
#include <atomic>
#include <cstdint>
#include <filesystem>
#include <fstream>
#include <string>
#include <string_view>
#include <thread>
#include <vector>
namespace
{
using Void::Net::BodyReader;
using Void::Net::Header;
using Void::Net::HttpClient;
using Void::Net::HttpServer;
using Void::Net::HttpServerOptions;
using Void::Net::Method;
using Void::Net::Request;
using Void::Net::ServerRequest;
using Void::Net::ServerResponse;
std::string raw_http_exchange(std::uint16_t port, std::string_view raw_req)
{
const int fd = ::socket(AF_INET, SOCK_STREAM, 0);
Void::Testing::require(fd >= 0);
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr.sin_port = htons(port);
Void::Testing::require(
::connect(fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) ==
0);
std::size_t off = 0;
while (off < raw_req.size()) {
const ssize_t w =
::send(fd, raw_req.data() + off, raw_req.size() - off, 0);
Void::Testing::require(w > 0);
off += static_cast<std::size_t>(w);
}
(void)::shutdown(fd, SHUT_WR);
std::string out;
std::array<char, 4096> buf{};
for (;;) {
const ssize_t r = ::recv(fd, buf.data(), buf.size(), 0);
if (r <= 0) {
break;
}
out.append(buf.data(), static_cast<std::size_t>(r));
}
(void)::close(fd);
return out;
}
std::string read_file_bytes(const std::filesystem::path& p)
{
std::ifstream in{p, std::ios::binary};
Void::Testing::require(in.is_open());
return std::string{std::istreambuf_iterator<char>{in},
std::istreambuf_iterator<char>{}};
}
} // namespace
Void::Testing::Test http_server_ephemeral_methods_and_concurrent_dispatch()
{
HttpServerOptions opts;
opts.bind_host = "127.0.0.1";
opts.port = 0;
HttpServer server{opts};
Void::Testing::require(
server
.add_route(Method::Get, "/items/:id",
[](const ServerRequest& req) {
return Void::Result::ok(ServerResponse{
.status = 200,
.headers = {Header{"X-Item",
req.parameters.at("id")}},
.body = "get:" + req.parameters.at("id") + "?" +
req.query});
})
.has_value());
Void::Testing::require(
server
.add_route(Method::Post, "/items",
[](const ServerRequest& req) {
return Void::Result::ok(ServerResponse{
.status = 201, .body = "post:" + req.body});
})
.has_value());
Void::Testing::require(
server
.add_route(Method::Put, "/items/:id",
[](const ServerRequest& req) {
return Void::Result::ok(ServerResponse{
.status = 200,
.body = "put:" + req.parameters.at("id") + ":" +
req.body});
})
.has_value());
Void::Testing::require(
server
.add_route(Method::Delete, "/items/:id",
[](const ServerRequest& req) {
return Void::Result::ok(ServerResponse{
.status = 200,
.body = "del:" + req.parameters.at("id")});
})
.has_value());
Void::Testing::require(
server
.add_route(Method::Get, "/boom",
[](const ServerRequest&) -> Void::Net::RouteResult {
return Void::Result::fail(
"internal secret db credentials leaked here");
})
.has_value());
Void::Testing::require(server.start().has_value());
const std::uint16_t port = server.bound_port();
Void::Testing::expect(port > 0);
Void::Testing::expect(server.running());
const std::string base = server.base_url();
HttpClient client;
// GET + query + path param
{
auto r = client.get(base + "/items/alpha?full=1");
Void::Testing::require(r.has_value());
Void::Testing::expect_eq(r->status, std::uint16_t{200});
Void::Testing::expect_eq(r->body, std::string{"get:alpha?full=1"});
Void::Testing::expect_eq(*r->header("x-item"), std::string_view{"alpha"});
}
// HEAD falls back to GET route without response body
{
auto r = client.send(Request{.method = Method::Head,
.url = base + "/items/alpha?full=1"});
Void::Testing::require(r.has_value());
Void::Testing::expect_eq(r->status, std::uint16_t{200});
Void::Testing::expect(r->body.empty());
Void::Testing::expect_eq(*r->header("X-Item"), std::string_view{"alpha"});
}
// POST, PUT, DELETE
{
auto post_r = client.post(base + "/items", "new-payload");
Void::Testing::require(post_r.has_value());
Void::Testing::expect_eq(post_r->status, std::uint16_t{201});
Void::Testing::expect_eq(post_r->body, std::string{"post:new-payload"});
auto put_r = client.send(Request{.method = Method::Put,
.url = base + "/items/beta",
.body = "updated"});
Void::Testing::require(put_r.has_value());
Void::Testing::expect_eq(put_r->status, std::uint16_t{200});
Void::Testing::expect_eq(put_r->body, std::string{"put:beta:updated"});
auto del_r = client.send(Request{.method = Method::Delete,
.url = base + "/items/beta"});
Void::Testing::require(del_r.has_value());
Void::Testing::expect_eq(del_r->status, std::uint16_t{200});
Void::Testing::expect_eq(del_r->body, std::string{"del:beta"});
}
// 404, 405 + Allow, sanitized 500
{
auto r404 = client.get(base + "/missing");
Void::Testing::require(r404.has_value());
Void::Testing::expect_eq(r404->status, std::uint16_t{404});
auto r405 = client.post(base + "/boom", "ignored");
Void::Testing::require(r405.has_value());
Void::Testing::expect_eq(r405->status, std::uint16_t{405});
auto allow = r405->header("Allow");
Void::Testing::require(allow.has_value());
Void::Testing::expect(allow->find("GET") != std::string_view::npos);
auto r500 = client.get(base + "/boom");
Void::Testing::require(r500.has_value());
Void::Testing::expect_eq(r500->status, std::uint16_t{500});
Void::Testing::expect(r500->body.find("secret db credentials") ==
std::string::npos);
}
// Concurrent client burst
{
constexpr int kThreads = 8;
constexpr int kPerThread = 10;
std::atomic<int> ok_count{0};
std::vector<std::thread> threads;
threads.reserve(kThreads);
for (int t = 0; t < kThreads; ++t) {
threads.emplace_back([&, t]() {
HttpClient c;
for (int i = 0; i < kPerThread; ++i) {
const std::string tag =
std::to_string(t) + "-" + std::to_string(i);
auto res = c.get(base + "/items/" + tag);
if (res.has_value() && res->status == 200 &&
res->body == ("get:" + tag + "?")) {
ok_count.fetch_add(1, std::memory_order_relaxed);
}
}
});
}
for (auto& th : threads) {
th.join();
}
Void::Testing::expect_eq(ok_count.load(), kThreads * kPerThread);
}
server.shutdown();
Void::Testing::expect(!server.running());
Void::Testing::expect_eq(server.bound_port(), std::uint16_t{0});
// No dangling listening socket after shutdown().
const int probe = ::socket(AF_INET, SOCK_STREAM, 0);
Void::Testing::require(probe >= 0);
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr.sin_port = htons(port);
Void::Testing::expect(
::connect(probe, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) !=
0);
(void)::close(probe);
}
Void::Testing::Test http_server_limits_smuggling_streaming_and_graceful_drain()
{
Void::FileSystem::TempDir tmp{"void_http_srv_"};
const auto uploaded_path = tmp / "uploaded.bin";
HttpServerOptions opts;
opts.max_header_bytes = 512;
opts.max_body_bytes = 64;
opts.max_streaming_body_bytes = 2U * 1024U * 1024U;
HttpServer server{opts};
Void::Testing::require(
server
.add_route(Method::Post, "/small",
[](const ServerRequest& req) {
return Void::Result::ok(ServerResponse{
.status = 200, .body = req.body});
})
.has_value());
Void::Testing::require(
server
.add_streaming_route(
Method::Put, "/upload",
[&](const ServerRequest&, BodyReader& body)
-> Void::Net::RouteResult {
auto n = body.read_to_file(uploaded_path);
if (!n.has_value()) {
return std::unexpected{std::move(n.error())};
}
return ServerResponse{
.status = 201,
.body = std::to_string(*n)};
})
.has_value());
Void::Testing::require(
server
.add_route(Method::Get, "/artifact",
[&](const ServerRequest&) {
return Void::Result::ok(
ServerResponse::from_file(uploaded_path));
})
.has_value());
std::atomic<bool> in_flight_entered{false};
std::atomic<bool> allow_in_flight_exit{false};
Void::Testing::require(
server
.add_route(Method::Get, "/slow",
[&](const ServerRequest&) {
in_flight_entered.store(true,
std::memory_order_release);
while (!allow_in_flight_exit.load(
std::memory_order_acquire)) {
std::this_thread::sleep_for(
std::chrono::milliseconds{5});
}
return Void::Result::ok(
ServerResponse{.status = 200, .body = "drained"});
})
.has_value());
Void::Testing::require(server.start().has_value());
const std::uint16_t port = server.bound_port();
const std::string base = server.base_url();
HttpClient client;
// 1. Oversized buffered body (Content-Length and chunked) rejected with 413.
{
const std::string big(128, 'A');
auto r413 = client.post(base + "/small", big);
Void::Testing::require(r413.has_value());
Void::Testing::expect_eq(r413->status, std::uint16_t{413});
const std::string chunked_big =
"POST /small HTTP/1.1\r\n"
"Host: 127.0.0.1\r\n"
"Transfer-Encoding: chunked\r\n"
"Connection: close\r\n\r\n"
"50\r\n" +
std::string(80, 'B') + "\r\n0\r\n\r\n";
const std::string raw_resp = raw_http_exchange(port, chunked_big);
Void::Testing::expect(raw_resp.starts_with("HTTP/1.1 413"));
}
// 2. Oversized header rejected with 431; TE+CL smuggling rejected with 400.
{
const std::string huge_hdr =
"GET /small HTTP/1.1\r\n"
"Host: 127.0.0.1\r\n"
"X-Huge: " +
std::string(700, 'H') + "\r\n\r\n";
const std::string raw_431 = raw_http_exchange(port, huge_hdr);
Void::Testing::expect(raw_431.starts_with("HTTP/1.1 431"));
const std::string smuggle =
"POST /small HTTP/1.1\r\n"
"Host: 127.0.0.1\r\n"
"Content-Length: 4\r\n"
"Transfer-Encoding: chunked\r\n\r\n"
"0\r\n\r\n";
const std::string raw_400 = raw_http_exchange(port, smuggle);
Void::Testing::expect(raw_400.starts_with("HTTP/1.1 400"));
}
// 3. Streaming PUT to file + streaming file_body GET (larger than buffered
// max_body_bytes = 64B!).
{
std::string payload(256U * 1024U, '\0');
for (std::size_t i = 0; i < payload.size(); ++i) {
payload[i] = static_cast<char>('a' + (i % 26U));
}
auto put_r = client.send(Request{.method = Method::Put,
.url = base + "/upload",
.body = payload});
Void::Testing::require(put_r.has_value());
Void::Testing::expect_eq(put_r->status, std::uint16_t{201});
Void::Testing::expect_eq(put_r->body,
std::to_string(payload.size()));
Void::Testing::expect_eq(read_file_bytes(uploaded_path), payload);
auto get_r = client.get(base + "/artifact");
Void::Testing::require(get_r.has_value());
Void::Testing::expect_eq(get_r->status, std::uint16_t{200});
Void::Testing::expect_eq(get_r->body, payload);
}
// 4. Graceful shutdown drains active in-flight request cleanly.
{
Void::Result::Result<Void::Net::Response, Void::Result::Error>
slow_result = Void::Result::fail("uninitialized");
std::thread slow_client([&]() {
HttpClient c;
slow_result = c.get(base + "/slow");
});
while (!in_flight_entered.load(std::memory_order_acquire)) {
std::this_thread::sleep_for(std::chrono::milliseconds{2});
}
std::thread releaser([&]() {
std::this_thread::sleep_for(std::chrono::milliseconds{40});
allow_in_flight_exit.store(true, std::memory_order_release);
});
server.shutdown(std::chrono::seconds{2});
releaser.join();
slow_client.join();
Void::Testing::require(slow_result.has_value());
Void::Testing::expect_eq(slow_result->status, std::uint16_t{200});
Void::Testing::expect_eq(slow_result->body, std::string{"drained"});
}
}
@@ -0,0 +1,176 @@
#include <Void/System/DirectoryWatcher.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/TempDir.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <algorithm>
#include <chrono>
#include <filesystem>
#include <string>
#include <vector>
namespace
{
[[nodiscard]] std::vector<Void::FileSystem::DirectoryEvent>
collect_events(Void::FileSystem::DirectoryWatcher& watcher,
std::chrono::milliseconds budget)
{
std::vector<Void::FileSystem::DirectoryEvent> all;
const auto deadline = std::chrono::steady_clock::now() + budget;
while (std::chrono::steady_clock::now() < deadline) {
auto batch = watcher.poll(std::chrono::milliseconds{40});
Void::Testing::require(batch.has_value());
for (auto& ev : *batch) {
all.push_back(std::move(ev));
}
if (!all.empty() && batch->empty()) {
break;
}
}
return all;
}
} // namespace
Void::Testing::Test directory_watcher_tracks_recursive_trees_ignores_and_renames()
{
Void::FileSystem::TempDir tmp{"void_dir_watch_"};
const auto ignored_dir = tmp / ".git";
Void::Testing::require(
Void::FileSystem::ensure_directory(ignored_dir).has_value());
Void::FileSystem::DirectoryWatcherOptions opts;
opts.ignore = [](const std::filesystem::path& p, bool) {
for (const auto& part : p) {
if (part == ".git" || part == "build") {
return true;
}
}
return false;
};
auto w_res = Void::FileSystem::DirectoryWatcher::create(tmp.path(), opts);
Void::Testing::require(w_res.has_value());
auto watcher = std::move(*w_res);
Void::Testing::expect_eq(watcher.watch_count(), std::size_t{1});
// Ignored subtree changes must produce zero events
Void::Testing::require(
Void::FileSystem::write_file(ignored_dir / "HEAD", "ref").has_value());
auto ignored_events = watcher.poll(std::chrono::milliseconds{40});
Void::Testing::require(ignored_events.has_value());
Void::Testing::expect(ignored_events->empty());
// Create nested subdirectories + file immediately -> auto-watched recursively
const auto sub = tmp / "src/core";
Void::Testing::require(Void::FileSystem::ensure_directory(sub).has_value());
Void::Testing::require(
Void::FileSystem::write_file(sub / "main.cpp", "int main(){}")
.has_value());
const auto create_events =
collect_events(watcher, std::chrono::milliseconds{500});
const bool saw_file_create_or_mod = std::any_of(
create_events.begin(), create_events.end(),
[&](const Void::FileSystem::DirectoryEvent& ev) {
return ev.path.filename() == "main.cpp" &&
(ev.kind == Void::FileSystem::DirectoryEventKind::Created ||
ev.kind == Void::FileSystem::DirectoryEventKind::Modified);
});
Void::Testing::expect(saw_file_create_or_mod);
Void::Testing::expect(watcher.watch_count() >= 3U);
// Modify inside auto-watched nested directory
Void::Testing::require(
Void::FileSystem::write_file(sub / "main.cpp", "int main(){return 0;}")
.has_value());
const auto mod_events =
collect_events(watcher, std::chrono::milliseconds{400});
Void::Testing::expect(std::any_of(
mod_events.begin(), mod_events.end(),
[](const Void::FileSystem::DirectoryEvent& ev) {
return ev.kind == Void::FileSystem::DirectoryEventKind::Modified &&
ev.path.filename() == "main.cpp";
}));
// File rename pairing (IN_MOVED_FROM / IN_MOVED_TO)
std::filesystem::rename(sub / "main.cpp", sub / "entry.cpp");
const auto ren_events =
collect_events(watcher, std::chrono::milliseconds{400});
Void::Testing::expect(std::any_of(
ren_events.begin(), ren_events.end(),
[](const Void::FileSystem::DirectoryEvent& ev) {
return ev.kind == Void::FileSystem::DirectoryEventKind::Renamed &&
ev.old_path.filename() == "main.cpp" &&
ev.path.filename() == "entry.cpp";
}));
// Directory rename rewrites watch paths so modifications inside new path
// still report the new directory path.
const auto renamed_dir = tmp / "src/engine";
std::filesystem::rename(sub, renamed_dir);
(void)collect_events(watcher, std::chrono::milliseconds{300});
Void::Testing::require(
Void::FileSystem::write_file(renamed_dir / "entry.cpp", "// updated")
.has_value());
const auto post_move_events =
collect_events(watcher, std::chrono::milliseconds{400});
Void::Testing::expect(std::any_of(
post_move_events.begin(), post_move_events.end(),
[&](const Void::FileSystem::DirectoryEvent& ev) {
return ev.kind == Void::FileSystem::DirectoryEventKind::Modified &&
ev.path == (watcher.root() / "src/engine/entry.cpp");
}));
// Directory replacement / deletion storm
std::filesystem::remove_all(tmp / "src");
const auto del_events =
collect_events(watcher, std::chrono::milliseconds{400});
Void::Testing::expect(std::any_of(
del_events.begin(), del_events.end(),
[](const Void::FileSystem::DirectoryEvent& ev) {
return ev.kind == Void::FileSystem::DirectoryEventKind::Deleted;
}));
}
Void::Testing::Test directory_watcher_signals_rescan_on_overflow_and_limit()
{
Void::FileSystem::TempDir tmp{"void_dir_ovf_"};
// 1. Simulated queue overflow emits RescanRequired and wake recovers
{
auto w_res = Void::FileSystem::DirectoryWatcher::create(tmp.path());
Void::Testing::require(w_res.has_value());
w_res->simulate_overflow_for_test();
auto evs = w_res->poll(std::chrono::milliseconds{100});
Void::Testing::require(evs.has_value());
Void::Testing::expect(std::any_of(
evs->begin(), evs->end(),
[](const Void::FileSystem::DirectoryEvent& ev) {
return ev.kind ==
Void::FileSystem::DirectoryEventKind::RescanRequired;
}));
Void::Testing::require(w_res->rescan().has_value());
}
// 2. max_watches exhaustion emits RescanRequired
{
Void::FileSystem::DirectoryWatcherOptions tight;
tight.max_watches = 1U;
auto w_res =
Void::FileSystem::DirectoryWatcher::create(tmp.path(), tight);
Void::Testing::require(w_res.has_value());
Void::Testing::require(
Void::FileSystem::ensure_directory(tmp / "extra_dir").has_value());
const auto evs = collect_events(*w_res, std::chrono::milliseconds{400});
Void::Testing::expect(std::any_of(
evs.begin(), evs.end(),
[](const Void::FileSystem::DirectoryEvent& ev) {
return ev.kind ==
Void::FileSystem::DirectoryEventKind::RescanRequired;
}));
}
}
+116
View File
@@ -96,3 +96,119 @@ Void::Testing::Test remove_path_handles_missing_and_recursive()
Void::Testing::expect(r2.has_value()); Void::Testing::expect(r2.has_value());
Void::Testing::expect(!std::filesystem::exists(tmp.path() / "a")); Void::Testing::expect(!std::filesystem::exists(tmp.path() / "a"));
} }
Void::Testing::Test filesystem_file_lock_symlink_swap_reflink_and_timestamps()
{
Void::FileSystem::TempDir tmp{"void_fs_vl010_"};
// 1. RAII advisory FileLock (shared & exclusive, blocking & try_lock)
{
const auto lock_path = tmp / "resource.lock";
auto ex = Void::FileSystem::FileLock::lock(
lock_path, Void::FileSystem::LockMode::Exclusive);
Void::Testing::require(ex.has_value());
Void::Testing::expect(ex->locked());
auto contended_ex = Void::FileSystem::FileLock::try_lock(
lock_path, Void::FileSystem::LockMode::Exclusive);
Void::Testing::require(contended_ex.has_value());
Void::Testing::expect(!contended_ex->has_value());
auto contended_sh = Void::FileSystem::FileLock::try_lock(
lock_path, Void::FileSystem::LockMode::Shared);
Void::Testing::require(contended_sh.has_value());
Void::Testing::expect(!contended_sh->has_value());
ex->unlock();
Void::Testing::expect(!ex->locked());
auto sh1 = Void::FileSystem::FileLock::try_lock(
lock_path, Void::FileSystem::LockMode::Shared);
auto sh2 = Void::FileSystem::FileLock::try_lock(
lock_path, Void::FileSystem::LockMode::Shared);
Void::Testing::require(sh1.has_value() && sh1->has_value());
Void::Testing::require(sh2.has_value() && sh2->has_value());
}
// 2. Atomic symlink swap over missing, existing, and dangling links
{
const auto link_path = tmp / "current";
Void::Testing::require(
Void::FileSystem::atomic_symlink_swap(link_path, "v1")
.has_value());
Void::Testing::expect_eq(
std::filesystem::read_symlink(link_path).string(),
std::string{"v1"});
Void::Testing::require(
Void::FileSystem::atomic_symlink_swap(link_path, "v2")
.has_value());
Void::Testing::expect_eq(
std::filesystem::read_symlink(link_path).string(),
std::string{"v2"});
}
// 3. reflink_copy_file isolates copied file (never hardlinked)
{
const auto src = tmp / "origin.bin";
const auto dst = tmp / "cloned.bin";
const std::string payload(128ULL * 1024ULL, 'K');
Void::Testing::require(
Void::FileSystem::write_file(src, payload).has_value());
auto cp = Void::FileSystem::reflink_copy_file(src, dst);
Void::Testing::require(cp.has_value());
Void::Testing::expect_eq(cp->bytes, payload.size());
Void::Testing::expect_eq(
Void::FileSystem::read_file(dst).value(), payload);
struct stat st_src {};
struct stat st_dst {};
Void::Testing::require(::lstat(src.c_str(), &st_src) == 0);
Void::Testing::require(::lstat(dst.c_str(), &st_dst) == 0);
Void::Testing::expect(st_src.st_ino != st_dst.st_ino);
Void::Testing::expect_eq(st_src.st_nlink, nlink_t{1});
Void::Testing::expect_eq(st_dst.st_nlink, nlink_t{1});
// overwrite == false must fail cleanly when dst already exists
Void::FileSystem::CopyOptions no_overwrite;
no_overwrite.overwrite = false;
Void::Testing::expect(
!Void::FileSystem::reflink_copy_file(src, dst, no_overwrite)
.has_value());
// Mutating dst must never alter src
Void::Testing::require(
Void::FileSystem::write_file(dst, "mutated").has_value());
Void::Testing::expect_eq(
Void::FileSystem::read_file(src).value(), payload);
}
// 4. Canonical timestamp setter with AT_SYMLINK_NOFOLLOW
{
const auto target = tmp / "real.txt";
const auto link = tmp / "alias.txt";
Void::Testing::require(
Void::FileSystem::write_file(target, "data").has_value());
Void::Testing::require(
Void::FileSystem::atomic_symlink_swap(link, target).has_value());
constexpr std::int64_t kTargetMtime = 1'700'000'000LL;
constexpr std::int64_t kLinkMtime = 1'600'000'123LL;
Void::Testing::require(
Void::FileSystem::set_canonical_mtime(target, kTargetMtime)
.has_value());
Void::Testing::require(
Void::FileSystem::set_canonical_mtime(link, kLinkMtime)
.has_value());
struct stat st_target {};
struct stat st_link {};
Void::Testing::require(::lstat(target.c_str(), &st_target) == 0);
Void::Testing::require(::lstat(link.c_str(), &st_link) == 0);
Void::Testing::expect_eq(static_cast<std::int64_t>(st_target.st_mtim.tv_sec),
kTargetMtime);
Void::Testing::expect_eq(static_cast<std::int64_t>(st_link.st_mtim.tv_sec),
kLinkMtime);
}
}
@@ -19,6 +19,7 @@
#include <fstream> #include <fstream>
#include <stop_token> #include <stop_token>
#include <string> #include <string>
#include <thread>
#include <vector> #include <vector>
namespace namespace
@@ -294,3 +295,72 @@ Void::Testing::Test system_replace_file_temp_ownership_and_metrics()
expect(sample.valid); expect(sample.valid);
expect(sample.ratio >= 0.0); expect(sample.ratio >= 0.0);
} }
Void::Testing::Test system_terminate_reaps_entire_process_group_after_leader_exits()
{
Void::FileSystem::TempDir tmp{"void_sys_pgid_"};
const auto marker = tmp / "grandchild_ticks.txt";
Void::Process::SpawnOptions opts;
opts.executable = VOID_PROCESS_HELPER_PATH;
opts.arguments = {"grandchild-ignore-sigterm", marker.string()};
opts.new_process_group = true;
opts.stdin_pipe = false;
opts.stderr_pipe = false;
auto spawned = Void::Process::spawn(opts);
require(spawned.has_value());
// Wait for grandchild readiness signal on stdout.
std::string ready_buf;
std::array<char, 64> chunk{};
const auto wait_start = std::chrono::steady_clock::now();
while (ready_buf.find("ready\n") == std::string::npos) {
const ssize_t n = ::read(spawned->stdout_fd(), chunk.data(), chunk.size());
if (n > 0) {
ready_buf.append(chunk.data(), static_cast<std::size_t>(n));
continue;
}
if (n < 0 && errno == EINTR) {
continue;
}
if (std::chrono::steady_clock::now() - wait_start > std::chrono::seconds{5}) {
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds{5});
}
require(ready_buf.find("ready\n") != std::string::npos);
// Wait until direct leader has exited and been reaped, while the
// SIGTERM-ignoring grandchild continues running in the process group.
std::optional<Void::Process::ExitStatus> leader_status;
for (int i = 0; i < 200; ++i) {
auto w = spawned->try_wait();
require(w.has_value());
if (w->has_value()) {
leader_status = *w;
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds{5});
}
require(leader_status.has_value());
expect(leader_status->exited);
expect_eq(leader_status->code, 0);
expect(spawned->process_group_alive());
// terminate(60ms) must send SIGTERM to -pgid, wait out grace since the
// grandchild ignores SIGTERM, escalate to SIGKILL, and not return until
// ESRCH confirms all process-group members are gone.
auto term = spawned->terminate(std::chrono::milliseconds{60});
require(term.has_value());
expect(!spawned->process_group_alive());
std::error_code ec;
const auto size_after_terminate = std::filesystem::file_size(marker, ec);
require(!ec);
expect(size_after_terminate > 0U);
std::this_thread::sleep_for(std::chrono::milliseconds{100});
const auto size_later = std::filesystem::file_size(marker, ec);
require(!ec);
expect_eq(size_later, size_after_terminate);
}
@@ -0,0 +1,46 @@
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Detail/Registry.hpp>
#include <Void/Testing/Test.hpp>
#include <string>
namespace void_testing_native_test
{
struct CounterFixture {
int value{0};
void setup() { value = 41; }
void teardown() { value = 0; }
};
} // namespace void_testing_native_test
VOID_TEST(NativeApi, self_registers_free_test)
{
Void::Testing::expect_eq(2 + 3, 5);
}
VOID_TEST_TAGGED(NativeApi, tagged_native_test, "fast", "native")
{
const auto& tests = Void::Testing::Detail::Registry::instance().tests();
bool found = false;
for (const auto& t : tests) {
if (t.suite == "NativeApi" && t.name == "tagged_native_test") {
found = (t.tags.size() == 2U && t.tags[0] == "fast" &&
t.tags[1] == "native");
break;
}
}
Void::Testing::expect(found);
}
VOID_TEST_DISABLED(NativeApi, disabled_native_test, "intentional skip check")
{
Void::Testing::expect(false);
}
VOID_TEST_FIXTURE(void_testing_native_test::CounterFixture,
fixture_runs_setup_hook)
{
Void::Testing::expect_eq(fixture.value, 41);
fixture.value += 1;
Void::Testing::expect_eq(fixture.value, 42);
}
+85
View File
@@ -148,12 +148,97 @@ Void::Testing::Test semver_version_ranges_reject_overflowing_upper_bounds()
{ {
Void::Testing::expect( Void::Testing::expect(
!Void::Semver::parse_range("^4294967295.0.0").has_value()); !Void::Semver::parse_range("^4294967295.0.0").has_value());
Void::Testing::expect(
!Void::Semver::parse_range("^4294967295").has_value());
Void::Testing::expect(
!Void::Semver::parse_range("~4294967295").has_value());
Void::Testing::expect( Void::Testing::expect(
!Void::Semver::parse_range("4294967295.x").has_value()); !Void::Semver::parse_range("4294967295.x").has_value());
Void::Testing::expect( Void::Testing::expect(
!Void::Semver::parse_range("1.4294967295.x").has_value()); !Void::Semver::parse_range("1.4294967295.x").has_value());
} }
Void::Testing::Test semver_shorthand_comparators()
{
const auto caret_major = Void::Semver::parse_range("^1");
Void::Testing::require(caret_major.has_value());
Void::Testing::expect(
caret_major->contains(*Void::Semver::parse("1.0.0")));
Void::Testing::expect(
caret_major->contains(*Void::Semver::parse("1.9.9")));
Void::Testing::expect(
!caret_major->contains(*Void::Semver::parse("2.0.0")));
Void::Testing::expect(
!caret_major->contains(*Void::Semver::parse("0.9.0")));
const auto caret_zero = Void::Semver::parse_range("^0");
Void::Testing::require(caret_zero.has_value());
Void::Testing::expect(
caret_zero->contains(*Void::Semver::parse("0.0.0")));
Void::Testing::expect(
caret_zero->contains(*Void::Semver::parse("0.9.5")));
Void::Testing::expect(
!caret_zero->contains(*Void::Semver::parse("1.0.0")));
const auto caret_minor = Void::Semver::parse_range("^1.0");
Void::Testing::require(caret_minor.has_value());
Void::Testing::expect(
caret_minor->contains(*Void::Semver::parse("1.0.0")));
Void::Testing::expect(
caret_minor->contains(*Void::Semver::parse("1.5.2")));
Void::Testing::expect(
!caret_minor->contains(*Void::Semver::parse("2.0.0")));
const auto caret_11 = Void::Semver::parse_range("^11.0");
Void::Testing::require(caret_11.has_value());
Void::Testing::expect(
caret_11->contains(*Void::Semver::parse("11.4.2")));
Void::Testing::expect(
!caret_11->contains(*Void::Semver::parse("12.0.0")));
const auto caret_zero_minor = Void::Semver::parse_range("^0.2");
Void::Testing::require(caret_zero_minor.has_value());
Void::Testing::expect(
caret_zero_minor->contains(*Void::Semver::parse("0.2.7")));
Void::Testing::expect(
!caret_zero_minor->contains(*Void::Semver::parse("0.3.0")));
const auto tilde_minor = Void::Semver::parse_range("~1.2");
Void::Testing::require(tilde_minor.has_value());
Void::Testing::expect(
tilde_minor->contains(*Void::Semver::parse("1.2.0")));
Void::Testing::expect(
tilde_minor->contains(*Void::Semver::parse("1.2.9")));
Void::Testing::expect(
!tilde_minor->contains(*Void::Semver::parse("1.3.0")));
const auto tilde_major = Void::Semver::parse_range("~2");
Void::Testing::require(tilde_major.has_value());
Void::Testing::expect(
tilde_major->contains(*Void::Semver::parse("2.5.0")));
Void::Testing::expect(
!tilde_major->contains(*Void::Semver::parse("3.0.0")));
const auto mixed = Void::Semver::parse_range(">=1.2 <2");
Void::Testing::require(mixed.has_value());
Void::Testing::expect(mixed->contains(*Void::Semver::parse("1.2.0")));
Void::Testing::expect(mixed->contains(*Void::Semver::parse("1.9.4")));
Void::Testing::expect(!mixed->contains(*Void::Semver::parse("1.1.9")));
Void::Testing::expect(!mixed->contains(*Void::Semver::parse("2.0.0")));
const auto less_only = Void::Semver::parse_range("<1.2.0");
Void::Testing::require(less_only.has_value());
Void::Testing::expect(less_only->contains(*Void::Semver::parse("1.1.9")));
Void::Testing::expect(
!less_only->contains(*Void::Semver::parse("1.2.0")));
Void::Testing::expect(!Void::Semver::parse_range("^").has_value());
Void::Testing::expect(!Void::Semver::parse_range("^1.").has_value());
Void::Testing::expect(!Void::Semver::parse_range("^01").has_value());
Void::Testing::expect(
!Void::Semver::parse_range(">=1.2-alpha").has_value());
}
// ── bump ───────────────────────────────────────────────────────────────────── // ── bump ─────────────────────────────────────────────────────────────────────
Void::Testing::Test semver_bump_major() Void::Testing::Test semver_bump_major()