diff --git a/CMakeLists.txt b/CMakeLists.txt index bf4f33b..dfa71d8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ 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) option(BUILD_SHARED_LIBS "Build Void modules as shared libraries" ON) elseif(NOT DEFINED BUILD_SHARED_LIBS) diff --git a/cmake/Dependencies.cmake b/cmake/Dependencies.cmake index ed0d046..bad158b 100644 --- a/cmake/Dependencies.cmake +++ b/cmake/Dependencies.cmake @@ -158,9 +158,89 @@ function(void_fetch_dependency DEP_NAME) endif() if(DEP_NAME STREQUAL "SQLite3") - if(NOT TARGET SQLite3::SQLite3 AND NOT TARGET SQLite::SQLite3) - find_package(SQLite3 REQUIRED) + if(TARGET SQLite3::SQLite3) + return() 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 + "$<$>:${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) add_library(SQLite3::SQLite3 ALIAS SQLite::SQLite3) endif() diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index 3979054..1345772 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -1,8 +1,8 @@ # Workflow state Updated: 2026-11-26. -Repository: VoidLibrary; active branch `feat/roadmap-p2-wave8` (from `main` -at `d83d0f4`, merged Waves 1–7 and pushed to `origin/main`). +Repository: VoidLibrary; active branch `feat/upstream-vbs-requests` (from `main` +at `53d42bd`, merged Waves 1–8 and pushed to `origin/main`). ## 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. - 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 Waves 1–8 (`P0`, `P1`, `P2` Operations Foundations, `System`/`SystemAsync`/`IPC`, `Crypto`/`CryptoAsync`/`Security`/`SecurityAsync`/`Archive`/`Update`, -`Sqlite`/`SqliteAsync`/`Storage` `G-STORE`, and -`Service`/`ServicePlugin`/`Plugin`/`Configuration`/`ConfigurationAsync`/`Fsm`) are complete -and merged to `main`, proceeding to the VoidBuildSystem upstream feature wave -(`VL-001`..`VL-013`) and P2 `Net`. +`Sqlite`/`SqliteAsync`/`Storage` `G-STORE`, +`Service`/`ServicePlugin`/`Plugin`/`Configuration`/`ConfigurationAsync`/`Fsm`) +and the VoidBuildSystem upstream feature wave (`VL-001`..`VL-013`) are complete, +verified, and merged to `main` via `--no-ff`. diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index 241fdf5..6927f7b 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -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` reflection/provenance/redaction/deprecation checks) + split `ConfigurationAsync` (transactional `ReloadController`, `Snapshot`, `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()`, 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 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 diff --git a/docs/agent-workflow/VERIFICATION.md b/docs/agent-workflow/VERIFICATION.md index 15d6e9c..c29d14d 100644 --- a/docs/agent-workflow/VERIFICATION.md +++ b/docs/agent-workflow/VERIFICATION.md @@ -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 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 | +| 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 | diff --git a/include/Void/Archive/Archive.hpp b/include/Void/Archive/Archive.hpp index 22b4318..6bf5780 100644 --- a/include/Void/Archive/Archive.hpp +++ b/include/Void/Archive/Archive.hpp @@ -29,9 +29,14 @@ namespace Void::Archive std::uint64_t bytes{0}; }; - /// Extract a tar/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 + /// Returns true if Void::Archive was built with LibArchive support (required + /// for .tar.zst and .tar.gz compression/decompression; uncompressed USTAR/PAX + /// .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`. [[nodiscard]] Void::Result::Result extract(const std::filesystem::path& archivePath, @@ -177,9 +182,9 @@ namespace Void::Archive std::chrono::seconds min_age = std::chrono::seconds{300}); - /// Create a bounded, optionally reproducible tar or tar.zst archive from - /// regular file and directory entries. Sorts normalized paths, rejects - /// duplicates/conflicts, and opens source files with O_NOFOLLOW. + /// Create a bounded, optionally reproducible tar, tar.gz, or tar.zst + /// archive from regular file and directory entries. Sorts normalized + /// paths, rejects duplicates/conflicts, and opens source files with O_NOFOLLOW. [[nodiscard]] Void::Result::Result create_archive(ByteSink& sink, std::span entries, const CreationOptions& options = {}); @@ -189,6 +194,16 @@ namespace Void::Archive std::span entries, const CreationOptions& options = {}); + /// Canonical snake_case alias for `create_archive`. + [[nodiscard]] Void::Result::Result + create(ByteSink& sink, std::span entries, + const CreationOptions& options = {}); + + [[nodiscard]] Void::Result::Result + create(const std::filesystem::path& output_path, + std::span entries, + const CreationOptions& options = {}); + /// Hardened untrusted-input profile: extracts the archive in an isolated /// System child process with bounded execution time and RSS checks, then /// independently verifies the staged tree and inventory in the parent diff --git a/include/Void/Archive/Types.hpp b/include/Void/Archive/Types.hpp index 44de549..7950833 100644 --- a/include/Void/Archive/Types.hpp +++ b/include/Void/Archive/Types.hpp @@ -175,13 +175,17 @@ namespace Void::Archive ProgressCallback on_progress{}; }; - enum class ArchiveCompression : std::uint8_t { None = 0, Zstd }; + enum class ArchiveCompression : std::uint8_t { None = 0, Zstd, Gzip }; struct CreationOptions { ArchiveCompression compression{ArchiveCompression::Zstd}; bool reproducible{true}; ReadLimits limits{}; 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 { @@ -190,6 +194,7 @@ namespace Void::Archive bool executable{false}; std::vector content{}; std::optional source_file{}; + std::optional mode{}; }; struct IsolationOptions { diff --git a/include/Void/Configuration/Argparse.hpp b/include/Void/Configuration/Argparse.hpp index 9d817c7..f01e936 100644 --- a/include/Void/Configuration/Argparse.hpp +++ b/include/Void/Configuration/Argparse.hpp @@ -2,7 +2,10 @@ #include +#include #include +#include +#include #include #include #include @@ -11,23 +14,56 @@ namespace Void::Argparse { + enum class ParseOutcome : std::uint8_t { + Ok, + Help, + Error, + }; + + struct ParseResult { + ParseOutcome outcome{ParseOutcome::Ok}; + std::string message{}; + std::vector 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 // ──────────────────────────────────────────────────────────────────── // Fluent command-line argument parser. // // Supports: // --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 + // option_many(...) repeatable option collecting all occurrences + // subcommand(...) nested subcommand parsers (e.g. "compdb use") // positional args collected in declaration order - // --help / -h auto-generated help text + // --help / -h auto-generated help text (ParseOutcome::Help) class Parser { public: 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. // long_name: e.g. "--verbose" short_name: e.g. "-v" (short_name @@ -43,6 +79,12 @@ namespace Void::Argparse std::string_view description, std::optional& 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& out); + // Add an option with a default value. out is always set after // parse(). Parser& option_default(std::string_view long_name, @@ -55,7 +97,28 @@ namespace Void::Argparse Parser& positional(std::string_view name, 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& 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 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 parse(int argc, const char* const* argv) const; @@ -70,18 +133,33 @@ namespace Void::Argparse }; struct OptionEntry { std::string lng, sht, desc, def; - std::optional* out_opt; - std::string* out_str; + std::optional* out_opt{nullptr}; + std::string* out_str{nullptr}; + std::vector* out_many{nullptr}; }; struct PosEntry { std::string name, desc; std::string* out; }; + struct MultiPosEntry { + std::string name, desc; + std::vector* out{nullptr}; + bool required{false}; + }; + struct SubcommandEntry { + std::string name; + std::unique_ptr parser; + std::function on_selected; + }; std::string program_, description_; std::vector flags_; std::vector options_; std::vector positionals_; + std::optional positional_many_; + std::vector subcommands_; + bool has_explicit_require_sub_{false}; + bool require_subcommand_{true}; }; // ── reflective options struct @@ -147,6 +225,8 @@ namespace Void::Argparse parser.flag(lng, sht, desc, out.[:m:]); } else if constexpr (Void::Meta::is_optional_v) { parser.option(lng, sht, desc, out.[:m:]); + } else if constexpr (std::same_as>) { + parser.option_many(lng, sht, desc, out.[:m:]); } else if constexpr (std::same_as) { const std::string def = out.[:m:]; parser.option_default(lng, sht, desc, out.[:m:], def); diff --git a/include/Void/Crypto/Crypto.hpp b/include/Void/Crypto/Crypto.hpp index caecfbc..724e3c9 100644 --- a/include/Void/Crypto/Crypto.hpp +++ b/include/Void/Crypto/Crypto.hpp @@ -13,9 +13,14 @@ namespace Void::Crypto { - enum class HashAlgorithm { Sha1, Sha256, Sha512 }; + enum class HashAlgorithm { Sha1, Sha256, Sha512, Blake2b256, Blake2b512 }; using Digest = std::vector; + /// 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 { public: @@ -60,6 +65,11 @@ namespace Void::Crypto [[nodiscard]] Void::Result::Result hashFile(HashAlgorithm algorithm, const std::filesystem::path& path, const ProviderOptions& provider); + [[nodiscard]] Void::Result::Result + hash_file(HashAlgorithm algorithm, const std::filesystem::path& path); + [[nodiscard]] Void::Result::Result + hash_file(HashAlgorithm algorithm, const std::filesystem::path& path, + const ProviderOptions& provider); [[nodiscard]] Void::Result::Result sha1(std::span data); @@ -70,12 +80,29 @@ namespace Void::Crypto [[nodiscard]] Void::Result::Result sha512(std::span data); [[nodiscard]] Void::Result::Result sha512(std::string_view data); + [[nodiscard]] Void::Result::Result + blake2b256(std::span data); + [[nodiscard]] Void::Result::Result blake2b256(std::string_view data); + [[nodiscard]] Void::Result::Result + blake2b512(std::span data); + [[nodiscard]] Void::Result::Result blake2b512(std::string_view data); + [[nodiscard]] Void::Result::Result sha1File(const std::filesystem::path& path); [[nodiscard]] Void::Result::Result sha256File(const std::filesystem::path& path); [[nodiscard]] Void::Result::Result sha512File(const std::filesystem::path& path); + [[nodiscard]] Void::Result::Result + sha1_file(const std::filesystem::path& path); + [[nodiscard]] Void::Result::Result + sha256_file(const std::filesystem::path& path); + [[nodiscard]] Void::Result::Result + sha512_file(const std::filesystem::path& path); + [[nodiscard]] Void::Result::Result + blake2b256_file(const std::filesystem::path& path); + [[nodiscard]] Void::Result::Result + blake2b512_file(const std::filesystem::path& path); /// Move-only owning Ed25519 private key handle. Has no implicit copy, /// string conversion, or secret formatting. diff --git a/include/Void/Crypto/Types.hpp b/include/Void/Crypto/Types.hpp index cd205a4..b78458b 100644 --- a/include/Void/Crypto/Types.hpp +++ b/include/Void/Crypto/Types.hpp @@ -111,10 +111,11 @@ namespace Void::Crypto MovedFrom }; - /// Per-operation OpenSSL 3 provider selection. Never mutates process-wide + /// Per-operation backend/provider selection. Never mutates process-wide /// provider state. struct ProviderOptions { std::string property_query{}; + bool prefer_builtin{false}; }; struct Ed25519PublicKey { diff --git a/include/Void/Data/StrictJson.hpp b/include/Void/Data/StrictJson.hpp index 9172ac7..2f92484 100644 --- a/include/Void/Data/StrictJson.hpp +++ b/include/Void/Data/StrictJson.hpp @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -41,6 +42,72 @@ namespace Void::Json::Strict 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(input[pos]); + if (b0 <= 0x7FU) { + return 1U; + } + if (b0 >= 0xC2U && b0 <= 0xDFU) { + if (pos + 1U >= input.size()) { + return 0U; + } + const auto b1 = static_cast(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(input[pos + 1U]); + const auto b2 = static_cast(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(input[pos + 1U]); + const auto b2 = static_cast(input[pos + 2U]); + const auto b3 = static_cast(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 + 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 { public: @@ -179,6 +246,18 @@ namespace Void::Json::Strict fail("control character in string"); } 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(value)); continue; } @@ -435,4 +514,171 @@ namespace Void::Json::Strict .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 + 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(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(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; + if constexpr (std::same_as) { + out += "null"; + } else if constexpr (std::same_as) { + out += (node ? "true" : "false"); + } else if constexpr (std::same_as) { + std::array 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) { + if (!std::isfinite(node)) { + throw ParseFailure{ + .error = + { + .offset = out.size(), + .message = + "non-finite double is not valid JSON", + }, + }; + } + std::array 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) { + append_escaped_string(out, node); + } else if constexpr (std::same_as) { + 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) { + 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 + 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 diff --git a/include/Void/Data/Toml.hpp b/include/Void/Data/Toml.hpp new file mode 100644 index 0000000..687e225 --- /dev/null +++ b/include/Void/Data/Toml.hpp @@ -0,0 +1,1906 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Data::Toml +{ + struct Origin { + std::size_t line{1}; + std::size_t column{1}; + + [[nodiscard]] constexpr auto + operator<=>(const Origin&) const noexcept = default; + }; + + struct ParseError { + Origin origin{}; + std::string message{}; + }; + + struct Date { + int year{0}; + int month{0}; + int day{0}; + + [[nodiscard]] constexpr bool + operator==(const Date&) const noexcept = default; + }; + + struct Time { + int hour{0}; + int minute{0}; + int second{0}; + std::uint32_t nanosecond{0}; + + [[nodiscard]] constexpr bool + operator==(const Time&) const noexcept = default; + }; + + enum class DateTimeKind : std::uint8_t { + OffsetDateTime, + LocalDateTime, + LocalDate, + LocalTime, + }; + + struct DateTime { + DateTimeKind kind{DateTimeKind::OffsetDateTime}; + Date date{}; + Time time{}; + bool utc{false}; + std::optional offset_minutes{}; + + void append_date_to(std::string& out) const + { + out += std::format("{:04d}-{:02d}-{:02d}", date.year, + date.month, date.day); + } + + void append_time_to(std::string& out) const + { + out += std::format("{:02d}:{:02d}:{:02d}", time.hour, + time.minute, time.second); + if (time.nanosecond != 0U) { + std::string frac = std::format("{:09d}", time.nanosecond); + while (!frac.empty() && frac.back() == '0') { + frac.pop_back(); + } + out.push_back('.'); + out += frac; + } + } + + [[nodiscard]] std::string to_string() const + { + std::string out; + switch (kind) { + case DateTimeKind::LocalDate: + append_date_to(out); + break; + case DateTimeKind::LocalTime: + append_time_to(out); + break; + case DateTimeKind::LocalDateTime: + append_date_to(out); + out.push_back('T'); + append_time_to(out); + break; + case DateTimeKind::OffsetDateTime: + append_date_to(out); + out.push_back('T'); + append_time_to(out); + if (utc) { + out.push_back('Z'); + } else if (offset_minutes.has_value()) { + const int mins = *offset_minutes; + const char sign = mins < 0 ? '-' : '+'; + const int abs_m = mins < 0 ? -mins : mins; + out += std::format("{}{:02d}:{:02d}", sign, + abs_m / 60, abs_m % 60); + } else { + out.push_back('Z'); + } + break; + } + return out; + } + + [[nodiscard]] bool + operator==(const DateTime&) const noexcept = default; + }; + + enum class ValueKind : std::uint8_t { + String, + Boolean, + Integer, + Float, + DateTime, + Array, + Table, + ArrayOfTables, + }; + + struct Value; + + struct Table { + std::map> entries{}; + bool is_inline{false}; + + [[nodiscard]] bool empty() const noexcept; + [[nodiscard]] std::size_t size() const noexcept; + [[nodiscard]] bool contains(std::string_view key) const noexcept; + [[nodiscard]] const Value* find(std::string_view key) const noexcept; + [[nodiscard]] Value* find(std::string_view key) noexcept; + }; + + struct Array { + std::vector elements{}; + + [[nodiscard]] bool empty() const noexcept; + [[nodiscard]] std::size_t size() const noexcept; + [[nodiscard]] const Value& operator[](std::size_t i) const noexcept; + }; + + struct ArrayOfTables { + std::vector tables{}; + + [[nodiscard]] bool empty() const noexcept; + [[nodiscard]] std::size_t size() const noexcept; + }; + + struct Value { + using Storage = + std::variant; + + Storage data{}; + Origin origin{1, 1}; + + Value() = default; + Value(std::string v, Origin o = {}) + : data(std::move(v)), origin(o) + { + } + Value(std::string_view v, Origin o = {}) + : data(std::string{v}), origin(o) + { + } + Value(const char* v, Origin o = {}) + : data(std::string{v}), origin(o) + { + } + Value(bool v, Origin o = {}) : data(v), origin(o) {} + Value(std::int64_t v, Origin o = {}) : data(v), origin(o) {} + Value(int v, Origin o = {}) + : data(static_cast(v)), origin(o) + { + } + Value(double v, Origin o = {}) : data(v), origin(o) {} + Value(DateTime v, Origin o = {}) : data(std::move(v)), origin(o) {} + Value(Array v, Origin o = {}) : data(std::move(v)), origin(o) {} + Value(Table v, Origin o = {}) : data(std::move(v)), origin(o) {} + Value(ArrayOfTables v, Origin o = {}) + : data(std::move(v)), origin(o) + { + } + + [[nodiscard]] ValueKind kind() const noexcept + { + switch (data.index()) { + case 0: return ValueKind::String; + case 1: return ValueKind::Boolean; + case 2: return ValueKind::Integer; + case 3: return ValueKind::Float; + case 4: return ValueKind::DateTime; + case 5: return ValueKind::Array; + case 6: return ValueKind::Table; + case 7: return ValueKind::ArrayOfTables; + default: return ValueKind::String; + } + } + + [[nodiscard]] bool is_string() const noexcept + { + return std::holds_alternative(data); + } + [[nodiscard]] bool is_bool() const noexcept + { + return std::holds_alternative(data); + } + [[nodiscard]] bool is_integer() const noexcept + { + return std::holds_alternative(data); + } + [[nodiscard]] bool is_float() const noexcept + { + return std::holds_alternative(data); + } + [[nodiscard]] bool is_datetime() const noexcept + { + return std::holds_alternative(data); + } + [[nodiscard]] bool is_array() const noexcept + { + return std::holds_alternative(data); + } + [[nodiscard]] bool is_table() const noexcept + { + return std::holds_alternative
(data); + } + [[nodiscard]] bool is_array_of_tables() const noexcept + { + return std::holds_alternative(data); + } + + [[nodiscard]] const std::string* as_string() const noexcept + { + return std::get_if(&data); + } + [[nodiscard]] const bool* as_bool() const noexcept + { + return std::get_if(&data); + } + [[nodiscard]] const std::int64_t* as_integer() const noexcept + { + return std::get_if(&data); + } + [[nodiscard]] const double* as_float() const noexcept + { + return std::get_if(&data); + } + [[nodiscard]] const DateTime* as_datetime() const noexcept + { + return std::get_if(&data); + } + [[nodiscard]] const Array* as_array() const noexcept + { + return std::get_if(&data); + } + [[nodiscard]] const Table* as_table() const noexcept + { + return std::get_if
(&data); + } + [[nodiscard]] const ArrayOfTables* + as_array_of_tables() const noexcept + { + return std::get_if(&data); + } + + [[nodiscard]] Table* as_table() noexcept + { + return std::get_if
(&data); + } + [[nodiscard]] Array* as_array() noexcept + { + return std::get_if(&data); + } + [[nodiscard]] ArrayOfTables* as_array_of_tables() noexcept + { + return std::get_if(&data); + } + }; + + inline bool Table::empty() const noexcept { return entries.empty(); } + inline std::size_t Table::size() const noexcept { return entries.size(); } + inline bool Table::contains(std::string_view key) const noexcept + { + return entries.find(key) != entries.end(); + } + + inline const Value* Table::find(std::string_view key) const noexcept + { + const auto it = entries.find(key); + return it == entries.end() ? nullptr : &it->second; + } + + inline Value* Table::find(std::string_view key) noexcept + { + const auto it = entries.find(key); + return it == entries.end() ? nullptr : &it->second; + } + + inline bool Array::empty() const noexcept { return elements.empty(); } + inline std::size_t Array::size() const noexcept { return elements.size(); } + + inline const Value& Array::operator[](std::size_t i) const noexcept + { + return elements[i]; + } + + inline bool ArrayOfTables::empty() const noexcept { return tables.empty(); } + inline std::size_t ArrayOfTables::size() const noexcept + { + return tables.size(); + } + + struct Document { + Table root{}; + Origin origin{1, 1}; + + [[nodiscard]] const Table& table() const noexcept { return root; } + [[nodiscard]] const Value* find(std::string_view key) const noexcept + { + return root.find(key); + } + [[nodiscard]] bool contains(std::string_view key) const noexcept + { + return root.contains(key); + } + }; + + struct ParseOptions { + std::size_t max_depth{64}; + std::size_t max_input_bytes{16ULL * 1024ULL * 1024ULL}; + }; + + namespace Detail + { + struct Failure { + ParseError error; + }; + + [[nodiscard]] constexpr std::size_t + utf8_seq_len(std::string_view input, std::size_t pos) noexcept + { + if (pos >= input.size()) { + return 0U; + } + const auto b0 = static_cast(input[pos]); + if (b0 <= 0x7FU) { + return 1U; + } + if (b0 >= 0xC2U && b0 <= 0xDFU) { + if (pos + 1U >= input.size()) { + return 0U; + } + const auto b1 = static_cast(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(input[pos + 1U]); + const auto b2 = static_cast(input[pos + 2U]); + const unsigned char lo = (b0 == 0xE0U) ? 0xA0U : 0x80U; + const unsigned char hi = (b0 == 0xEDU) ? 0x9FU : 0xBFU; + return (b1 >= lo && b1 <= hi && b2 >= 0x80U && b2 <= 0xBFU) + ? 3U + : 0U; + } + if (b0 >= 0xF0U && b0 <= 0xF4U) { + if (pos + 3U >= input.size()) { + return 0U; + } + const auto b1 = static_cast(input[pos + 1U]); + const auto b2 = static_cast(input[pos + 2U]); + const auto b3 = static_cast(input[pos + 3U]); + const unsigned char lo = (b0 == 0xF0U) ? 0x90U : 0x80U; + const unsigned char hi = (b0 == 0xF4U) ? 0x8FU : 0xBFU; + return (b1 >= lo && b1 <= hi && b2 >= 0x80U && b2 <= 0xBFU && + b3 >= 0x80U && b3 <= 0xBFU) + ? 4U + : 0U; + } + return 0U; + } + + [[nodiscard]] inline std::optional + validate_document_utf8(std::string_view input) + { + std::size_t line = 1; + std::size_t col = 1; + std::size_t pos = 0; + while (pos < input.size()) { + const std::size_t len = utf8_seq_len(input, pos); + if (len == 0U) { + return ParseError{ + .origin = Origin{line, col}, + .message = "invalid UTF-8 byte sequence in TOML document", + }; + } + if (len == 1U && input[pos] == '\n') { + ++line; + col = 1; + } else { + ++col; + } + pos += len; + } + return std::nullopt; + } + + enum class NodeState : std::uint8_t { + Scalar, + ImplicitTable, + DottedTable, + ExplicitTable, + InlineTable, + ArrayOfTables, + }; + + struct MetaNode { + NodeState state{NodeState::ImplicitTable}; + std::map, std::less<>> + children{}; + std::vector> aot_items{}; + }; + + [[nodiscard]] constexpr bool is_ws(char ch) noexcept + { + return ch == ' ' || ch == '\t'; + } + + [[nodiscard]] constexpr bool is_bare_key_char(char ch) noexcept + { + return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || + (ch >= '0' && ch <= '9') || ch == '_' || ch == '-'; + } + + [[nodiscard]] constexpr bool is_disallowed_control(unsigned char ch, + bool allow_newline) noexcept + { + if (ch == '\t') { + return false; + } + if (allow_newline && ch == '\n') { + return false; + } + return (ch < 0x20U) || (ch == 0x7FU); + } + + [[nodiscard]] constexpr int days_in_month(int year, int month) noexcept + { + constexpr int kDays[12] = {31, 28, 31, 30, 31, 30, + 31, 31, 30, 31, 30, 31}; + if (month < 1 || month > 12) { + return 0; + } + if (month == 2) { + const bool leap = + ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); + return leap ? 29 : 28; + } + return kDays[month - 1]; + } + + inline void append_utf8_scalar(std::string& out, std::uint32_t cp) + { + if (cp <= 0x7FU) { + out.push_back(static_cast(cp)); + } else if (cp <= 0x7FFU) { + out.push_back(static_cast(0xC0U | (cp >> 6U))); + out.push_back(static_cast(0x80U | (cp & 0x3FU))); + } else if (cp <= 0xFFFFU) { + out.push_back(static_cast(0xE0U | (cp >> 12U))); + out.push_back(static_cast(0x80U | ((cp >> 6U) & 0x3FU))); + out.push_back(static_cast(0x80U | (cp & 0x3FU))); + } else { + out.push_back(static_cast(0xF0U | (cp >> 18U))); + out.push_back(static_cast(0x80U | ((cp >> 12U) & 0x3FU))); + out.push_back(static_cast(0x80U | ((cp >> 6U) & 0x3FU))); + out.push_back(static_cast(0x80U | (cp & 0x3FU))); + } + } + + class Parser final + { + public: + + Parser(std::string_view input, ParseOptions options) + : input_(input), options_(options) + { + } + + [[nodiscard]] Document parse() + { + if (input_.size() > options_.max_input_bytes) { + fail("TOML input exceeds max_input_bytes"); + } + if (const auto err = validate_document_utf8(input_)) { + throw Failure{.error = *err}; + } + + Document doc; + root_meta_.state = NodeState::ImplicitTable; + current_table_ = &doc.root; + current_meta_ = &root_meta_; + + while (pos_ < input_.size()) { + skip_ws_and_comments(true); + if (pos_ >= input_.size()) { + break; + } + const char ch = input_[pos_]; + if (ch == '[') { + parse_table_header(doc); + } else { + parse_key_value_into(*current_table_, *current_meta_, + false, 0U); + skip_ws(); + skip_comment_to_eol(); + if (pos_ < input_.size() && !consume_newline()) { + fail("expected newline after key-value assignment"); + } + } + } + return doc; + } + + private: + + [[nodiscard]] Origin here() const noexcept + { + return Origin{line_, column_}; + } + + [[noreturn]] void fail(std::string_view msg, + std::optional at = std::nullopt) const + { + throw Failure{ + .error = + { + .origin = at.value_or(here()), + .message = std::string{msg}, + }, + }; + } + + [[nodiscard]] bool starts_with(std::string_view s) const noexcept + { + return input_.substr(pos_, s.size()) == s; + } + + char advance_byte() noexcept + { + const char ch = input_[pos_++]; + if (ch == '\n') { + ++line_; + column_ = 1; + } else { + const auto uc = static_cast(ch); + if ((uc & 0xC0U) != 0x80U) { + ++column_; + } + } + return ch; + } + + void skip_ws() noexcept + { + while (pos_ < input_.size() && is_ws(input_[pos_])) { + (void)advance_byte(); + } + } + + void skip_comment_to_eol() + { + if (pos_ >= input_.size() || input_[pos_] != '#') { + return; + } + (void)advance_byte(); + while (pos_ < input_.size()) { + const char ch = input_[pos_]; + if (ch == '\n') { + break; + } + if (ch == '\r') { + if (pos_ + 1U < input_.size() && + input_[pos_ + 1U] == '\n') { + break; + } + fail("bare CR is not allowed in comment"); + } + if (is_disallowed_control( + static_cast(ch), false)) { + fail("disallowed control character in comment"); + } + (void)advance_byte(); + } + } + + bool consume_newline() + { + if (pos_ >= input_.size()) { + return false; + } + if (input_[pos_] == '\n') { + (void)advance_byte(); + return true; + } + if (input_[pos_] == '\r') { + if (pos_ + 1U < input_.size() && + input_[pos_ + 1U] == '\n') { + (void)advance_byte(); + (void)advance_byte(); + return true; + } + fail("bare CR without LF is not valid in TOML"); + } + return false; + } + + void skip_ws_and_comments(bool allow_newlines) + { + while (pos_ < input_.size()) { + skip_ws(); + if (allow_newlines) { + skip_comment_to_eol(); + if (consume_newline()) { + continue; + } + } + break; + } + } + + struct KeyPart { + std::string name{}; + Origin origin{}; + }; + + [[nodiscard]] static int hex_val(char ch) noexcept + { + if (ch >= '0' && ch <= '9') return ch - '0'; + if (ch >= 'a' && ch <= 'f') return 10 + (ch - 'a'); + if (ch >= 'A' && ch <= 'F') return 10 + (ch - 'A'); + return -1; + } + + [[nodiscard]] std::uint32_t parse_hex_escape(int digits, + Origin esc_origin) + { + std::uint32_t cp = 0; + for (int i = 0; i < digits; ++i) { + if (pos_ >= input_.size()) { + fail("unterminated unicode escape", esc_origin); + } + const int v = hex_val(advance_byte()); + if (v < 0) { + fail("invalid hexadecimal digit in unicode escape", + esc_origin); + } + cp = (cp << 4U) | static_cast(v); + } + if (cp > 0x10FFFFU || (cp >= 0xD800U && cp <= 0xDFFFU)) { + fail("unicode escape is not a valid scalar value", + esc_origin); + } + return cp; + } + + [[nodiscard]] std::string parse_basic_string(bool allow_multiline) + { + const Origin start = here(); + (void)advance_byte(); // opening '"' + const bool multiline = + allow_multiline && starts_with("\"\""); + if (multiline) { + (void)advance_byte(); + (void)advance_byte(); + // Trim one immediate newline after opening delimiter. + (void)consume_newline(); + } + + std::string out; + while (pos_ < input_.size()) { + const char ch = input_[pos_]; + if (ch == '"') { + if (!multiline) { + (void)advance_byte(); + return out; + } + if (starts_with("\"\"\"")) { + std::size_t qcount = 0; + while (pos_ + qcount < input_.size() && + input_[pos_ + qcount] == '"' && + qcount < 6U) { + ++qcount; + } + if (qcount == 6U) { + fail("too many closing quotes in multiline " + "basic string"); + } + for (std::size_t i = 0; i < qcount; ++i) { + (void)advance_byte(); + } + for (std::size_t i = 0; i < qcount - 3U; ++i) { + out.push_back('"'); + } + return out; + } + out.push_back(advance_byte()); + continue; + } + + if (ch == '\\') { + const Origin esc_origin = here(); + (void)advance_byte(); + if (pos_ >= input_.size()) { + fail("unterminated escape sequence", + esc_origin); + } + const char esc = input_[pos_]; + if (multiline && (is_ws(esc) || esc == '\n' || + esc == '\r')) { + while (pos_ < input_.size() && + is_ws(input_[pos_])) { + (void)advance_byte(); + } + if (!consume_newline()) { + fail("invalid line-ending backslash escape", + esc_origin); + } + while (pos_ < input_.size()) { + if (is_ws(input_[pos_])) { + (void)advance_byte(); + } else if (consume_newline()) { + // continue trimming + } else { + break; + } + } + continue; + } + (void)advance_byte(); + switch (esc) { + case 'b': out.push_back('\b'); break; + case 't': out.push_back('\t'); break; + case 'n': out.push_back('\n'); break; + case 'f': out.push_back('\f'); break; + case 'r': out.push_back('\r'); break; + case '"': out.push_back('"'); break; + case '\\': out.push_back('\\'); break; + case 'u': + append_utf8_scalar( + out, parse_hex_escape(4, esc_origin)); + break; + case 'U': + append_utf8_scalar( + out, parse_hex_escape(8, esc_origin)); + break; + default: + fail("invalid basic string escape sequence", + esc_origin); + } + continue; + } + + if (ch == '\r') { + if (multiline && pos_ + 1U < input_.size() && + input_[pos_ + 1U] == '\n') { + (void)advance_byte(); + (void)advance_byte(); + out.push_back('\n'); + continue; + } + fail("invalid carriage return in string"); + } + if (ch == '\n') { + if (!multiline) { + fail("newline not allowed in single-line basic " + "string", + start); + } + out.push_back(advance_byte()); + continue; + } + if (is_disallowed_control( + static_cast(ch), false)) { + fail("disallowed control character in string"); + } + out.push_back(advance_byte()); + } + fail("unterminated basic string", start); + } + + [[nodiscard]] std::string + parse_literal_string(bool allow_multiline) + { + const Origin start = here(); + (void)advance_byte(); // opening '\'' + const bool multiline = + allow_multiline && starts_with("''"); + if (multiline) { + (void)advance_byte(); + (void)advance_byte(); + (void)consume_newline(); + } + + std::string out; + while (pos_ < input_.size()) { + const char ch = input_[pos_]; + if (ch == '\'') { + if (!multiline) { + (void)advance_byte(); + return out; + } + if (starts_with("'''")) { + std::size_t qcount = 0; + while (pos_ + qcount < input_.size() && + input_[pos_ + qcount] == '\'' && + qcount < 6U) { + ++qcount; + } + if (qcount == 6U) { + fail("too many closing quotes in multiline " + "literal string"); + } + for (std::size_t i = 0; i < qcount; ++i) { + (void)advance_byte(); + } + for (std::size_t i = 0; i < qcount - 3U; ++i) { + out.push_back('\''); + } + return out; + } + out.push_back(advance_byte()); + continue; + } + if (ch == '\r') { + if (multiline && pos_ + 1U < input_.size() && + input_[pos_ + 1U] == '\n') { + (void)advance_byte(); + (void)advance_byte(); + out.push_back('\n'); + continue; + } + fail("invalid carriage return in literal string"); + } + if (ch == '\n') { + if (!multiline) { + fail("newline not allowed in single-line " + "literal string", + start); + } + out.push_back(advance_byte()); + continue; + } + if (is_disallowed_control( + static_cast(ch), false)) { + fail("disallowed control character in literal " + "string"); + } + out.push_back(advance_byte()); + } + fail("unterminated literal string", start); + } + + [[nodiscard]] KeyPart parse_simple_key() + { + const Origin start = here(); + if (pos_ >= input_.size()) { + fail("expected key"); + } + if (input_[pos_] == '"') { + if (starts_with("\"\"\"")) { + fail("multiline strings cannot be keys", start); + } + return KeyPart{parse_basic_string(false), start}; + } + if (input_[pos_] == '\'') { + if (starts_with("'''")) { + fail("multiline literal strings cannot be keys", + start); + } + return KeyPart{parse_literal_string(false), start}; + } + std::string bare; + while (pos_ < input_.size() && + is_bare_key_char(input_[pos_])) { + bare.push_back(advance_byte()); + } + if (bare.empty()) { + fail("expected valid key", start); + } + return KeyPart{std::move(bare), start}; + } + + [[nodiscard]] std::vector parse_key_path() + { + std::vector path; + path.push_back(parse_simple_key()); + while (true) { + skip_ws(); + if (pos_ < input_.size() && input_[pos_] == '.') { + (void)advance_byte(); + skip_ws(); + path.push_back(parse_simple_key()); + } else { + break; + } + } + return path; + } + + void parse_table_header(Document& doc) + { + const Origin hdr_origin = here(); + (void)advance_byte(); // '[' + const bool is_aot = + pos_ < input_.size() && input_[pos_] == '['; + if (is_aot) { + (void)advance_byte(); + } + skip_ws(); + auto path = parse_key_path(); + skip_ws(); + if (pos_ >= input_.size() || input_[pos_] != ']') { + fail("expected ']' closing table header", hdr_origin); + } + (void)advance_byte(); + if (is_aot) { + if (pos_ >= input_.size() || input_[pos_] != ']') { + fail("expected ']]' closing array-of-tables header", + hdr_origin); + } + (void)advance_byte(); + } + skip_ws(); + skip_comment_to_eol(); + if (pos_ < input_.size() && !consume_newline()) { + fail("expected newline after table header"); + } + + Table* cur_tbl = &doc.root; + MetaNode* cur_meta = &root_meta_; + + for (std::size_t i = 0; i + 1U < path.size(); ++i) { + const auto& seg = path[i]; + auto* val = cur_tbl->find(seg.name); + if (val == nullptr) { + auto [it, ok] = cur_tbl->entries.emplace( + seg.name, Value{Table{}, seg.origin}); + static_cast(ok); + auto meta_ptr = std::make_unique(); + meta_ptr->state = NodeState::ImplicitTable; + auto [mit, mok] = cur_meta->children.emplace( + seg.name, std::move(meta_ptr)); + static_cast(mok); + cur_tbl = it->second.as_table(); + cur_meta = mit->second.get(); + } else { + auto mit = cur_meta->children.find(seg.name); + if (mit == cur_meta->children.end()) { + fail("internal metadata mismatch", seg.origin); + } + MetaNode* child_meta = mit->second.get(); + if (child_meta->state == NodeState::ArrayOfTables) { + auto* aot = val->as_array_of_tables(); + cur_tbl = &aot->tables.back(); + cur_meta = child_meta->aot_items.back().get(); + } else if (auto* sub = val->as_table(); + sub != nullptr && + child_meta->state != + NodeState::InlineTable) { + cur_tbl = sub; + cur_meta = child_meta; + } else { + fail(std::format("cannot traverse non-table " + "key '{}'", + seg.name), + seg.origin); + } + } + } + + const auto& leaf = path.back(); + auto* existing = cur_tbl->find(leaf.name); + if (!is_aot) { + if (existing == nullptr) { + auto [it, ok] = cur_tbl->entries.emplace( + leaf.name, Value{Table{}, leaf.origin}); + static_cast(ok); + auto meta_ptr = std::make_unique(); + meta_ptr->state = NodeState::ExplicitTable; + auto [mit, mok] = cur_meta->children.emplace( + leaf.name, std::move(meta_ptr)); + static_cast(mok); + current_table_ = it->second.as_table(); + current_meta_ = mit->second.get(); + return; + } + auto mit = cur_meta->children.find(leaf.name); + MetaNode* leaf_meta = mit->second.get(); + if (leaf_meta->state != NodeState::ImplicitTable) { + fail(std::format("redefinition of table or key " + "'{}'", + leaf.name), + hdr_origin); + } + leaf_meta->state = NodeState::ExplicitTable; + existing->origin = leaf.origin; + current_table_ = existing->as_table(); + current_meta_ = leaf_meta; + } else { + if (existing == nullptr) { + ArrayOfTables aot; + aot.tables.push_back(Table{}); + auto [it, ok] = cur_tbl->entries.emplace( + leaf.name, + Value{std::move(aot), leaf.origin}); + static_cast(ok); + auto meta_ptr = std::make_unique(); + meta_ptr->state = NodeState::ArrayOfTables; + auto elem_meta = std::make_unique(); + elem_meta->state = NodeState::ExplicitTable; + meta_ptr->aot_items.push_back(std::move(elem_meta)); + MetaNode* next_meta = meta_ptr->aot_items.back().get(); + cur_meta->children.emplace(leaf.name, + std::move(meta_ptr)); + current_table_ = + &it->second.as_array_of_tables()->tables.back(); + current_meta_ = next_meta; + return; + } + auto mit = cur_meta->children.find(leaf.name); + MetaNode* leaf_meta = mit->second.get(); + if (leaf_meta->state != NodeState::ArrayOfTables) { + fail(std::format("key '{}' is not an array of " + "tables", + leaf.name), + hdr_origin); + } + auto* aot = existing->as_array_of_tables(); + aot->tables.push_back(Table{}); + auto elem_meta = std::make_unique(); + elem_meta->state = NodeState::ExplicitTable; + leaf_meta->aot_items.push_back(std::move(elem_meta)); + current_table_ = &aot->tables.back(); + current_meta_ = leaf_meta->aot_items.back().get(); + } + } + + void parse_key_value_into(Table& root_tbl, MetaNode& root_meta, + bool in_inline, std::size_t depth) + { + auto path = parse_key_path(); + skip_ws(); + if (pos_ >= input_.size() || input_[pos_] != '=') { + fail("expected '=' after key"); + } + (void)advance_byte(); + skip_ws(); + Value val = parse_value(depth); + + Table* cur_tbl = &root_tbl; + MetaNode* cur_meta = &root_meta; + for (std::size_t i = 0; i + 1U < path.size(); ++i) { + const auto& seg = path[i]; + auto* existing = cur_tbl->find(seg.name); + if (existing == nullptr) { + Table sub; + sub.is_inline = false; + auto [it, ok] = cur_tbl->entries.emplace( + seg.name, Value{std::move(sub), seg.origin}); + static_cast(ok); + auto meta_ptr = std::make_unique(); + meta_ptr->state = NodeState::DottedTable; + auto [mit, mok] = cur_meta->children.emplace( + seg.name, std::move(meta_ptr)); + static_cast(mok); + cur_tbl = it->second.as_table(); + cur_meta = mit->second.get(); + } else { + auto mit = cur_meta->children.find(seg.name); + MetaNode* child_meta = mit->second.get(); + if (!existing->is_table() || + child_meta->state == NodeState::InlineTable || + child_meta->state == NodeState::ExplicitTable) { + fail(std::format("cannot extend '{}' via " + "dotted key", + seg.name), + seg.origin); + } + if (!in_inline && + child_meta->state == NodeState::ImplicitTable) { + child_meta->state = NodeState::DottedTable; + } + cur_tbl = existing->as_table(); + cur_meta = child_meta; + } + } + + const auto& leaf = path.back(); + if (cur_tbl->contains(leaf.name)) { + fail(std::format("duplicate key '{}'", leaf.name), + leaf.origin); + } + NodeState val_state = NodeState::Scalar; + if (val.is_table()) { + val_state = val.as_table()->is_inline + ? NodeState::InlineTable + : NodeState::ExplicitTable; + } + auto meta_ptr = std::make_unique(); + meta_ptr->state = val_state; + cur_meta->children.emplace(leaf.name, std::move(meta_ptr)); + cur_tbl->entries.emplace(leaf.name, std::move(val)); + } + + [[nodiscard]] Value parse_value(std::size_t depth) + { + if (depth > options_.max_depth || pos_ >= input_.size()) { + fail("nesting depth exceeded or unexpected end of input"); + } + const Origin start = here(); + const char ch = input_[pos_]; + if (ch == '"') { + return Value{parse_basic_string(true), start}; + } + if (ch == '\'') { + return Value{parse_literal_string(true), start}; + } + if (ch == '[') { + return parse_array(depth); + } + if (ch == '{') { + return parse_inline_table(depth); + } + return parse_bare_scalar(start); + } + + [[nodiscard]] Value parse_array(std::size_t depth) + { + const Origin start = here(); + (void)advance_byte(); // '[' + Array arr; + while (true) { + skip_ws_and_comments(true); + if (pos_ >= input_.size()) { + fail("unterminated array", start); + } + if (input_[pos_] == ']') { + (void)advance_byte(); + return Value{std::move(arr), start}; + } + arr.elements.push_back(parse_value(depth + 1U)); + skip_ws_and_comments(true); + if (pos_ >= input_.size()) { + fail("unterminated array", start); + } + if (input_[pos_] == ',') { + (void)advance_byte(); + continue; + } + if (input_[pos_] == ']') { + (void)advance_byte(); + return Value{std::move(arr), start}; + } + fail("expected ',' or ']' in array"); + } + } + + [[nodiscard]] Value parse_inline_table(std::size_t depth) + { + const Origin start = here(); + (void)advance_byte(); // '{' + Table tbl; + tbl.is_inline = true; + MetaNode inline_meta; + inline_meta.state = NodeState::InlineTable; + + skip_ws(); + if (pos_ < input_.size() && input_[pos_] == '}') { + (void)advance_byte(); + return Value{std::move(tbl), start}; + } + + while (true) { + skip_ws(); + if (pos_ >= input_.size() || input_[pos_] == '\n' || + input_[pos_] == '\r') { + fail("inline tables must stay on a single line", + start); + } + if (input_[pos_] == '}' || input_[pos_] == ',') { + fail("invalid empty entry or trailing comma in " + "inline table"); + } + parse_key_value_into(tbl, inline_meta, true, + depth + 1U); + skip_ws(); + if (pos_ >= input_.size()) { + fail("unterminated inline table", start); + } + if (input_[pos_] == '}') { + (void)advance_byte(); + return Value{std::move(tbl), start}; + } + if (input_[pos_] != ',') { + fail("expected ',' or '}' in inline table"); + } + (void)advance_byte(); + skip_ws(); + if (pos_ < input_.size() && input_[pos_] == '}') { + fail("trailing comma is not allowed in inline " + "table"); + } + } + } + + [[nodiscard]] static bool + is_token_terminator(char ch) noexcept + { + return is_ws(ch) || ch == '\n' || ch == '\r' || ch == '#' || + ch == ',' || ch == ']' || ch == '}'; + } + + [[nodiscard]] static bool + parse_two_digits(std::string_view sv, std::size_t pos, + int& out) noexcept + { + if (pos + 2U > sv.size()) { + return false; + } + const char a = sv[pos]; + const char b = sv[pos + 1U]; + if (a < '0' || a > '9' || b < '0' || b > '9') { + return false; + } + out = (a - '0') * 10 + (b - '0'); + return true; + } + + [[nodiscard]] static bool + parse_date_prefix(std::string_view sv, Date& d) noexcept + { + if (sv.size() != 10U || sv[4] != '-' || sv[7] != '-') { + return false; + } + for (std::size_t i = 0; i < 4U; ++i) { + if (sv[i] < '0' || sv[i] > '9') { + return false; + } + } + int y = 0; + const auto [ptr, ec] = + std::from_chars(sv.data(), sv.data() + 4U, y); + if (ec != std::errc{} || ptr != sv.data() + 4U) { + return false; + } + int m = 0; + int day = 0; + if (!parse_two_digits(sv, 5U, m) || + !parse_two_digits(sv, 8U, day)) { + return false; + } + const int dim = days_in_month(y, m); + if (dim == 0 || day < 1 || day > dim) { + return false; + } + d = Date{y, m, day}; + return true; + } + + [[nodiscard]] static bool + parse_time_part(std::string_view sv, Time& t, + std::size_t& consumed) noexcept + { + if (sv.size() < 8U || sv[2] != ':' || sv[5] != ':') { + return false; + } + int hh = 0; + int mm = 0; + int ss = 0; + if (!parse_two_digits(sv, 0U, hh) || + !parse_two_digits(sv, 3U, mm) || + !parse_two_digits(sv, 6U, ss)) { + return false; + } + if (hh < 0 || hh > 23 || mm < 0 || mm > 59 || ss < 0 || + ss > 60) { + return false; + } + std::size_t idx = 8U; + std::uint32_t ns = 0; + if (idx < sv.size() && sv[idx] == '.') { + ++idx; + if (idx >= sv.size() || sv[idx] < '0' || + sv[idx] > '9') { + return false; + } + std::uint32_t scale = 100'000'000U; + int digits = 0; + while (idx < sv.size() && sv[idx] >= '0' && + sv[idx] <= '9') { + if (digits < 9) { + ns += static_cast(sv[idx] - '0') * + scale; + scale /= 10U; + ++digits; + } + ++idx; + } + } + t = Time{hh, mm, ss, ns}; + consumed = idx; + return true; + } + + [[nodiscard]] std::optional + try_parse_datetime(std::string_view tok) const noexcept + { + // Local Time only: HH:MM:SS[.fff] + if (tok.size() >= 8U && tok[2] == ':') { + Time t; + std::size_t used = 0; + if (parse_time_part(tok, t, used) && + used == tok.size()) { + return DateTime{ + .kind = DateTimeKind::LocalTime, + .time = t, + }; + } + return std::nullopt; + } + + // Date prefix YYYY-MM-DD + if (tok.size() < 10U) { + return std::nullopt; + } + Date d; + if (!parse_date_prefix(tok.substr(0, 10U), d)) { + return std::nullopt; + } + if (tok.size() == 10U) { + return DateTime{ + .kind = DateTimeKind::LocalDate, + .date = d, + }; + } + const char sep = tok[10U]; + if (sep != 'T' && sep != 't' && sep != ' ') { + return std::nullopt; + } + Time t; + std::size_t t_len = 0; + if (!parse_time_part(tok.substr(11U), t, t_len)) { + return std::nullopt; + } + const std::size_t rem_pos = 11U + t_len; + if (rem_pos == tok.size()) { + return DateTime{ + .kind = DateTimeKind::LocalDateTime, + .date = d, + .time = t, + }; + } + const std::string_view off = tok.substr(rem_pos); + if (off == "Z" || off == "z") { + return DateTime{ + .kind = DateTimeKind::OffsetDateTime, + .date = d, + .time = t, + .utc = true, + .offset_minutes = 0, + }; + } + if (off.size() == 6U && (off[0] == '+' || off[0] == '-') && + off[3] == ':') { + int oh = 0; + int om = 0; + if (!parse_two_digits(off, 1U, oh) || + !parse_two_digits(off, 4U, om) || oh > 23 || + om > 59) { + return std::nullopt; + } + const int total = + (off[0] == '-' ? -1 : 1) * (oh * 60 + om); + return DateTime{ + .kind = DateTimeKind::OffsetDateTime, + .date = d, + .time = t, + .utc = false, + .offset_minutes = total, + }; + } + return std::nullopt; + } + + [[nodiscard]] static bool validate_underscores( + std::string_view digits, bool allow_hex) noexcept + { + if (digits.empty()) { + return false; + } + auto is_dig = [&](char c) { + if (c >= '0' && c <= '9') return true; + return allow_hex && ((c >= 'a' && c <= 'f') || + (c >= 'A' && c <= 'F')); + }; + if (!is_dig(digits.front()) || !is_dig(digits.back())) { + return false; + } + bool prev_underscore = false; + for (char c : digits) { + if (c == '_') { + if (prev_underscore) { + return false; + } + prev_underscore = true; + } else if (is_dig(c)) { + prev_underscore = false; + } else { + return false; + } + } + return true; + } + + [[nodiscard]] static std::string + strip_underscores(std::string_view s) + { + std::string out; + out.reserve(s.size()); + for (char c : s) { + if (c != '_') { + out.push_back(c); + } + } + return out; + } + + [[nodiscard]] Value parse_bare_scalar(Origin start) + { + const std::size_t tok_begin = pos_; + while (pos_ < input_.size() && + !is_token_terminator(input_[pos_])) { + (void)advance_byte(); + } + // TOML 1.0 permits a single space separating YYYY-MM-DD + // and HH:MM:SS in DateTime values. + if (pos_ - tok_begin == 10U && pos_ + 2U < input_.size() && + input_[pos_] == ' ' && input_[pos_ + 1U] >= '0' && + input_[pos_ + 1U] <= '9') { + Date dummy_d; + if (parse_date_prefix( + input_.substr(tok_begin, 10U), dummy_d)) { + const std::size_t save_pos = pos_; + const std::size_t save_line = line_; + const std::size_t save_col = column_; + (void)advance_byte(); // ' ' + while (pos_ < input_.size() && + !is_token_terminator(input_[pos_])) { + (void)advance_byte(); + } + const std::string_view cand = input_.substr( + tok_begin, pos_ - tok_begin); + if (const auto dt = try_parse_datetime(cand)) { + return Value{*dt, start}; + } + pos_ = save_pos; + line_ = save_line; + column_ = save_col; + } + } + + const std::string_view tok = + input_.substr(tok_begin, pos_ - tok_begin); + if (tok.empty()) { + fail("expected value", start); + } + if (tok == "true") { + return Value{true, start}; + } + if (tok == "false") { + return Value{false, start}; + } + if (tok == "inf" || tok == "+inf") { + return Value{std::numeric_limits::infinity(), + start}; + } + if (tok == "-inf") { + return Value{-std::numeric_limits::infinity(), + start}; + } + if (tok == "nan" || tok == "+nan") { + return Value{std::numeric_limits::quiet_NaN(), + start}; + } + if (tok == "-nan") { + return Value{-std::numeric_limits::quiet_NaN(), + start}; + } + + if (const auto dt = try_parse_datetime(tok)) { + return Value{*dt, start}; + } + + // Look for date/time mistakes vs numbers. + if (tok.find(':') != std::string_view::npos) { + fail("invalid date-time or time literal", start); + } + + // Based integer prefixes: 0x / 0o / 0b (no leading sign) + if (tok.size() >= 2U && tok[0] == '0' && + (tok[1] == 'x' || tok[1] == 'o' || tok[1] == 'b')) { + const int base = + (tok[1] == 'x') ? 16 : ((tok[1] == 'o') ? 8 : 2); + const std::string_view digits = tok.substr(2U); + if (!validate_underscores(digits, base == 16)) { + fail("invalid based integer literal", start); + } + if (base == 8) { + for (char c : digits) { + if (c != '_' && (c < '0' || c > '7')) { + fail("invalid octal digit", start); + } + } + } else if (base == 2) { + for (char c : digits) { + if (c != '_' && c != '0' && c != '1') { + fail("invalid binary digit", start); + } + } + } + const std::string cleaned = strip_underscores(digits); + std::uint64_t uval = 0; + const auto [ptr, ec] = std::from_chars( + cleaned.data(), cleaned.data() + cleaned.size(), + uval, base); + if (ec != std::errc{} || + ptr != cleaned.data() + cleaned.size() || + uval > static_cast( + std::numeric_limits::max())) { + fail("integer literal out of 64-bit signed range", + start); + } + return Value{static_cast(uval), start}; + } + + // Signed decimal integer or float + const bool has_dot = + tok.find('.') != std::string_view::npos; + const bool has_exp = + tok.find('e') != std::string_view::npos || + tok.find('E') != std::string_view::npos; + + if (!has_dot && !has_exp) { + if (tok.find('-') != std::string_view::npos && + tok.find('-', 1) != std::string_view::npos) { + fail("invalid integer or date literal", start); + } + std::string_view body = tok; + bool negative = false; + if (body.front() == '+' || body.front() == '-') { + negative = (body.front() == '-'); + body.remove_prefix(1U); + } + if (!validate_underscores(body, false)) { + fail("invalid integer literal", start); + } + if (body.size() > 1U && body.front() == '0') { + fail("leading zeros are not allowed in TOML " + "integers", + start); + } + const std::string cleaned = + (negative ? "-" : "") + strip_underscores(body); + std::int64_t ival = 0; + const auto [ptr, ec] = std::from_chars( + cleaned.data(), cleaned.data() + cleaned.size(), + ival, 10); + if (ec != std::errc{} || + ptr != cleaned.data() + cleaned.size()) { + fail("integer literal out of int64 range", start); + } + return Value{ival, start}; + } + + // Float: [+/-] int (. frac)? ([eE] [+/-]? exp)? + std::string_view rest = tok; + std::string clean_float; + if (rest.front() == '+' || rest.front() == '-') { + if (rest.front() == '-') { + clean_float.push_back('-'); + } + rest.remove_prefix(1U); + } + const std::size_t dot_pos = rest.find('.'); + const std::size_t exp_pos = rest.find_first_of("eE"); + if (dot_pos != std::string_view::npos && + exp_pos != std::string_view::npos && exp_pos < dot_pos) { + fail("decimal point cannot follow exponent in float", + start); + } + const std::size_t int_end = + dot_pos != std::string_view::npos ? dot_pos : exp_pos; + const std::string_view int_part = + rest.substr(0, int_end); + if (!validate_underscores(int_part, false)) { + fail("invalid float integer part", start); + } + if (int_part.size() > 1U && int_part.front() == '0') { + fail("leading zero in float integer part", start); + } + clean_float += strip_underscores(int_part); + + if (dot_pos != std::string_view::npos) { + const std::string_view frac = + exp_pos == std::string_view::npos + ? rest.substr(dot_pos + 1U) + : rest.substr(dot_pos + 1U, + exp_pos - dot_pos - 1U); + if (!validate_underscores(frac, false)) { + fail("invalid float fractional part", start); + } + clean_float.push_back('.'); + clean_float += strip_underscores(frac); + } + if (exp_pos != std::string_view::npos) { + std::string_view exp_part = rest.substr(exp_pos + 1U); + clean_float.push_back('e'); + if (!exp_part.empty() && + (exp_part.front() == '+' || + exp_part.front() == '-')) { + clean_float.push_back(exp_part.front()); + exp_part.remove_prefix(1U); + } + if (!validate_underscores(exp_part, false)) { + fail("invalid float exponent", start); + } + clean_float += strip_underscores(exp_part); + } + + double dval = 0.0; + const auto [ptr, ec] = std::from_chars( + clean_float.data(), + clean_float.data() + clean_float.size(), dval, + std::chars_format::general); + if (ec != std::errc{} || + ptr != clean_float.data() + clean_float.size()) { + fail("invalid or out-of-range float literal", start); + } + return Value{dval, start}; + } + + std::string_view input_; + ParseOptions options_; + std::size_t pos_{0}; + std::size_t line_{1}; + std::size_t column_{1}; + MetaNode root_meta_{}; + Table* current_table_{nullptr}; + MetaNode* current_meta_{nullptr}; + }; + + inline void append_escaped_basic(std::string& out, std::string_view s) + { + out.push_back('"'); + for (const char raw : s) { + const auto ch = static_cast(raw); + switch (ch) { + case '"': out += "\\\""; break; + case '\\': out += "\\\\"; break; + case '\b': out += "\\b"; break; + case '\f': out += "\\f"; break; + case '\n': out += "\\n"; break; + case '\r': out += "\\r"; break; + case '\t': out += "\\t"; break; + default: + if (ch < 0x20U || ch == 0x7FU) { + static constexpr char kHex[] = "0123456789abcdef"; + out += "\\u00"; + out.push_back(kHex[(ch >> 4U) & 0x0FU]); + out.push_back(kHex[ch & 0x0FU]); + } else { + out.push_back(raw); + } + break; + } + } + out.push_back('"'); + } + + inline void append_key(std::string& out, std::string_view key) + { + const bool bare = !key.empty() && + std::all_of(key.begin(), key.end(), [](char ch) { + return is_bare_key_char(ch); + }); + if (bare) { + out += key; + } else { + append_escaped_basic(out, key); + } + } + + inline void serialize_inline_value(std::string& out, const Value& v); + + inline void serialize_inline_table(std::string& out, const Table& t) + { + if (t.entries.empty()) { + out += "{}"; + return; + } + out += "{ "; + bool first = true; + for (const auto& [k, v] : t.entries) { + if (!first) { + out += ", "; + } + first = false; + append_key(out, k); + out += " = "; + serialize_inline_value(out, v); + } + out += " }"; + } + + inline void serialize_inline_value(std::string& out, const Value& v) + { + switch (v.kind()) { + case ValueKind::String: + append_escaped_basic(out, *v.as_string()); + break; + case ValueKind::Boolean: + out += (*v.as_bool() ? "true" : "false"); + break; + case ValueKind::Integer: { + std::array buf{}; + const auto [ptr, ec] = std::to_chars( + buf.data(), buf.data() + buf.size(), *v.as_integer()); + static_cast(ec); + out.append(buf.data(), ptr); + break; + } + case ValueKind::Float: { + const double d = *v.as_float(); + if (std::isnan(d)) { + out += std::signbit(d) ? "-nan" : "nan"; + } else if (std::isinf(d)) { + out += std::signbit(d) ? "-inf" : "inf"; + } else { + std::array buf{}; + const auto [ptr, ec] = std::to_chars( + buf.data(), buf.data() + buf.size(), d, + std::chars_format::general); + static_cast(ec); + const std::string_view repr{buf.data(), ptr}; + out += repr; + if (repr.find('.') == std::string_view::npos && + repr.find('e') == std::string_view::npos && + repr.find('E') == std::string_view::npos) { + out += ".0"; + } + } + break; + } + case ValueKind::DateTime: + out += v.as_datetime()->to_string(); + break; + case ValueKind::Array: { + const auto& arr = *v.as_array(); + out.push_back('['); + for (std::size_t i = 0; i < arr.elements.size(); ++i) { + if (i > 0U) { + out += ", "; + } + serialize_inline_value(out, arr.elements[i]); + } + out.push_back(']'); + break; + } + case ValueKind::Table: + serialize_inline_table(out, *v.as_table()); + break; + case ValueKind::ArrayOfTables: { + const auto& aot = *v.as_array_of_tables(); + out.push_back('['); + for (std::size_t i = 0; i < aot.tables.size(); ++i) { + if (i > 0U) { + out += ", "; + } + serialize_inline_table(out, aot.tables[i]); + } + out.push_back(']'); + break; + } + } + } + + inline void append_dotted_prefix(std::string& out, + const std::vector& path) + { + for (std::size_t i = 0; i < path.size(); ++i) { + if (i > 0U) { + out.push_back('.'); + } + append_key(out, path[i]); + } + } + + inline void serialize_table_body(std::string& out, const Table& table, + std::vector& prefix) + { + for (const auto& [k, v] : table.entries) { + if (v.kind() == ValueKind::ArrayOfTables || + (v.kind() == ValueKind::Table && + !v.as_table()->is_inline)) { + continue; + } + append_key(out, k); + out += " = "; + serialize_inline_value(out, v); + out.push_back('\n'); + } + + for (const auto& [k, v] : table.entries) { + if (v.kind() == ValueKind::Table && !v.as_table()->is_inline) { + prefix.push_back(k); + if (!out.empty() && out.back() != '\n') { + out.push_back('\n'); + } + if (!out.empty()) { + out.push_back('\n'); + } + out.push_back('['); + append_dotted_prefix(out, prefix); + out += "]\n"; + serialize_table_body(out, *v.as_table(), prefix); + prefix.pop_back(); + } else if (v.kind() == ValueKind::ArrayOfTables) { + prefix.push_back(k); + for (const auto& elem : v.as_array_of_tables()->tables) { + if (!out.empty()) { + out.push_back('\n'); + } + out += "[["; + append_dotted_prefix(out, prefix); + out += "]]\n"; + serialize_table_body(out, elem, prefix); + } + prefix.pop_back(); + } + } + } + } // namespace Detail + + [[nodiscard]] inline std::expected + parse(std::string_view input, ParseOptions options = {}) + { + try { + return Detail::Parser{input, options}.parse(); + } catch (const Detail::Failure& failure) { + return std::unexpected{failure.error}; + } + } + + [[nodiscard]] inline std::string serialize_table(const Table& table) + { + std::string out; + std::vector prefix; + Detail::serialize_table_body(out, table, prefix); + return out; + } + + [[nodiscard]] inline std::string serialize(const Document& doc) + { + return serialize_table(doc.root); + } + +} // namespace Void::Data::Toml + +namespace Void::Toml +{ + using namespace Void::Data::Toml; +} // namespace Void::Toml \ No newline at end of file diff --git a/include/Void/Functional/Error.hpp b/include/Void/Functional/Error.hpp index 2908cac..045fb3b 100644 --- a/include/Void/Functional/Error.hpp +++ b/include/Void/Functional/Error.hpp @@ -75,6 +75,7 @@ namespace Void::Result inline constexpr std::uint32_t kPluginErrorDomain = 23; inline constexpr std::uint32_t kConfigurationErrorDomain = 24; inline constexpr std::uint32_t kFsmErrorDomain = 25; + inline constexpr std::uint32_t kNetErrorDomain = 26; struct ErrorCode { std::uint32_t domain{kGenericErrorDomain}; diff --git a/include/Void/Net/Http.hpp b/include/Void/Net/Http.hpp index 7fe1b30..293c909 100644 --- a/include/Void/Net/Http.hpp +++ b/include/Void/Net/Http.hpp @@ -4,13 +4,79 @@ #include #include +#include #include +#include +#include #include +#include +#include #include +#include +#include #include 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(code)}, + sys_err}; + } 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 total_bytes{}; + }; + + struct DownloadOptions { + std::vector
headers{}; + std::chrono::seconds timeout{30}; + std::uint64_t max_bytes{0}; + std::stop_token stop{}; + std::function)> on_chunk{}; + std::function on_progress{}; + }; + + struct DownloadResult { + std::uint16_t status{0}; + std::vector
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 + header(std::string_view name) const; + }; + + struct UploadOptions { + Method method{Method::Put}; + std::vector
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 on_progress{}; + }; + /// Synchronous HTTP/HTTPS client built on Boost.Beast/Asio + OpenSSL. /// Supports direct connections, HTTP-CONNECT and SOCKS5 proxies, and TLS. /// Generic: no application-specific defaults beyond a configurable @@ -73,6 +187,12 @@ namespace Void::Net HttpClient() = default; 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); } [[nodiscard]] const ProxyConfig& proxy() const noexcept @@ -83,9 +203,33 @@ namespace Void::Net /// Default User-Agent applied when a request sets none. void set_user_agent(std::string ua) { m_user_agent = std::move(ua); } - /// Verify TLS peer certificates (default: false, matching common - /// scraping/proxy use; enable for security-sensitive callers). + /// Verify TLS peer certificates (default constructor keeps `false` + /// for 1.x compatibility; `HttpClient::secure()` defaults `true`). 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 /// 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. 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; /// the client-level proxy applies. Returns an Error only on transport /// failure — a non-2xx HTTP response is a successful Result. [[nodiscard]] Void::Result::Result 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 + 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 + upload_file(std::string_view url, + const std::filesystem::path& source_path, + const UploadOptions& options = {}) const; + // Convenience wrappers. [[nodiscard]] Void::Result::Result get(std::string_view url, @@ -113,14 +279,28 @@ namespace Void::Net [[nodiscard]] Void::Result::Result post(std::string_view url, std::string body, std::vector
headers = {}) const; + [[nodiscard]] Void::Result::Result + put_file(std::string_view url, + const std::filesystem::path& source_path, + std::vector
headers = {}, + std::string content_type = + "application/octet-stream") const; + [[nodiscard]] Void::Result::Result + post_file(std::string_view url, + const std::filesystem::path& source_path, + std::vector
headers = {}, + std::string content_type = + "application/octet-stream") const; private: ProxyConfig m_proxy{}; std::string m_user_agent = "Void.Net/1.0"; bool m_verify_tls = false; + std::string m_ca_file{}; std::uint64_t m_max_body = 64ull * 1024 * 1024; int m_max_redirects = 0; + bool m_allow_insecure_redirects = false; }; } // namespace Void::Net diff --git a/include/Void/Net/HttpServer.hpp b/include/Void/Net/HttpServer.hpp new file mode 100644 index 0000000..e97c43d --- /dev/null +++ b/include/Void/Net/HttpServer.hpp @@ -0,0 +1,108 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 + 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 + read_some(std::span dst); + + /// Stream the request body atomically to `destination`, enforcing + /// `max_bytes` (or server max_streaming_body_bytes when 0). + [[nodiscard]] Void::Result::Result + read_to_file(const std::filesystem::path& destination, + std::uint64_t max_bytes = 0); + + private: + + State* m_state{nullptr}; + }; + + using StreamingRouteHandler = + std::function; + + /// 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 + add_route(Method method, std::string pattern, + RouteHandler handler); + + [[nodiscard]] Void::Result::Result + add_streaming_route(Method method, std::string pattern, + StreamingRouteHandler handler); + + [[nodiscard]] Void::Result::Result 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 m_impl; + }; + +} // namespace Void::Net diff --git a/include/Void/Net/Server.hpp b/include/Void/Net/Server.hpp index 7120b30..993f3aa 100644 --- a/include/Void/Net/Server.hpp +++ b/include/Void/Net/Server.hpp @@ -30,6 +30,7 @@ namespace Void::Net std::vector
headers; std::string body; RouteParameters parameters; + std::string query{}; [[nodiscard]] std::optional header(std::string_view name) const noexcept; @@ -39,6 +40,12 @@ namespace Void::Net std::uint16_t status{200}; std::vector
headers; std::string body; + std::optional file_body{}; + + [[nodiscard]] static ServerResponse + from_file(std::filesystem::path path, + std::string content_type = {}, + std::uint16_t status = 200); [[nodiscard]] std::optional header(std::string_view name) const noexcept; @@ -67,6 +74,9 @@ namespace Void::Net [[nodiscard]] Void::Result::Result> dispatch(ServerRequest request) const; + [[nodiscard]] std::vector + allowed_methods(std::string_view path) const; + [[nodiscard]] std::size_t size() const; private: diff --git a/include/Void/System/DirectoryWatcher.hpp b/include/Void/System/DirectoryWatcher.hpp new file mode 100644 index 0000000..06297f6 --- /dev/null +++ b/include/Void/System/DirectoryWatcher.hpp @@ -0,0 +1,90 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +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; + +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 + create(const std::filesystem::path& root, + DirectoryWatcherOptions options = {}); + + [[nodiscard]] Void::Result::Result, + 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 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_{}; + + explicit DirectoryWatcher(std::unique_ptr impl) noexcept; +}; + +} // namespace Void::FileSystem \ No newline at end of file diff --git a/include/Void/System/Path.hpp b/include/Void/System/Path.hpp index 4627bf2..a9d82ec 100644 --- a/include/Void/System/Path.hpp +++ b/include/Void/System/Path.hpp @@ -24,10 +24,17 @@ #ifndef _WIN32 #include +#include +#include #include +#include +#include #include #if defined(__linux__) #include +#if __has_include() +#include +#endif #endif #endif @@ -548,4 +555,589 @@ namespace detail 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 + 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, + 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, + 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{std::move(fd), mode}}; + } + const int err = errno; + if (err == EINTR) { + continue; + } + if (nonblocking && (err == EWOULDBLOCK || err == EAGAIN)) { + return std::optional{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 + 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 + 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(src_st.st_mode & 0777) + : static_cast(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(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 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(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(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 + 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(atime_sec); + ts[0].tv_nsec = static_cast(atime_nsec); + ts[1].tv_sec = static_cast(mtime_sec); + ts[1].tv_nsec = static_cast(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 + 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 + 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 diff --git a/include/Void/System/Process.hpp b/include/Void/System/Process.hpp index 626e4d1..275f8d5 100644 --- a/include/Void/System/Process.hpp +++ b/include/Void/System/Process.hpp @@ -116,6 +116,7 @@ public: [[nodiscard]] bool valid() const noexcept; [[nodiscard]] bool running() const noexcept; + [[nodiscard]] bool process_group_alive() const noexcept; [[nodiscard]] long long pid() const noexcept; [[nodiscard]] long long pgid() const noexcept; [[nodiscard]] bool owns_process_group() const noexcept; @@ -201,4 +202,10 @@ private: const std::vector& arguments, 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 + enable_subreaper() noexcept; + } // namespace Void::Process diff --git a/include/Void/Testing/Test.hpp b/include/Void/Testing/Test.hpp index 28c0544..42e6b15 100644 --- a/include/Void/Testing/Test.hpp +++ b/include/Void/Testing/Test.hpp @@ -1,10 +1,190 @@ #pragma once -namespace Void::Testing { +#include +#include -// Aliases to void so users can omit return statements safely -// and avoid compiler warnings/errors. Perfectly matches std::function. -using Test = void; -using DisabledTest = void; +#include +#include +#include +#include +#include + +namespace Void::Testing +{ + + // Aliases to void so users can omit return statements safely + // and avoid compiler warnings/errors. Perfectly matches + // std::function. + 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 tags = {}, + bool disabled = false, + std::string_view skip_reason = {}) + { + std::vector 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 class NativeFixtureRegistrar final + { + public: + + NativeFixtureRegistrar(void (*fn)(FixtureT&), + std::string_view suite, + const char* file, int line, + std::string_view name, + std::initializer_list tags = {}, + bool disabled = false, + std::string_view skip_reason = {}) + { + std::vector 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 + +#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) diff --git a/include/Void/Text/Semver.hpp b/include/Void/Text/Semver.hpp index fd4862d..5797ca1 100644 --- a/include/Void/Text/Semver.hpp +++ b/include/Void/Text/Semver.hpp @@ -438,6 +438,54 @@ namespace Void::Semver using Clause = std::vector; std::vector m_alternatives; + struct PartialVersion { + Version version{}; + int components{0}; + }; + + [[nodiscard]] static std::optional + 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, std::string_view token) { @@ -447,53 +495,76 @@ namespace Void::Semver if (token.starts_with('^') || token.starts_with('~')) { const char kind = token.front(); token.remove_prefix(1); - const auto lower = parse_strict(token); - if (!lower) { + const auto partial = parse_partial(token); + if (!partial) { return false; } + const Version& lower = partial->version; Version upper; if (kind == '~') { - if (lower->minor == + if (partial->components == 1) { + if (lower.major == + std::numeric_limits::max()) { + return false; + } + upper = Version{.major = lower.major + 1, + .minor = 0, + .patch = 0, + .pre_release = {}, + .build = {}}; + } else { + if (lower.minor == + std::numeric_limits::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::max()) { return false; } - upper = Version{.major = lower->major, - .minor = lower->minor + 1, - .patch = 0, - .pre_release = {}, - .build = {}}; - } else if (lower->major > 0) { - if (lower->major == - std::numeric_limits::max()) { - return false; - } - upper = Version{.major = lower->major + 1, + upper = Version{.major = lower.major + 1, .minor = 0, .patch = 0, .pre_release = {}, .build = {}}; - } else if (lower->minor > 0) { - if (lower->minor == + } else if (lower.major > 0) { + if (lower.major == + std::numeric_limits::max()) { + return false; + } + upper = Version{.major = lower.major + 1, + .minor = 0, + .patch = 0, + .pre_release = {}, + .build = {}}; + } else if (lower.minor > 0) { + if (lower.minor == std::numeric_limits::max()) { return false; } upper = Version{.major = 0, - .minor = lower->minor + 1, + .minor = lower.minor + 1, .patch = 0, .pre_release = {}, .build = {}}; } else { - if (lower->patch == + if (lower.patch == std::numeric_limits::max()) { return false; } upper = Version{.major = 0, .minor = 0, - .patch = lower->patch + 1, + .patch = lower.patch + 1, .pre_release = {}, .build = {}}; } - clause.push_back({Operation::GreaterEqual, *lower}); + clause.push_back({Operation::GreaterEqual, lower}); clause.push_back({Operation::Less, std::move(upper)}); return true; } @@ -518,11 +589,11 @@ namespace Void::Semver } else if (token.starts_with('=')) { token.remove_prefix(1); } - const auto version = parse_strict(token); - if (!version) { + const auto partial = parse_partial(token); + if (!partial) { return false; } - clause.push_back({operation, *version}); + clause.push_back({operation, partial->version}); return true; } diff --git a/src/Archive/Archive.cpp b/src/Archive/Archive.cpp index db8ac61..3c41dfc 100644 --- a/src/Archive/Archive.cpp +++ b/src/Archive/Archive.cpp @@ -1,10 +1,13 @@ #include +#include "BuiltinTar.hpp" + #include #include #include #include #include +#include #include #include #include @@ -13,8 +16,10 @@ #include #include +#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE #include #include +#endif #ifndef _WIN32 #include @@ -28,6 +33,7 @@ namespace Void::Archive { namespace { +#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE using ArchiveHandle = std::unique_ptr; @@ -39,6 +45,7 @@ namespace Void::Archive "Archive::extract: {}: {}", operation, message == nullptr ? "unknown archive error" : message)}; } +#endif [[nodiscard]] std::optional safe_relative_path(std::string_view rawPath, bool directory) @@ -225,12 +232,14 @@ namespace Void::Archive return {}; } + template [[nodiscard]] Void::Result::Result - extract_regular(archive *reader, int rootDescriptor, - const std::filesystem::path &relative, - const std::filesystem::path &displayRoot, - const ExtractionOptions &options, - std::uint64_t alreadyExtracted, bool executable) + extract_regular_stream(int rootDescriptor, + const std::filesystem::path &relative, + const std::filesystem::path &displayRoot, + const ExtractionOptions &options, + std::uint64_t alreadyExtracted, + bool executable, ReadFn &&read_fn) { auto openedParent = open_parent_directory( rootDescriptor, relative.parent_path(), displayRoot); @@ -286,15 +295,14 @@ namespace Void::Archive std::array buffer{}; std::uint64_t fileBytes = 0; for (;;) { - const auto count = - archive_read_data(reader, buffer.data(), buffer.size()); - if (count == 0) { + auto chunk = read_fn(std::span{buffer}); + if (!chunk.has_value()) { + return fail(chunk.error().message()); + } + if (*chunk == 0) { break; } - if (count < 0) { - return fail(archive_error(reader, "read entry").message()); - } - const auto amount = static_cast(count); + const auto amount = static_cast(*chunk); if (amount > options.maxFileBytes - fileBytes || amount > options.maxTotalBytes - alreadyExtracted - fileBytes) { @@ -303,11 +311,11 @@ namespace Void::Archive } std::size_t written = 0; - while (written < static_cast(count)) { + while (written < *chunk) { const auto result = ::write( descriptor.get(), reinterpret_cast(buffer.data()) + written, - static_cast(count) - written); + *chunk - written); if (result < 0 && errno == EINTR) { continue; } @@ -448,10 +456,12 @@ namespace Void::Archive return {}; } + template [[nodiscard]] Void::Result::Result - extract_regular(archive *reader, const std::filesystem::path &path, - const ExtractionOptions &options, - std::uint64_t alreadyExtracted) + extract_regular_stream(const std::filesystem::path &path, + const ExtractionOptions &options, + std::uint64_t alreadyExtracted, + ReadFn &&read_fn) { std::error_code error; const auto status = std::filesystem::symlink_status(path, error); @@ -486,15 +496,14 @@ namespace Void::Archive std::array buffer{}; std::uint64_t fileBytes = 0; for (;;) { - const auto count = - archive_read_data(reader, buffer.data(), buffer.size()); - if (count == 0) { + auto chunk = read_fn(std::span{buffer}); + if (!chunk.has_value()) { + return fail(chunk.error().message()); + } + if (*chunk == 0) { break; } - if (count < 0) { - return fail(archive_error(reader, "read entry").message()); - } - const auto amount = static_cast(count); + const auto amount = static_cast(*chunk); if (amount > options.maxFileBytes - fileBytes || amount > options.maxTotalBytes - alreadyExtracted - fileBytes) { @@ -502,7 +511,7 @@ namespace Void::Archive "Archive::extract: extracted size exceeds policy"); } output.write(reinterpret_cast(buffer.data()), - count); + static_cast(*chunk)); if (!output) { return fail("Archive::extract: write failed"); } @@ -544,11 +553,13 @@ namespace Void::Archive } #endif +#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE ArchiveHandle reader{archive_read_new(), &archive_read_free}; if (!reader) { return Void::Result::fail( "Archive::extract: cannot allocate archive reader"); } + archive_read_support_filter_gzip(reader.get()); archive_read_support_filter_zstd(reader.get()); archive_read_support_filter_none(reader.get()); archive_read_support_format_tar(reader.get()); @@ -633,14 +644,23 @@ namespace Void::Archive return Void::Result::fail( "Archive::extract: declared entry size exceeds policy"); } + auto read_libarchive_chunk = + [&](std::span dst) -> Void::Result::Result { + 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(count); + }; #ifndef _WIN32 const bool executable = (archive_entry_perm(entry) & 0111) != 0; - auto extracted = - extract_regular(reader.get(), root->get(), *relative, - destination, options, result.bytes, executable); + auto extracted = extract_regular_stream( + root->get(), *relative, destination, options, result.bytes, + executable, read_libarchive_chunk); #else - auto extracted = - extract_regular(reader.get(), output, options, result.bytes); + auto extracted = extract_regular_stream( + output, options, result.bytes, read_libarchive_chunk); #endif if (!extracted) { return std::unexpected{extracted.error()}; @@ -648,5 +668,103 @@ namespace Void::Archive result.bytes += *extracted; } 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::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 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 dst) -> Void::Result::Result { + 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 diff --git a/src/Archive/BuiltinTar.cpp b/src/Archive/BuiltinTar.cpp new file mode 100644 index 0000000..979f9ff --- /dev/null +++ b/src/Archive/BuiltinTar.cpp @@ -0,0 +1,867 @@ +#include "BuiltinTar.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef _WIN32 +#include +#endif + +namespace Void::Archive::Detail +{ + namespace + { + constexpr std::size_t kTarBlockSize = 512; + + [[nodiscard]] bool is_zero_block(const std::array& block) noexcept + { + for (const std::byte b : block) { + if (b != std::byte{0}) { + return false; + } + } + return true; + } + + inline void write_octal(std::span 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('0' + (value & 7ULL)); + value >>= 3ULL; + } + } + + [[nodiscard]] Void::Result::Result + parse_octal(std::span field, const char* name) + { + const auto* p = reinterpret_cast(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(p[0] & 0x3FU); + for (std::size_t i = 1; i < n; ++i) { + if (v > (std::numeric_limits::max() >> 8U)) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::corrupt_archive, + std::format("Archive: overflowing field '{}'", + name))}; + } + v = (v << 8U) | static_cast(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::max() >> 3U)) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::corrupt_archive, + std::format("Archive: octal overflow in '{}'", name))}; + } + out = (out << 3U) | static_cast(p[i] - '0'); + saw_digit = true; + } + if (!saw_digit) { + return std::uint64_t{0}; + } + return out; + } + + [[nodiscard]] std::string_view + c_field(std::span field) noexcept + { + const char* s = reinterpret_cast(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& block) noexcept + { + std::uint32_t sum = 0; + for (std::size_t i = 0; i < kTarBlockSize; ++i) { + if (i >= 148 && i < 156) { + sum += static_cast(' '); + } else { + sum += static_cast( + std::to_integer(block[i])); + } + } + return sum; + } + + [[nodiscard]] std::int32_t + compute_checksum_signed(const std::array& block) noexcept + { + std::int32_t sum = 0; + for (std::size_t i = 0; i < kTarBlockSize; ++i) { + if (i >= 148 && i < 156) { + sum += static_cast(' '); + } else { + sum += static_cast( + static_cast( + std::to_integer(block[i]))); + } + } + return sum; + } + + void build_ustar_header(std::array& 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(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(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(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(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 + write_padding(ByteSink& sink, std::uint64_t written) + { + const std::size_t rem = static_cast(written % kTarBlockSize); + if (rem == 0) { + return {}; + } + std::array 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(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 + parse_pax_records(std::string_view payload, std::string& path_out, + std::string& link_out, + std::optional& 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 + write_builtin_tar(ByteSink& sink, + std::span items, + const CreationOptions& options) + { + const std::uint64_t mtime = + options.reproducible + ? static_cast(std::max( + 0, options.canonical_mtime)) + : static_cast(std::max( + 0, + std::chrono::duration_cast( + 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 hdr{}; + std::vector 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( + 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::min(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{ + io_buf.data(), static_cast(r)}); + !w.has_value()) { + return w; + } + remaining -= static_cast(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 eof_blocks{}; + return sink.write(eof_blocks); + } + + BuiltinTarStream::BuiltinTarStream( + ByteSource& source, const ReadLimits& limits, std::stop_token stop, + std::optional 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 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 + BuiltinTarStream::read_exact_or_eof(std::span 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(*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 + BuiltinTarStream::read_exact_required(std::span 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 + BuiltinTarStream::discard_bytes(std::uint64_t count, + const char* context) + { + std::array scratch{}; + std::uint64_t rem = count; + while (rem > 0) { + const std::size_t want = static_cast( + std::min(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 BuiltinTarStream::open() + { + if (auto chk = check_stop_deadline(); !chk.has_value()) { + return chk; + } + m_prefetch.resize(std::min(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(*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> + BuiltinTarStream::next_entry() + { + if (m_reached_eof) { + return std::optional{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 next_pax_size; + std::string global_pax_path; + std::string global_pax_link; + std::optional global_pax_size; + std::string gnu_long_name; + std::string gnu_long_link; + + std::array 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{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{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(*recorded_sum) != + static_cast(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(std::to_integer(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(*parsed_size); + std::string payload(static_cast(*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((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(*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{std::move(out)}; + } + } + + Void::Result::Result 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 + BuiltinTarStream::read_entry_data(std::span 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::min(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 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 diff --git a/src/Archive/BuiltinTar.hpp b/src/Archive/BuiltinTar.hpp new file mode 100644 index 0000000..d433ddf --- /dev/null +++ b/src/Archive/BuiltinTar.hpp @@ -0,0 +1,93 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +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 inline_content{}; + int source_fd{-1}; + }; + + [[nodiscard]] Void::Result::Result + write_builtin_tar(ByteSink& sink, + std::span 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 deadline, + const Void::Time::MonotonicClock& clock); + + [[nodiscard]] Void::Result::Result open(); + + [[nodiscard]] Void::Result::Result> + next_entry(); + + [[nodiscard]] Void::Result::Result + read_entry_data(std::span dst); + + [[nodiscard]] Void::Result::Result skip_entry_data(); + + [[nodiscard]] std::uint64_t total_compressed_bytes() const noexcept + { + return m_total_compressed; + } + + private: + + [[nodiscard]] Void::Result::Result check_stop_deadline() const; + [[nodiscard]] Void::Result::Result + read_exact_or_eof(std::span dst); + [[nodiscard]] Void::Result::Result + read_exact_required(std::span dst, + const char* context); + [[nodiscard]] Void::Result::Result + discard_bytes(std::uint64_t count, const char* context); + [[nodiscard]] Void::Result::Result + finish_active_entry_padding(); + + ByteSource* m_source{nullptr}; + ReadLimits m_limits{}; + std::stop_token m_stop{}; + std::optional m_deadline{}; + const Void::Time::MonotonicClock* m_clock{ + &Void::Time::SystemMonotonicClock::instance()}; + + std::vector 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 diff --git a/src/Archive/StagedArchive.cpp b/src/Archive/StagedArchive.cpp index c0da04c..5042116 100644 --- a/src/Archive/StagedArchive.cpp +++ b/src/Archive/StagedArchive.cpp @@ -1,6 +1,8 @@ #include #include +#include "BuiltinTar.hpp" + #include #include #include @@ -18,8 +20,10 @@ #include #include +#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE #include #include +#endif #ifndef _WIN32 #include @@ -51,12 +55,14 @@ namespace Void::Archive constexpr std::string_view kInventoryFilename = "inventory.txt"; constexpr std::string_view kTreeSubdir = "tree"; +#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE using ArchiveReadPtr = std::unique_ptr; using ArchiveWritePtr = std::unique_ptr; using ArchiveEntryPtr = std::unique_ptr; +#endif class OwnedFd { @@ -129,6 +135,7 @@ namespace Void::Archive std::error_code{err, std::generic_category()}); } +#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE [[nodiscard]] Void::Result::Error make_libarchive_error(archive* a, std::string_view op, ArchiveErrorCode fallback = @@ -140,6 +147,7 @@ namespace Void::Archive return make_archive_error(fallback, std::format("Archive: {}: {}", op, detail)); } +#endif [[nodiscard]] bool is_safe_single_component( std::string_view name, std::size_t max_bytes = 255) noexcept @@ -894,6 +902,15 @@ namespace Void::Archive } } // 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 out; @@ -1088,10 +1105,14 @@ namespace Void::Archive std::optional deadline{}; const Void::Time::MonotonicClock* clock{ &Void::Time::SystemMonotonicClock::instance()}; +#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE ArchiveReadPtr handle{nullptr, &archive_read_free}; std::vector read_buf{}; - PathTracker tracker; std::optional source_error{}; +#endif + std::unique_ptr builtin_stream{}; + bool using_builtin{false}; + PathTracker tracker; bool has_active_file{false}; bool reached_eof{false}; bool poisoned{false}; @@ -1101,7 +1122,10 @@ namespace Void::Archive std::uint64_t total_compressed{0}; 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) { } @@ -1121,6 +1145,7 @@ namespace Void::Archive return {}; } +#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE static la_ssize_t libarchive_read_cb(archive* a, void* client_data, const void** buffer) { @@ -1150,6 +1175,7 @@ namespace Void::Archive *buffer = self->read_buf.data(); return static_cast(n); } +#endif }; Reader::Reader(std::unique_ptr impl) noexcept @@ -1178,6 +1204,7 @@ namespace Void::Archive return std::unexpected{std::move(chk.error())}; } +#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE impl->handle = ArchiveReadPtr{archive_read_new(), &archive_read_free}; if (!impl->handle) { @@ -1185,6 +1212,7 @@ namespace Void::Archive ArchiveErrorCode::io_error, "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_none(impl->handle.get()); (void)archive_read_support_format_tar(impl->handle.get()); @@ -1199,6 +1227,16 @@ namespace Void::Archive impl->handle.get(), "open archive", ArchiveErrorCode::unsupported_format)}; } + impl->using_builtin = false; +#else + impl->builtin_stream = std::make_unique( + 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)}; } @@ -1242,6 +1280,91 @@ namespace Void::Archive 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{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{ + .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; const int status = archive_read_next_header(m_impl->handle.get(), &entry); @@ -1335,6 +1458,12 @@ namespace Void::Archive .executable = executable, .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 @@ -1358,21 +1487,46 @@ namespace Void::Archive const std::size_t to_read = std::min(dst.size(), m_impl->limits.transfer_buffer_bytes); - 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)}; + std::size_t read_bytes = 0; + if (m_impl->using_builtin) { + auto r = + m_impl->builtin_stream->read_entry_data(dst.subspan(0, to_read)); + m_impl->total_compressed = + m_impl->builtin_stream->total_compressed_bytes(); + if (!r.has_value()) { + m_impl->poisoned = true; + return std::unexpected{std::move(r.error())}; } - return std::unexpected{ - make_libarchive_error(m_impl->handle.get(), "read entry data")}; + read_bytes = *r; + 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(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(n); + const auto amount = static_cast(read_bytes); if (amount > m_impl->limits.max_file_bytes - m_impl->entry_bytes_read || amount > m_impl->limits.max_total_bytes - m_impl->total_decompressed) { @@ -1383,7 +1537,7 @@ namespace Void::Archive } m_impl->entry_bytes_read += amount; m_impl->total_decompressed += amount; - return static_cast(n); + return read_bytes; } Void::Result::Result Reader::skip_entry() @@ -1462,6 +1616,7 @@ namespace Void::Archive } // Opt-in forensic listing: reports rejected entries without writing. +#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE struct ForensicState { ByteSource* source{nullptr}; ReadLimits limits{}; @@ -1477,6 +1632,7 @@ namespace Void::Archive ArchiveErrorCode::io_error, "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_none(handle.get()); (void)archive_read_support_format_tar(handle.get()); @@ -1592,6 +1748,88 @@ namespace Void::Archive (void)archive_read_data_skip(handle.get()); } 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 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() ? "" + : 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> @@ -2314,6 +2552,30 @@ namespace Void::Archive return a.path < b.path; }); + if (options.compression == ArchiveCompression::None && + (options.prefer_builtin_tar || !has_libarchive_backend())) { + std::vector 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 { ByteSink* sink{nullptr}; std::optional err{}; @@ -2331,6 +2593,19 @@ namespace Void::Archive return std::unexpected{ 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 { if (archive_write_add_filter_none(writer.get()) != ARCHIVE_OK) { return std::unexpected{ @@ -2380,14 +2655,24 @@ namespace Void::Archive const bool is_dir = (item.src->type == EntryType::Directory); const std::string wire_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_filetype(ae.get(), is_dir ? AE_IFDIR : AE_IFREG); - archive_entry_set_perm( - ae.get(), is_dir ? 0755 : (item.src->executable ? 0755 : 0644)); + archive_entry_set_perm(ae.get(), static_cast(perm)); if (options.reproducible) { - archive_entry_set_mtime(ae.get(), 0, 0); - archive_entry_set_uid(ae.get(), 0); - archive_entry_set_gid(ae.get(), 0); + archive_entry_set_mtime( + ae.get(), + static_cast( + std::max(0, options.canonical_mtime)), + 0); + archive_entry_set_uid( + ae.get(), static_cast(options.canonical_uid)); + archive_entry_set_gid( + ae.get(), static_cast(options.canonical_gid)); archive_entry_set_uname(ae.get(), ""); archive_entry_set_gname(ae.get(), ""); } @@ -2473,6 +2758,12 @@ namespace Void::Archive make_libarchive_error(writer.get(), "close archive writer")}; } return {}; +#else + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsupported_format, + "Archive::create_archive: compressed archives require " + "LibArchive backend")}; +#endif } Void::Result::Result @@ -2491,6 +2782,20 @@ namespace Void::Archive return sink->sync_and_close(); } + Void::Result::Result create(ByteSink& sink, + std::span entries, + const CreationOptions& options) + { + return create_archive(sink, entries, options); + } + + Void::Result::Result create(const std::filesystem::path& output_path, + std::span entries, + const CreationOptions& options) + { + return create_archive(output_path, entries, options); + } + // ── Isolated Child Decoder Profile ─────────────────────────────────────── Void::Result::Result diff --git a/src/Archive/module.cmake b/src/Archive/module.cmake index 824c085..452698d 100644 --- a/src/Archive/module.cmake +++ b/src/Archive/module.cmake @@ -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 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} ) diff --git a/src/Configuration/Argparse.cpp b/src/Configuration/Argparse.cpp index 25eb3e7..dabbf34 100644 --- a/src/Configuration/Argparse.cpp +++ b/src/Configuration/Argparse.cpp @@ -7,108 +7,284 @@ namespace Void::Argparse Parser::Parser(std::string program, std::string 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; } -Parser& Parser::option(std::string_view lng, std::string_view sht, - std::string_view desc, std::optional& out) +Parser& Parser::option(std::string_view lng, + std::string_view sht, + std::string_view desc, + std::optional& 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; } -Parser& Parser::option_default(std::string_view lng, std::string_view sht, - std::string_view desc, std::string& out, - std::string_view default_value) +Parser& Parser::option_many(std::string_view lng, + std::string_view sht, + std::string_view desc, + std::vector& 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}; - options_.push_back({std::string{lng}, std::string{sht}, std::string{desc}, - std::string{default_value}, nullptr, &out}); + options_.push_back({std::string{lng}, + std::string{sht}, + std::string{desc}, + std::string{default_value}, + nullptr, + &out, + nullptr}); 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}); return *this; } -std::expected -Parser::parse(int argc, const char* const* argv) const +Parser& Parser::positional_many(std::string_view name, + std::string_view desc, + std::vector& 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 on_selected) +{ + const std::string sub_prog = + program_.empty() ? name : (program_ + " " + name); + auto sub_parser = std::make_unique(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; + bool after_double_dash = false; + std::vector matched_path; + std::vector*> 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) { const std::string_view arg{argv[i]}; - // Help - if (arg == "--help" || arg == "-h") { - return std::unexpected{help()}; - } + if (!after_double_dash) { + if (arg == "--") { + after_double_dash = true; + continue; + } - // Flag check - bool matched_flag = false; - for (const auto& f : flags_) { - if (arg == f.lng || (!f.sht.empty() && arg == f.sht)) { - *f.out = true; - matched_flag = true; - break; + if (arg == "--help" || arg == "-h") { + return ParseResult{ + .outcome = ParseOutcome::Help, + .message = active->help(), + .matched_command_path = std::move(matched_path), + }; + } + + 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 = ⊂ + 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 - bool matched_opt = false; - for (const auto& opt : options_) { - std::string_view value; - bool found = false; - - // --key=value - 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; - } - // --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 (pos_idx < active->positionals_.size()) { + *active->positionals_[pos_idx++].out = std::string{arg}; + } else if (active->positional_many_.has_value() && + active->positional_many_->out != nullptr) { + active->positional_many_->out->push_back(std::string{arg}); + } else { + return ParseResult{ + .outcome = ParseOutcome::Error, + .message = + "unexpected positional argument: " + std::string{arg}, + .matched_command_path = std::move(matched_path), + }; } - 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 - for (std::size_t j = pos_idx; j < positionals_.size(); ++j) - return std::unexpected{"missing required argument: <" + positionals_[j].name + ">"}; + if (!active->subcommands_.empty()) { + const bool req = active->has_explicit_require_sub_ + ? 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 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 {}; } @@ -116,19 +292,42 @@ std::string Parser::help() const { std::ostringstream os; os << "Usage: " << program_; - for (const auto& f : flags_) os << " [" << f.lng << "]"; + for (const auto& f : flags_) os << " [" << f.lng << "]"; 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 << ">]"; } + if (!subcommands_.empty()) { + os << " "; + } 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"; 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"; for (const auto& p : positionals_) os << " <" << p.name << "> " << p.desc << "\n"; + if (positional_many_.has_value()) { + os << " <" << positional_many_->name << "...> " + << positional_many_->desc << "\n"; + } } if (!flags_.empty()) { os << "\nFlags:\n"; @@ -141,13 +340,13 @@ std::string Parser::help() const if (!options_.empty()) { os << "\nOptions:\n"; for (const auto& o : options_) { - // Derive a display name from the long option (strip leading --) - const std::string_view dname = std::string_view{o.lng}.substr( - o.lng.size() > 2 ? 2 : 0); + const std::string_view dname = + std::string_view{o.lng}.substr(o.lng.size() > 2 ? 2 : 0); os << " " << o.lng; if (!o.sht.empty()) os << ", " << o.sht; os << " <" << dname << ">"; if (!o.def.empty()) os << " (default: " << o.def << ")"; + if (o.out_many != nullptr) os << " (repeatable)"; os << " " << o.desc << "\n"; } } @@ -155,4 +354,4 @@ std::string Parser::help() const return os.str(); } -} // namespace Void::Argparse +} // namespace Void::Argparse \ No newline at end of file diff --git a/src/Crypto/BuiltinHash.cpp b/src/Crypto/BuiltinHash.cpp new file mode 100644 index 0000000..83d1101 --- /dev/null +++ b/src/Crypto/BuiltinHash.cpp @@ -0,0 +1,895 @@ +#include "BuiltinHash.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Crypto::Detail +{ + namespace + { + [[nodiscard]] inline std::uint32_t load_be32(const std::byte* p) noexcept + { + return (static_cast(std::to_integer(p[0])) << 24U) | + (static_cast(std::to_integer(p[1])) << 16U) | + (static_cast(std::to_integer(p[2])) << 8U) | + static_cast(std::to_integer(p[3])); + } + + inline void store_be32(std::byte* p, std::uint32_t v) noexcept + { + p[0] = static_cast((v >> 24U) & 0xFFU); + p[1] = static_cast((v >> 16U) & 0xFFU); + p[2] = static_cast((v >> 8U) & 0xFFU); + p[3] = static_cast(v & 0xFFU); + } + + [[nodiscard]] inline std::uint64_t load_be64(const std::byte* p) noexcept + { + return (static_cast(load_be32(p)) << 32U) | + static_cast(load_be32(p + 4)); + } + + inline void store_be64(std::byte* p, std::uint64_t v) noexcept + { + store_be32(p, static_cast((v >> 32U) & 0xFFFFFFFFU)); + store_be32(p + 4, static_cast(v & 0xFFFFFFFFU)); + } + + [[nodiscard]] inline std::uint64_t load_le64(const std::byte* p) noexcept + { + return static_cast(std::to_integer(p[0])) | + (static_cast(std::to_integer(p[1])) << 8U) | + (static_cast(std::to_integer(p[2])) << 16U) | + (static_cast(std::to_integer(p[3])) << 24U) | + (static_cast(std::to_integer(p[4])) << 32U) | + (static_cast(std::to_integer(p[5])) << 40U) | + (static_cast(std::to_integer(p[6])) << 48U) | + (static_cast(std::to_integer(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((v >> (8U * i)) & 0xFFU); + } + } + + // ── FIPS 180-4 SHA-1 ───────────────────────────────────────────────── + + struct Sha1State { + std::array h{0x67452301U, 0xefcdab89U, + 0x98badcfeU, 0x10325476U, + 0xc3d2e1f0U}; + std::array buf{}; + std::size_t buf_len{0}; + std::uint64_t total_bytes{0}; + + void compress(const std::byte* block) noexcept + { + std::array 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 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 out20) noexcept + { + buf[buf_len++] = std::byte{0x80}; + if (buf_len > 56) { + std::fill(buf.begin() + static_cast(buf_len), + buf.end(), std::byte{0}); + compress(buf.data()); + buf_len = 0; + } + std::fill(buf.begin() + static_cast(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 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 h{0x6a09e667U, 0xbb67ae85U, + 0x3c6ef372U, 0xa54ff53aU, + 0x510e527fU, 0x9b05688cU, + 0x1f83d9abU, 0x5be0cd19U}; + std::array buf{}; + std::size_t buf_len{0}; + std::uint64_t total_bytes{0}; + + void compress(const std::byte* block) noexcept + { + std::array 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 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 out32) noexcept + { + buf[buf_len++] = std::byte{0x80}; + if (buf_len > 56) { + std::fill(buf.begin() + static_cast(buf_len), + buf.end(), std::byte{0}); + compress(buf.data()); + buf_len = 0; + } + std::fill(buf.begin() + static_cast(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 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 h{ + 0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL, + 0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL, + 0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL, + 0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL}; + std::array buf{}; + std::size_t buf_len{0}; + std::uint64_t total_bytes{0}; + + void compress(const std::byte* block) noexcept + { + std::array 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 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 out64) noexcept + { + buf[buf_len++] = std::byte{0x80}; + if (buf_len > 112) { + std::fill(buf.begin() + static_cast(buf_len), + buf.end(), std::byte{0}); + compress(buf.data()); + buf_len = 0; + } + std::fill(buf.begin() + static_cast(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 kIv = { + 0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL, + 0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL, + 0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL, + 0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL}; + + static constexpr std::array, 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 h{kIv}; + std::array t{0, 0}; + std::array 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(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 m{}; + for (std::size_t i = 0; i < 16; ++i) { + m[i] = load_le64(block + i * 8); + } + std::array 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 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 out) noexcept + { + add_counter(static_cast(buf_len)); + std::fill(buf.begin() + static_cast(buf_len), + buf.end(), std::byte{0}); + compress(buf.data(), true); + std::array 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 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 lhs, + std::span 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(lhs[i]); + const auto b = static_cast(rhs[i]); + diff = static_cast(diff | (a ^ b)); + } + std::atomic_signal_fence(std::memory_order_seq_cst); + return diff == 0; + } + + struct BuiltinHasher::State { + std::variant + impl{}; + + void wipe() noexcept + { + std::visit( + [](auto& st) { + using T = std::decay_t; + if constexpr (!std::is_same_v) { + st.wipe(); + } + }, + impl); + impl.template emplace(); + } + }; + + 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(); + return true; + case HashAlgorithm::Sha256: + m_state->impl.emplace(); + return true; + case HashAlgorithm::Sha512: + m_state->impl.emplace(); + return true; + case HashAlgorithm::Blake2b256: { + auto& b = m_state->impl.emplace(); + b.init(32); + return true; + } + case HashAlgorithm::Blake2b512: { + auto& b = m_state->impl.emplace(); + b.init(64); + return true; + } + } + return false; + } + + void BuiltinHasher::update(std::span data) noexcept + { + if (m_state == nullptr || data.empty()) { + return; + } + std::visit( + [&](auto& st) { + using T = std::decay_t; + if constexpr (!std::is_same_v) { + 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; + if constexpr (std::is_same_v) { + out.resize(20); + st.finalize_into(out); + } else if constexpr (std::is_same_v) { + out.resize(32); + st.finalize_into(out); + } else if constexpr (std::is_same_v) { + out.resize(64); + st.finalize_into(out); + } else if constexpr (std::is_same_v) { + out.resize(st.out_len); + st.finalize_into(out); + } + }, + m_state->impl); + return out; + } + + void builtin_hmac_sha256(std::span secret_key, + std::span message, + std::span output_32) noexcept + { + std::array 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 ipad{}; + std::array 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 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 secret_input, + std::span salt, + std::span context, + std::span secret_output) noexcept + { + std::array zero_salt{}; + const auto effective_salt = + salt.empty() ? std::span{zero_salt} : salt; + + std::array prk{}; + builtin_hmac_sha256(effective_salt, secret_input, prk); + + std::array t{}; + std::size_t t_len = 0; + std::size_t written = 0; + std::uint8_t counter = 1; + + while (written < secret_output.size()) { + std::array ipad{}; + std::array 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 inner_hash{}; + Sha256State inner; + inner.update(ipad); + if (t_len > 0) { + inner.update(std::span{t.data(), t_len}); + } + if (!context.empty()) { + inner.update(context); + } + const std::byte ctr_byte = static_cast(counter); + inner.update(std::span{&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(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 diff --git a/src/Crypto/BuiltinHash.hpp b/src/Crypto/BuiltinHash.hpp new file mode 100644 index 0000000..fe86865 --- /dev/null +++ b/src/Crypto/BuiltinHash.hpp @@ -0,0 +1,49 @@ +#pragma once + +#include +#include + +#include +#include + +namespace Void::Crypto::Detail +{ + void builtin_secure_wipe(std::span buffer) noexcept; + + [[nodiscard]] bool + builtin_constant_time_equal(std::span lhs, + std::span 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 data) noexcept; + [[nodiscard]] Digest finalize(); + + private: + + struct State; + State* m_state{nullptr}; + void destroy() noexcept; + }; + + void builtin_hmac_sha256(std::span secret_key, + std::span message, + std::span output_32) noexcept; + + void builtin_hkdf_sha256(std::span secret_input, + std::span salt, + std::span context, + std::span secret_output) noexcept; + +} // namespace Void::Crypto::Detail diff --git a/src/Crypto/Crypto.cpp b/src/Crypto/Crypto.cpp index a00c02e..81aa6e0 100644 --- a/src/Crypto/Crypto.cpp +++ b/src/Crypto/Crypto.cpp @@ -1,19 +1,24 @@ #include +#include "BuiltinHash.hpp" + #include #include #include #include #include #include +#include #include +#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL #include #include #include #include #include #include +#endif namespace Void::Crypto { @@ -42,6 +47,36 @@ namespace Void::Crypto std::format("{}: injected crypto backend fault", operation)); } + [[nodiscard]] bool spans_overlap(std::span a, + std::span b) noexcept + { + if (a.empty() || b.empty()) { + return false; + } + const auto a_begin = reinterpret_cast(a.data()); + const auto a_end = a_begin + a.size(); + const auto b_begin = reinterpret_cast(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* algorithm_name(HashAlgorithm algorithm) noexcept { @@ -52,6 +87,10 @@ namespace Void::Crypto return "SHA256"; case HashAlgorithm::Sha512: return "SHA512"; + case HashAlgorithm::Blake2b256: + return nullptr; + case HashAlgorithm::Blake2b512: + return "BLAKE2B512"; } return nullptr; } @@ -78,19 +117,6 @@ namespace Void::Crypto code, std::format("{}: {}", operation, buffer.data())); } - [[nodiscard]] bool spans_overlap(std::span a, - std::span b) noexcept - { - if (a.empty() || b.empty()) { - return false; - } - const auto a_begin = reinterpret_cast(a.data()); - const auto a_end = a_begin + a.size(); - const auto b_begin = reinterpret_cast(b.data()); - const auto b_end = b_begin + b.size(); - return a_begin < b_end && b_begin < a_end; - } - using EvpMdPtr = std::unique_ptr; using EvpMdCtxPtr = std::unique_ptr; @@ -110,6 +136,7 @@ namespace Void::Crypto ? &kEmptyByte : reinterpret_cast(span.data()); } +#endif [[nodiscard]] Void::Result::Result verify_ed25519_impl(std::span message, @@ -144,6 +171,12 @@ namespace Void::Crypto 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(); const char* propq = propq_or_null(provider); EvpPkeyPtr key{EVP_PKEY_new_raw_public_key_ex( @@ -182,14 +215,33 @@ namespace Void::Crypto } ERR_clear_error(); return result == 1; +#else + (void)provider; + return std::unexpected{make_crypto_error( + CryptoErrorCode::unsupported_algorithm, + "Crypto::verifyEd25519: built without OpenSSL backend")}; +#endif } } // 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 buffer) noexcept { +#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL if (!buffer.empty()) { OPENSSL_cleanse(buffer.data(), buffer.size()); } +#else + Detail::builtin_secure_wipe(buffer); +#endif } bool constant_time_equal(std::span lhs, @@ -201,7 +253,11 @@ namespace Void::Crypto if (lhs.empty()) { return true; } +#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL 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 @@ -218,8 +274,12 @@ namespace Void::Crypto } struct Hasher::Impl { +#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL EvpMdCtxPtr context{nullptr, &EVP_MD_CTX_free}; EvpMdPtr algorithm{nullptr, &EVP_MD_free}; +#endif + Detail::BuiltinHasher builtin{}; + bool using_builtin{false}; HasherState state{HasherState::Ready}; }; @@ -244,18 +304,50 @@ namespace Void::Crypto Void::Result::Result Hasher::create(HashAlgorithm algorithm, const ProviderOptions& provider) { - const char* md_name = algorithm_name(algorithm); - if (md_name == nullptr) { - return std::unexpected{make_crypto_error( - CryptoErrorCode::unsupported_algorithm, - "Crypto::Hasher: unsupported algorithm")}; + switch (algorithm) { + case HashAlgorithm::Sha1: + case HashAlgorithm::Sha256: + case HashAlgorithm::Sha512: + 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, "Crypto::Hasher::create"); fault.has_value()) { 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(); + 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(); auto impl = std::make_unique(); impl->algorithm = EvpMdPtr{ @@ -278,8 +370,14 @@ namespace Void::Crypto CryptoErrorCode::provider_error, "Crypto::Hasher: digest initialization failed")}; } + impl->using_builtin = false; impl->state = HasherState::Ready; return Hasher{std::move(impl)}; +#else + return std::unexpected{make_crypto_error( + CryptoErrorCode::backend_error, + "Crypto::Hasher: OpenSSL backend unavailable")}; +#endif } Void::Result::Result Hasher::update(std::span data) @@ -301,6 +399,12 @@ namespace Void::Crypto m_impl->state = HasherState::Failed; 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() && EVP_DigestUpdate(m_impl->context.get(), data.data(), data.size()) != 1) { @@ -311,6 +415,12 @@ namespace Void::Crypto } m_impl->state = HasherState::Updating; 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 Hasher::update(std::string_view data) @@ -337,6 +447,12 @@ namespace Void::Crypto m_impl->state = HasherState::Failed; 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()); if (digest_size <= 0) { m_impl->state = HasherState::Failed; @@ -357,6 +473,12 @@ namespace Void::Crypto m_impl->state = HasherState::Finalized; digest.resize(written); 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 data) @@ -388,18 +510,31 @@ namespace Void::Crypto auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path) -> Void::Result::Result { - return hashFile(algorithm, path, ProviderOptions{}); + return hash_file(algorithm, path, ProviderOptions{}); } auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path, const ProviderOptions& provider) -> Void::Result::Result + { + return hash_file(algorithm, path, provider); + } + + auto hash_file(HashAlgorithm algorithm, const std::filesystem::path& path) + -> Void::Result::Result + { + return hash_file(algorithm, path, ProviderOptions{}); + } + + auto hash_file(HashAlgorithm algorithm, const std::filesystem::path& path, + const ProviderOptions& provider) + -> Void::Result::Result { std::ifstream input{path, std::ios::binary}; if (!input.is_open()) { return std::unexpected{make_crypto_error( CryptoErrorCode::io_error, - std::format("Crypto::hashFile: cannot open '{}'", + std::format("Crypto::hash_file: cannot open '{}'", path.string()))}; } auto hasher = Hasher::create(algorithm, provider); @@ -422,7 +557,7 @@ namespace Void::Crypto if (input.bad() || (!input.eof() && input.fail())) { return std::unexpected{make_crypto_error( CryptoErrorCode::io_error, - std::format("Crypto::hashFile: I/O error reading '{}'", + std::format("Crypto::hash_file: I/O error reading '{}'", path.string()))}; } return hasher->finalize(); @@ -452,21 +587,63 @@ namespace Void::Crypto { return hash(HashAlgorithm::Sha512, data); } + Void::Result::Result blake2b256(std::span data) + { + return hash(HashAlgorithm::Blake2b256, data); + } + Void::Result::Result blake2b256(std::string_view data) + { + return hash(HashAlgorithm::Blake2b256, data); + } + Void::Result::Result blake2b512(std::span data) + { + return hash(HashAlgorithm::Blake2b512, data); + } + Void::Result::Result blake2b512(std::string_view data) + { + return hash(HashAlgorithm::Blake2b512, data); + } Void::Result::Result sha1File(const std::filesystem::path& path) { - return hashFile(HashAlgorithm::Sha1, path); + return hash_file(HashAlgorithm::Sha1, path); } Void::Result::Result sha256File(const std::filesystem::path& path) { - return hashFile(HashAlgorithm::Sha256, path); + return hash_file(HashAlgorithm::Sha256, path); } Void::Result::Result sha512File(const std::filesystem::path& path) { - return hashFile(HashAlgorithm::Sha512, path); + return hash_file(HashAlgorithm::Sha512, path); + } + Void::Result::Result sha1_file(const std::filesystem::path& path) + { + return hash_file(HashAlgorithm::Sha1, path); + } + Void::Result::Result sha256_file(const std::filesystem::path& path) + { + return hash_file(HashAlgorithm::Sha256, path); + } + Void::Result::Result sha512_file(const std::filesystem::path& path) + { + return hash_file(HashAlgorithm::Sha512, path); + } + Void::Result::Result + blake2b256_file(const std::filesystem::path& path) + { + return hash_file(HashAlgorithm::Blake2b256, path); + } + Void::Result::Result + blake2b512_file(const std::filesystem::path& path) + { + return hash_file(HashAlgorithm::Blake2b512, path); } struct Ed25519PrivateKey::Impl { +#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL EvpPkeyPtr pkey{nullptr, &EVP_PKEY_free}; +#else + std::uint8_t unused{0}; +#endif }; Ed25519PrivateKey::Ed25519PrivateKey(std::unique_ptr impl) noexcept @@ -481,7 +658,11 @@ namespace Void::Crypto bool Ed25519PrivateKey::valid() const noexcept { +#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL return m_impl != nullptr && m_impl->pkey != nullptr; +#else + return false; +#endif } Void::Result::Result @@ -492,6 +673,12 @@ namespace Void::Crypto fault.has_value()) { 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(); EvpPkeyPtr key{ EVP_PKEY_Q_keygen(nullptr, propq_or_null(provider), "ED25519"), @@ -504,6 +691,13 @@ namespace Void::Crypto auto impl = std::make_unique(); impl->pkey = std::move(key); 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 @@ -523,6 +717,13 @@ namespace Void::Crypto fault.has_value()) { 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(); EvpPkeyPtr key{EVP_PKEY_new_raw_private_key_ex( nullptr, "ED25519", propq_or_null(provider), @@ -536,6 +737,13 @@ namespace Void::Crypto auto impl = std::make_unique(); impl->pkey = std::move(key); 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 Ed25519PrivateKey::public_key() const @@ -546,6 +754,7 @@ namespace Void::Crypto "Crypto::Ed25519PrivateKey::public_key: invalid or moved-from " "key")}; } +#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL Ed25519PublicKey pub; std::size_t len = pub.bytes.size(); if (EVP_PKEY_get_raw_public_key( @@ -558,6 +767,12 @@ namespace Void::Crypto "Crypto::Ed25519PrivateKey::public_key failed")}; } return pub; +#else + return std::unexpected{make_crypto_error( + CryptoErrorCode::unsupported_algorithm, + "Crypto::Ed25519PrivateKey::public_key: built without OpenSSL " + "backend")}; +#endif } Void::Result::Result Ed25519PrivateKey::export_raw_seed() const @@ -568,6 +783,7 @@ namespace Void::Crypto "Crypto::Ed25519PrivateKey::export_raw_seed: invalid or " "moved-from key")}; } +#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL std::array raw{}; std::size_t len = raw.size(); if (EVP_PKEY_get_raw_private_key( @@ -582,6 +798,12 @@ namespace Void::Crypto auto result = Ed25519Seed::from_bytes(raw); secure_wipe(raw); 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 @@ -607,6 +829,12 @@ namespace Void::Crypto 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(); EvpMdCtxPtr context{EVP_MD_CTX_new(), &EVP_MD_CTX_free}; if (!context) { @@ -635,6 +863,12 @@ namespace Void::Crypto "Crypto::sign_ed25519 failed")}; } 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 verifyEd25519(std::span message, @@ -682,6 +916,19 @@ namespace Void::Crypto 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(); EvpMacPtr mac{EVP_MAC_fetch(nullptr, "HMAC", propq_or_null(provider)), &EVP_MAC_free}; @@ -732,6 +979,12 @@ namespace Void::Crypto "Crypto::hmac_sha256_into: EVP_MAC_final failed")}; } 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 hmac_sha256(std::span secret_key, @@ -780,6 +1033,20 @@ namespace Void::Crypto 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(); EvpKdfPtr kdf{EVP_KDF_fetch(nullptr, "HKDF", propq_or_null(provider)), &EVP_KDF_free}; @@ -825,6 +1092,12 @@ namespace Void::Crypto "Crypto::hkdf_sha256: EVP_KDF_derive failed")}; } 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 diff --git a/src/Crypto/module.cmake b/src/Crypto/module.cmake index 0fb20a7..d5578e1 100644 --- a/src/Crypto/module.cmake +++ b/src/Crypto/module.cmake @@ -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 INTERNAL_DEPS Functional - EXTERNAL_DEPS OpenSSL::Crypto + EXTERNAL_DEPS ${_void_crypto_ext_deps} EXCLUDE_HEADERS Void/Crypto/AsyncHash.hpp ) +target_compile_definitions(Void_Crypto PUBLIC + VOID_CRYPTO_HAS_OPENSSL=${_void_crypto_has_openssl} +) diff --git a/src/Net/Http.cpp b/src/Net/Http.cpp index 84134c7..2ce3345 100644 --- a/src/Net/Http.cpp +++ b/src/Net/Http.cpp @@ -4,36 +4,48 @@ #include #include +#include #include #include #include #include #include #include +#include #include +#include #include +#include #if !defined(_WIN32) +#include #include +#include #include +#include #endif +#include +#include +#include #include +#include #include #include #include +#include #include #include #include #include #include +#include #include #include namespace Void::Net { - namespace { namespace asio = boost::asio; @@ -42,6 +54,72 @@ namespace Void::Net namespace ssl = boost::asio::ssl; using tcp = boost::asio::ip::tcp; + std::atomic g_dl_temp_seq{0}; + + [[nodiscard]] bool + equal_ascii_ci(std::string_view a, std::string_view b) noexcept + { + return a.size() == b.size() && + std::ranges::equal(a, b, [](char x, char y) { + return std::tolower(static_cast(x)) == + std::tolower(static_cast(y)); + }); + } + + [[nodiscard]] bool is_sensitive_header(std::string_view name) noexcept + { + return equal_ascii_ci(name, "Authorization") || + equal_ascii_ci(name, "Proxy-Authorization") || + equal_ascii_ci(name, "Cookie") || + equal_ascii_ci(name, "Set-Cookie") || + equal_ascii_ci(name, "X-Api-Key"); + } + + [[nodiscard]] std::optional + find_header_ci(const std::vector
& headers, + std::string_view name) noexcept + { + for (const auto& h : headers) { + if (equal_ascii_ci(h.name, name)) { + return h.value; + } + } + return std::nullopt; + } + + [[nodiscard]] std::string sanitize_url_for_log(std::string_view raw) + { + const std::size_t scheme_end = raw.find("://"); + if (scheme_end == std::string_view::npos) { + return std::string{raw}; + } + const std::size_t auth_start = scheme_end + 3U; + const std::size_t slash = raw.find('/', auth_start); + const std::size_t at = raw.find('@', auth_start); + if (at != std::string_view::npos && + (slash == std::string_view::npos || at < slash)) { + std::string out{raw.substr(0, auth_start)}; + out += "@"; + out += raw.substr(at + 1U); + return out; + } + return std::string{raw}; + } + + [[nodiscard]] std::string_view method_to_str(Method m) noexcept + { + switch (m) { + case Method::Get: return "GET"; + case Method::Post: return "POST"; + case Method::Put: return "PUT"; + case Method::Delete: return "DELETE"; + case Method::Patch: return "PATCH"; + case Method::Head: return "HEAD"; + case Method::Options: return "OPTIONS"; + } + return "GET"; + } + [[nodiscard]] http::verb to_verb(Method m) { switch (m) { @@ -56,38 +134,76 @@ namespace Void::Net return http::verb::get; } - // Build the Beast request for an origin-form target (direct / tunnelled). - http::request - build_request(const Url& url, const Request& req, - std::string_view default_ua, std::string_view target) + [[nodiscard]] bool same_origin(const Url& a, const Url& b) noexcept { - http::request r{to_verb(req.method), - std::string{target}, 11}; - r.set(http::field::host, url.host); + return equal_ascii_ci(a.scheme, b.scheme) && + equal_ascii_ci(a.host, b.host) && a.port == b.port; + } + + void strip_sensitive_headers(std::vector
& headers) + { + std::erase_if(headers, [](const Header& h) { + return is_sensitive_header(h.name); + }); + } + + template + void populate_common_headers(RequestMsg& rq, const Url& url, + const std::vector
& headers, + std::string_view default_ua) + { + const bool std_port = + (url.is_tls && url.port == "443") || + (!url.is_tls && url.port == "80") || url.port.empty(); + if (std_port) { + rq.set(http::field::host, url.host); + } else { + rq.set(http::field::host, url.host + ":" + url.port); + } bool has_ua = false; - for (const auto& h : req.headers) { - r.set(h.name, h.value); - if (!has_ua && h.name == "User-Agent") has_ua = true; + for (const auto& h : headers) { + rq.set(h.name, h.value); + if (!has_ua && equal_ascii_ci(h.name, "User-Agent")) { + has_ua = true; + } } if (!has_ua) { - r.set(http::field::user_agent, std::string{default_ua}); + rq.set(http::field::user_agent, std::string{default_ua}); } - if (req.body) { - r.body() = *req.body; + } + + http::request + build_request(const Url& url, Method method, + const std::vector
& headers, + const std::optional& body, + std::string_view default_ua, std::string_view target) + { + http::request r{to_verb(method), + std::string{target}, 11}; + populate_common_headers(r, url, headers, default_ua); + if (body) { + r.body() = *body; r.prepare_payload(); } return r; } + std::vector
extract_headers(const http::fields& fields) + { + std::vector
out; + for (const auto& f : fields) { + out.push_back( + {std::string{f.name_string()}, std::string{f.value()}}); + } + return out; + } + Response convert(const http::response& src) { Response out; out.status = static_cast(src.result_int()); out.body = beast::buffers_to_string(src.body().data()); - for (const auto& f : src.base()) { - out.headers.push_back( - {std::string{f.name_string()}, std::string{f.value()}}); - } + out.headers = extract_headers(src.base()); return out; } @@ -97,10 +213,10 @@ namespace Void::Net { http::write(stream, rq); beast::flat_buffer buffer; - // Use a parser so the body limit is configurable. Beast's default - // (~1 MiB) is too small for binary downloads (release artifacts); - // max_body == 0 means unlimited. http::response_parser parser; + if (rq.method() == http::verb::head) { + parser.skip(true); + } parser.body_limit(max_body == 0 ? std::numeric_limits::max() : max_body); @@ -108,7 +224,6 @@ namespace Void::Net return convert(parser.get()); } - // SOCKS5 CONNECT handshake on an already-connected socket. void socks5_connect(tcp::socket& socket, const Url& url, const ProxyConfig& proxy) { @@ -131,9 +246,11 @@ namespace Void::Net } std::vector a{0x01}; a.push_back(static_cast(proxy.username->size())); - a.insert(a.end(), proxy.username->begin(), proxy.username->end()); + a.insert(a.end(), proxy.username->begin(), + proxy.username->end()); a.push_back(static_cast(proxy.password->size())); - a.insert(a.end(), proxy.password->begin(), proxy.password->end()); + a.insert(a.end(), proxy.password->begin(), + proxy.password->end()); asio::write(socket, asio::buffer(a)); std::vector ar(2); asio::read(socket, asio::buffer(ar)); @@ -175,7 +292,6 @@ namespace Void::Net throw std::runtime_error(std::format( "SOCKS5: connect failed (code {})", int(cres[1]))); } - // Drain the bound address. switch (cres[3]) { case 0x01: { std::vector b(6); @@ -198,7 +314,6 @@ namespace Void::Net } } - // HTTP CONNECT tunnel for TLS targets on a connected proxy socket. void http_connect_tunnel(tcp::socket& socket, const Url& url, const ProxyConfig& proxy) { @@ -213,10 +328,6 @@ namespace Void::Net } http::write(socket, creq); beast::flat_buffer buffer; - // A 2xx CONNECT reply has no body; the socket then becomes a raw - // tunnel. Some proxies attach a body to non-2xx replies, which an - // empty_body reader rejects ("unexpected body") before we can even - // read the status. skip(true) + read_header reads only the headers. http::response_parser cparser; cparser.skip(true); http::read_header(socket, buffer, cparser); @@ -227,35 +338,109 @@ namespace Void::Net } } - void tls_handshake(ssl::stream& stream, const Url& url) + struct TlsError : std::runtime_error { + using std::runtime_error::runtime_error; + }; + + struct QuotaError : std::runtime_error { + using std::runtime_error::runtime_error; + }; + + struct CancelledError : std::runtime_error { + using std::runtime_error::runtime_error; + }; + + ssl::context make_ssl_context(bool verify_tls, + const std::string& ca_file) { - if (!SSL_set_tlsext_host_name(stream.native_handle(), - url.host.c_str())) { - throw std::runtime_error("TLS: failed to set SNI host"); + ssl::context ctx{ssl::context::tls_client}; + (void)SSL_CTX_set_min_proto_version(ctx.native_handle(), + TLS1_2_VERSION); + if (verify_tls) { + if (!ca_file.empty()) { + boost::system::error_code ec; + ctx.load_verify_file(ca_file, ec); + if (ec) { + throw TlsError(std::format( + "TLS: failed to load CA file '{}': {}", ca_file, + ec.message())); + } + } else { + ctx.set_default_verify_paths(); + } + ctx.set_verify_mode(ssl::verify_peer | + ssl::verify_fail_if_no_peer_cert); + } else { + ctx.set_verify_mode(ssl::verify_none); + } + return ctx; + } + + void tls_handshake(ssl::stream& stream, const Url& url, + bool verify_tls) + { + std::string clean_host = url.host; + if (clean_host.size() >= 2 && clean_host.front() == '[' && + clean_host.back() == ']') { + clean_host = clean_host.substr(1, clean_host.size() - 2); + } + boost::system::error_code ip_ec; + (void)asio::ip::make_address(clean_host, ip_ec); + const bool is_ip = !ip_ec; + + if (!is_ip && + !SSL_set_tlsext_host_name(stream.native_handle(), + clean_host.c_str())) { + throw TlsError("TLS: failed to set SNI hostname"); + } + if (verify_tls) { + X509_VERIFY_PARAM* param = SSL_get0_param(stream.native_handle()); + if (param == nullptr) { + throw TlsError("TLS: X509_VERIFY_PARAM unavailable"); + } + if (is_ip) { + if (X509_VERIFY_PARAM_set1_ip_asc( + param, clean_host.c_str()) != 1) { + throw TlsError( + "TLS: failed to set peer IP verification target"); + } + } else { + X509_VERIFY_PARAM_set_hostflags( + param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); + if (X509_VERIFY_PARAM_set1_host(param, clean_host.c_str(), + clean_host.size()) != 1) { + throw TlsError( + "TLS: failed to set peer hostname verification"); + } + } + } + + boost::system::error_code hs_ec; + stream.handshake(ssl::stream_base::client, hs_ec); + if (hs_ec) { + throw TlsError(std::format("TLS handshake failed: {}", + hs_ec.message())); } - stream.handshake(ssl::stream_base::client); } - // Bounds every sync operation on an open socket with the request - // timeout. Asio's synchronous ops cannot be bounded any other way - // short of going fully async: SO_RCVTIMEO merely makes recv return - // EAGAIN, which the sync emulation treats as would-block and then - // poll()s without a deadline. On expiry the watchdog ::shutdown()s - // the descriptor — shutdown (unlike close) is safe against a - // concurrent blocked op and wakes it with EOF, so the op fails and - // the request errors out instead of hanging the calling thread - // forever. The descriptor must stay open for the guard's lifetime - // (declare the guard after the connected socket, in the same scope). - // Name resolution and connect() are not covered (kernel defaults). class DeadlineGuard { public: DeadlineGuard(tcp::socket& socket, - std::chrono::seconds timeout) + std::chrono::seconds timeout, + std::stop_token stop = {}) + : m_stop(std::move(stop)), + m_stop_cb(socket.is_open() ? m_stop : std::stop_token{}, + StopShutdown{ + &m_cancelled, + socket.is_open() + ? socket.native_handle() + : tcp::socket::native_handle_type{}, + socket.is_open()}) { - if (timeout <= std::chrono::seconds::zero() || - !socket.is_open()) { + if (!socket.is_open() || + timeout <= std::chrono::seconds::zero()) { return; } const auto fd = socket.native_handle(); @@ -268,7 +453,7 @@ namespace Void::Net #else ::shutdown(fd, SHUT_RDWR); #endif - m_timed_out = true; + m_timed_out.store(true, std::memory_order_release); } }); } @@ -291,60 +476,378 @@ namespace Void::Net [[nodiscard]] bool timed_out() const noexcept { - return m_timed_out; + return m_timed_out.load(std::memory_order_acquire); + } + [[nodiscard]] bool cancelled() const noexcept + { + return m_cancelled.load(std::memory_order_acquire); } private: + struct StopShutdown { + std::atomic* cancelled{nullptr}; + tcp::socket::native_handle_type fd{}; + bool has_fd{false}; + + void operator()() const noexcept + { + if (cancelled != nullptr) { + cancelled->store(true, + std::memory_order_release); + } + if (has_fd) { +#if defined(_WIN32) + ::shutdown(fd, SD_BOTH); +#else + ::shutdown(fd, SHUT_RDWR); +#endif + } + } + }; + std::thread m_worker; std::mutex m_mutex; std::condition_variable m_cv; bool m_done{false}; - bool m_timed_out{false}; + std::atomic m_timed_out{false}; + std::atomic m_cancelled{false}; + std::stop_token m_stop{}; + std::stop_callback m_stop_cb; }; - // Perform the request over an already-connected plain socket, doing a - // TLS upgrade in place when the target is https. The TLS stream is an - // out-parameter declared in the caller's scope so the descriptor - // outlives the caller's DeadlineGuard (declaration order there is - // socket, stream, guard — the guard is destroyed first). Response finish(tcp::socket& socket, std::optional>& tls, - ssl::context& ctx, const Url& url, const Request& req, - std::string_view ua, std::uint64_t max_body) + ssl::context& ctx, const Url& url, Method method, + const std::vector
& headers, + const std::optional& body, + std::string_view ua, std::uint64_t max_body, + bool verify_tls) { if (url.is_tls) { tls.emplace(std::move(socket), ctx); - tls_handshake(*tls, url); - auto rq = build_request(url, req, ua, url.target); + tls_handshake(*tls, url, verify_tls); + auto rq = + build_request(url, method, headers, body, ua, url.target); return write_read(*tls, rq, max_body); } - auto rq = build_request(url, req, ua, url.target); + auto rq = build_request(url, method, headers, body, ua, url.target); return write_read(socket, rq, max_body); } - } // namespace - std::optional - Response::header(std::string_view name) const - { - for (const auto& h : headers) { - if (h.name.size() == name.size()) { - bool eq = true; - for (std::size_t i = 0; i < name.size(); ++i) { - const char a = static_cast(std::tolower(h.name[i])); - const char b = static_cast(std::tolower(name[i])); - if (a != b) { eq = false; break; } + class OwnedTempFile + { + public: + + static Void::Result::Result + create(const std::filesystem::path& destination) + { + std::filesystem::path parent = destination.parent_path(); + if (parent.empty()) { + parent = "."; + } + std::error_code ec; + std::filesystem::create_directories(parent, ec); + if (ec) { + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net: create_directories failed: {}", + ec.message()), + ec)}; + } + const std::filesystem::path tmp_path = + parent / std::format(".void-dl-{}-{}", + static_cast(::getpid()), + g_dl_temp_seq.fetch_add( + 1, std::memory_order_relaxed)); + const int fd = ::open( + tmp_path.c_str(), + O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, + 0644); + if (fd < 0) { + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net: create temp download file failed: " + "{}", + std::strerror(errno)), + std::error_code{errno, std::generic_category()})}; + } + return OwnedTempFile{fd, tmp_path, destination}; } - if (eq) return h.value; - } - } - return std::nullopt; - } - namespace - { - // Resolve a redirect Location against the URL it came from. Handles - // absolute URLs and host-relative ("/path") and bare-relative targets. + OwnedTempFile(OwnedTempFile&& o) noexcept + : m_fd(std::exchange(o.m_fd, -1)), + m_tmp(std::move(o.m_tmp)), + m_dest(std::move(o.m_dest)), + m_committed(std::exchange(o.m_committed, true)) + { + } + OwnedTempFile& operator=(OwnedTempFile&&) = delete; + OwnedTempFile(const OwnedTempFile&) = delete; + OwnedTempFile& operator=(const OwnedTempFile&) = delete; + + ~OwnedTempFile() noexcept { discard(); } + + [[nodiscard]] Void::Result::Result + write_all(std::span data) + { + std::size_t off = 0; + while (off < data.size()) { + const ssize_t w = ::write( + m_fd, + reinterpret_cast(data.data()) + off, + data.size() - off); + if (w < 0 && errno == EINTR) { + continue; + } + if (w <= 0) { + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net: write download file failed: " + "{}", + std::strerror(errno)), + std::error_code{errno, + std::generic_category()})}; + } + off += static_cast(w); + } + return {}; + } + + [[nodiscard]] Void::Result::Result commit() + { + if (::fsync(m_fd) != 0) { + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net: fsync download file failed: {}", + std::strerror(errno)), + std::error_code{errno, std::generic_category()})}; + } + const int raw = std::exchange(m_fd, -1); + if (::close(raw) != 0) { + discard(); + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net: close download file failed: {}", + std::strerror(errno)), + std::error_code{errno, std::generic_category()})}; + } + std::error_code ec; + std::filesystem::rename(m_tmp, m_dest, ec); + if (ec) { + discard(); + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net: rename download file failed: {}", + ec.message()), + ec)}; + } + m_committed = true; + return {}; + } + + void discard() noexcept + { + if (m_fd >= 0) { + (void)::close(m_fd); + m_fd = -1; + } + if (!m_committed && !m_tmp.empty()) { + std::error_code ec; + std::filesystem::remove(m_tmp, ec); + } + m_committed = true; + } + + private: + + OwnedTempFile(int fd, std::filesystem::path tmp, + std::filesystem::path dest) + : m_fd(fd), m_tmp(std::move(tmp)), m_dest(std::move(dest)) + { + } + + int m_fd{-1}; + std::filesystem::path m_tmp{}; + std::filesystem::path m_dest{}; + bool m_committed{false}; + }; + + template + DownloadResult read_stream_to_file( + Stream& stream, const Url& url, const std::vector
& headers, + std::string_view ua, std::string_view target, + const std::filesystem::path& destination, + const DownloadOptions& options) + { + auto rq = build_request(url, Method::Get, headers, std::nullopt, ua, + target); + http::write(stream, rq); + + beast::flat_buffer rx_buf; + http::response_parser parser; + parser.body_limit(std::numeric_limits::max()); + http::read_header(stream, rx_buf, parser); + + const auto status = + static_cast(parser.get().result_int()); + auto resp_headers = extract_headers(parser.get().base()); + const auto boost_cl = parser.content_length(); + const std::optional declared_total = + boost_cl.has_value() + ? std::optional{*boost_cl} + : std::nullopt; + + if (options.max_bytes > 0 && declared_total.has_value() && + *declared_total > options.max_bytes) { + throw QuotaError(std::format( + "Net: Content-Length {} exceeds max_bytes quota {}", + *declared_total, options.max_bytes)); + } + + auto tmp = OwnedTempFile::create(destination); + if (!tmp.has_value()) { + throw std::runtime_error(tmp.error().message()); + } + + std::vector chunk(64ULL * 1024U); + std::uint64_t total_written = 0; + while (!parser.is_done()) { + if (options.stop.stop_requested()) { + throw CancelledError("Net: download cancelled"); + } + parser.get().body().data = chunk.data(); + parser.get().body().size = chunk.size(); + beast::error_code ec; + (void)http::read_some(stream, rx_buf, parser, ec); + const bool eof_ok = + (ec == http::error::end_of_stream && + !declared_total.has_value()); + if (ec && ec != http::error::need_buffer && !eof_ok) { + throw boost::system::system_error{ec}; + } + const std::size_t got = + chunk.size() - parser.get().body().size; + if (got > 0) { + const auto amt = static_cast(got); + if (options.max_bytes > 0 && + amt > options.max_bytes - total_written) { + throw QuotaError(std::format( + "Net: download exceeded max_bytes quota {}", + options.max_bytes)); + } + const auto slice = + std::span{chunk.data(), got}; + if (auto wr = tmp->write_all(slice); !wr.has_value()) { + throw std::runtime_error(wr.error().message()); + } + total_written += amt; + if (options.on_chunk) { + options.on_chunk(slice); + } + if (options.on_progress) { + options.on_progress(TransferProgress{ + .bytes_transferred = total_written, + .total_bytes = declared_total}); + } + } + if (eof_ok) { + break; + } + } + + if (auto cm = tmp->commit(); !cm.has_value()) { + throw std::runtime_error(cm.error().message()); + } + + return DownloadResult{ + .status = status, + .headers = std::move(resp_headers), + .bytes_written = total_written, + .elapsed = {}, + }; + } + + template + Response stream_file_request(Stream& stream, const Url& url, + std::string_view target, int file_fd, + std::uint64_t file_size, + const UploadOptions& options, + std::string_view default_ua, + std::uint64_t max_response_body) + { + http::request rq{to_verb(options.method), + std::string{target}, 11}; + populate_common_headers(rq, url, options.headers, default_ua); + if (!find_header_ci(options.headers, "Content-Type").has_value() && + !options.content_type.empty()) { + rq.set(http::field::content_type, options.content_type); + } + rq.content_length(file_size); + rq.body().data = nullptr; + rq.body().size = 0; + rq.body().more = (file_size > 0); + + http::request_serializer sr{rq}; + http::write_header(stream, sr); + + if (file_size > 0) { + std::array buf{}; + std::uint64_t sent_total = 0; + while (sent_total < file_size) { + if (options.stop.stop_requested()) { + throw CancelledError("Net: upload cancelled"); + } + const std::size_t want = static_cast( + std::min(buf.size(), + file_size - sent_total)); + const ssize_t r = ::read(file_fd, buf.data(), want); + if (r < 0 && errno == EINTR) { + continue; + } + if (r <= 0) { + throw std::runtime_error( + "Net: source file shrunk or read failed during " + "upload"); + } + const auto amt = static_cast(r); + rq.body().data = buf.data(); + rq.body().size = static_cast(r); + rq.body().more = (sent_total + amt < file_size); + + beast::error_code ec; + (void)http::write(stream, sr, ec); + if (ec == http::error::need_buffer) { + ec = {}; + } + if (ec) { + throw boost::system::system_error{ec}; + } + sent_total += amt; + if (options.on_progress) { + options.on_progress(TransferProgress{ + .bytes_transferred = sent_total, + .total_bytes = file_size}); + } + } + } else { + beast::error_code ec; + (void)http::write(stream, sr, ec); + if (ec && ec != http::error::need_buffer) { + throw boost::system::system_error{ec}; + } + } + + beast::flat_buffer rx_buf; + http::response_parser parser; + parser.body_limit( + max_response_body == 0 + ? std::numeric_limits::max() + : max_response_body); + http::read(stream, rx_buf, parser); + return convert(parser.get()); + } + std::string resolve_redirect(const Url& base, std::string_view location) { if (location.starts_with("http://") || @@ -366,33 +869,75 @@ namespace Void::Net } } // namespace + std::optional + Response::header(std::string_view name) const + { + return find_header_ci(headers, name); + } + + std::optional + DownloadResult::header(std::string_view name) const + { + return find_header_ci(headers, name); + } + + HttpClient::HttpClient(HttpClientOptions options) + : m_proxy(std::move(options.proxy)), + m_user_agent(std::move(options.user_agent)), + m_verify_tls(options.verify_tls), + m_ca_file(std::move(options.ca_file)), + m_max_body(options.max_body_size), + m_max_redirects(options.max_redirects), + m_allow_insecure_redirects(options.allow_insecure_redirects) + { + } + + HttpClient HttpClient::secure(ProxyConfig proxy) + { + return HttpClient{HttpClientOptions{ + .proxy = std::move(proxy), + .verify_tls = true, + }}; + } + + std::string HttpClient::format_request_diagnostics(const Request& req) + { + std::string out = std::format("{} {}", method_to_str(req.method), + sanitize_url_for_log(req.url)); + for (const auto& h : req.headers) { + out += "\n "; + out += h.name; + out += ": "; + out += is_sensitive_header(h.name) ? "" : h.value; + } + return out; + } + Void::Result::Result HttpClient::send(const Request& req) const { std::string target_url = req.url; + std::vector
active_headers = req.headers; int redirects = 0; while (true) { const auto url = Url::parse(target_url); if (!url) { - return Void::Result::fail( - std::format("Net: invalid URL '{}'", target_url)); + return std::unexpected{make_net_error( + NetErrorCode::invalid_url, + std::format("Net: invalid URL '{}'", + sanitize_url_for_log(target_url)))}; } + bool cancelled = false; + bool timed_out = false; try { const auto start = std::chrono::steady_clock::now(); asio::io_context ioc; - ssl::context ctx{ssl::context::tlsv12_client}; - ctx.set_default_verify_paths(); - ctx.set_verify_mode(m_verify_tls ? ssl::verify_peer - : ssl::verify_none); + ssl::context ctx = make_ssl_context(m_verify_tls, m_ca_file); Response response; tcp::resolver resolver{ioc}; - - // Declaration order matters: the DeadlineGuard must be - // destroyed (and its watchdog joined) BEFORE the objects - // that own the descriptor it may shut down. tcp::socket socket{ioc}; std::optional> tls; @@ -403,42 +948,70 @@ namespace Void::Net DeadlineGuard deadline{socket, req.timeout}; if (m_proxy.kind == ProxyConfig::Kind::Socks5) { socks5_connect(socket, *url, m_proxy); - response = finish(socket, tls, ctx, *url, req, - m_user_agent, m_max_body); - } else { // Http proxy + response = finish(socket, tls, ctx, *url, req.method, + active_headers, req.body, + m_user_agent, m_max_body, + m_verify_tls); + } else { if (url->is_tls) { http_connect_tunnel(socket, *url, m_proxy); - response = finish(socket, tls, ctx, *url, req, - m_user_agent, m_max_body); + response = finish(socket, tls, ctx, *url, + req.method, active_headers, + req.body, m_user_agent, + m_max_body, m_verify_tls); } else { - // Plain HTTP through proxy: absolute-form target. const std::string absolute = std::format( "{}://{}{}", url->scheme, url->host, url->target); - auto rq = build_request(*url, req, m_user_agent, - absolute); + auto rq = build_request(*url, req.method, + active_headers, req.body, + m_user_agent, absolute); if (m_proxy.has_auth()) { const auto enc = Void::Encoding::Base64::encode( - *m_proxy.username + ":" + *m_proxy.password); + *m_proxy.username + ":" + + *m_proxy.password); rq.set(http::field::proxy_authorization, "Basic " + enc); } response = write_read(socket, rq, m_max_body); } } + timed_out = deadline.timed_out(); + cancelled = deadline.cancelled(); } else { asio::connect(socket, resolver.resolve(url->host, url->port)); DeadlineGuard deadline{socket, req.timeout}; - response = finish(socket, tls, ctx, *url, req, - m_user_agent, m_max_body); + response = + finish(socket, tls, ctx, *url, req.method, + active_headers, req.body, m_user_agent, + m_max_body, m_verify_tls); + timed_out = deadline.timed_out(); + cancelled = deadline.cancelled(); } - // Transparently follow redirects when enabled. if (m_max_redirects > 0 && response.status >= 300 && response.status < 400 && redirects < m_max_redirects) { if (auto loc = response.header("location")) { - target_url = resolve_redirect(*url, *loc); + const std::string next_url = + resolve_redirect(*url, *loc); + const auto next_parsed = Url::parse(next_url); + if (!next_parsed) { + return std::unexpected{make_net_error( + NetErrorCode::invalid_url, + "Net: invalid redirect Location URL")}; + } + if (url->is_tls && !next_parsed->is_tls && + m_verify_tls && !m_allow_insecure_redirects) { + return std::unexpected{make_net_error( + NetErrorCode::redirect_blocked, + "Net: blocked HTTPS to HTTP downgrade " + "redirect")}; + } + if (!same_origin(*url, *next_parsed)) { + strip_sensitive_headers(active_headers); + } + target_url = next_url; ++redirects; continue; } @@ -448,14 +1021,316 @@ namespace Void::Net std::chrono::duration_cast( std::chrono::steady_clock::now() - start); return response; + } catch (const TlsError& e) { + return std::unexpected{make_net_error( + NetErrorCode::tls_error, + std::format("Net: TLS request to '{}' failed: {}", + sanitize_url_for_log(target_url), e.what()))}; } catch (const std::exception& e) { - return Void::Result::fail( - std::format("Net: request to '{}' failed: {}", target_url, - e.what())); + if (cancelled) { + return std::unexpected{make_net_error( + NetErrorCode::cancelled, + std::format("Net: request to '{}' cancelled", + sanitize_url_for_log(target_url)))}; + } + if (timed_out) { + return std::unexpected{make_net_error( + NetErrorCode::timeout, + std::format("Net: request to '{}' timed out: {}", + sanitize_url_for_log(target_url), + e.what()))}; + } + return std::unexpected{make_net_error( + NetErrorCode::connect_failed, + std::format("Net: request to '{}' failed: {}", + sanitize_url_for_log(target_url), e.what()))}; } } } + Void::Result::Result + HttpClient::download_to_file(std::string_view url_str, + const std::filesystem::path& destination, + const DownloadOptions& options) const + { + if (options.stop.stop_requested()) { + return std::unexpected{make_net_error( + NetErrorCode::cancelled, "Net: download cancelled")}; + } + std::string target_url{url_str}; + std::vector
active_headers = options.headers; + int redirects = 0; + + while (true) { + if (options.stop.stop_requested()) { + return std::unexpected{make_net_error( + NetErrorCode::cancelled, "Net: download cancelled")}; + } + const auto url = Url::parse(target_url); + if (!url) { + return std::unexpected{make_net_error( + NetErrorCode::invalid_url, + std::format("Net: invalid URL '{}'", + sanitize_url_for_log(target_url)))}; + } + bool timed_out = false; + bool cancelled = false; + try { + const auto start = std::chrono::steady_clock::now(); + asio::io_context ioc; + ssl::context ctx = make_ssl_context(m_verify_tls, m_ca_file); + tcp::resolver resolver{ioc}; + tcp::socket socket{ioc}; + std::optional> tls; + + if (m_proxy.enabled()) { + asio::connect(socket, resolver.resolve( + m_proxy.host, + std::to_string(m_proxy.port))); + } else { + asio::connect(socket, + resolver.resolve(url->host, url->port)); + } + + DeadlineGuard deadline{socket, options.timeout, options.stop}; + DownloadResult result; + const auto finish_stream = [&]() { + if (m_proxy.enabled()) { + if (m_proxy.kind == ProxyConfig::Kind::Socks5) { + socks5_connect(socket, *url, m_proxy); + } else if (url->is_tls) { + http_connect_tunnel(socket, *url, m_proxy); + } else { + const std::string absolute = std::format( + "{}://{}{}", url->scheme, url->host, + url->target); + auto h = active_headers; + if (m_proxy.has_auth()) { + const auto enc = Void::Encoding::Base64::encode( + *m_proxy.username + ":" + + *m_proxy.password); + h.push_back(Header{"Proxy-Authorization", + "Basic " + enc}); + } + result = read_stream_to_file( + socket, *url, h, m_user_agent, absolute, + destination, options); + return; + } + } + if (url->is_tls) { + tls.emplace(std::move(socket), ctx); + tls_handshake(*tls, *url, m_verify_tls); + result = read_stream_to_file( + *tls, *url, active_headers, m_user_agent, + url->target, destination, options); + } else { + result = read_stream_to_file( + socket, *url, active_headers, m_user_agent, + url->target, destination, options); + } + }; + finish_stream(); + timed_out = deadline.timed_out(); + cancelled = deadline.cancelled(); + + if (m_max_redirects > 0 && result.status >= 300 && + result.status < 400 && redirects < m_max_redirects) { + if (auto loc = result.header("location")) { + const std::string next_url = + resolve_redirect(*url, *loc); + const auto next_parsed = Url::parse(next_url); + if (!next_parsed) { + return std::unexpected{make_net_error( + NetErrorCode::invalid_url, + "Net: invalid redirect Location URL")}; + } + if (url->is_tls && !next_parsed->is_tls && + m_verify_tls && !m_allow_insecure_redirects) { + return std::unexpected{make_net_error( + NetErrorCode::redirect_blocked, + "Net: blocked HTTPS to HTTP downgrade " + "redirect")}; + } + if (!same_origin(*url, *next_parsed)) { + strip_sensitive_headers(active_headers); + } + std::error_code rm_ec; + std::filesystem::remove(destination, rm_ec); + target_url = next_url; + ++redirects; + continue; + } + } + + result.elapsed = + std::chrono::duration_cast( + std::chrono::steady_clock::now() - start); + return result; + } catch (const QuotaError& e) { + return std::unexpected{ + make_net_error(NetErrorCode::quota_exceeded, e.what())}; + } catch (const CancelledError& e) { + return std::unexpected{ + make_net_error(NetErrorCode::cancelled, e.what())}; + } catch (const TlsError& e) { + return std::unexpected{make_net_error( + NetErrorCode::tls_error, + std::format("Net: TLS download '{}' failed: {}", + sanitize_url_for_log(target_url), e.what()))}; + } catch (const std::exception& e) { + if (cancelled || options.stop.stop_requested()) { + return std::unexpected{make_net_error( + NetErrorCode::cancelled, "Net: download cancelled")}; + } + if (timed_out) { + return std::unexpected{make_net_error( + NetErrorCode::timeout, + std::format("Net: download '{}' timed out: {}", + sanitize_url_for_log(target_url), + e.what()))}; + } + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net: download '{}' failed: {}", + sanitize_url_for_log(target_url), e.what()))}; + } + } + } + + Void::Result::Result + HttpClient::upload_file(std::string_view url_str, + const std::filesystem::path& source_path, + const UploadOptions& options) const + { + if (options.stop.stop_requested()) { + return std::unexpected{ + make_net_error(NetErrorCode::cancelled, "Net: upload cancelled")}; + } + const int raw_fd = + ::open(source_path.c_str(), O_RDONLY | O_CLOEXEC); + if (raw_fd < 0) { + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net: cannot open upload file '{}': {}", + source_path.string(), std::strerror(errno)), + std::error_code{errno, std::generic_category()})}; + } + struct FdClose { + int fd; + ~FdClose() noexcept + { + if (fd >= 0) (void)::close(fd); + } + } fd_guard{raw_fd}; + + struct stat st{}; + if (::fstat(raw_fd, &st) != 0 || !S_ISREG(st.st_mode)) { + return std::unexpected{make_net_error( + NetErrorCode::invalid_argument, + std::format("Net: upload source '{}' is not a regular file", + source_path.string()))}; + } + const auto file_size = static_cast(st.st_size); + if (options.max_upload_bytes > 0 && + file_size > options.max_upload_bytes) { + return std::unexpected{make_net_error( + NetErrorCode::quota_exceeded, + std::format("Net: upload file size {} exceeds limit {}", + file_size, options.max_upload_bytes))}; + } + + const auto url = Url::parse(url_str); + if (!url) { + return std::unexpected{make_net_error( + NetErrorCode::invalid_url, + std::format("Net: invalid URL '{}'", + sanitize_url_for_log(url_str)))}; + } + + bool timed_out = false; + bool cancelled = false; + try { + const auto start = std::chrono::steady_clock::now(); + asio::io_context ioc; + ssl::context ctx = make_ssl_context(m_verify_tls, m_ca_file); + tcp::resolver resolver{ioc}; + tcp::socket socket{ioc}; + std::optional> tls; + + if (m_proxy.enabled()) { + asio::connect(socket, + resolver.resolve(m_proxy.host, + std::to_string(m_proxy.port))); + } else { + asio::connect(socket, resolver.resolve(url->host, url->port)); + } + + DeadlineGuard deadline{socket, options.timeout, options.stop}; + Response response; + if (m_proxy.enabled()) { + if (m_proxy.kind == ProxyConfig::Kind::Socks5) { + socks5_connect(socket, *url, m_proxy); + } else if (url->is_tls) { + http_connect_tunnel(socket, *url, m_proxy); + } else { + const std::string absolute = std::format( + "{}://{}{}", url->scheme, url->host, url->target); + response = stream_file_request( + socket, *url, absolute, raw_fd, file_size, options, + m_user_agent, m_max_body); + timed_out = deadline.timed_out(); + cancelled = deadline.cancelled(); + response.elapsed = + std::chrono::duration_cast( + std::chrono::steady_clock::now() - start); + return response; + } + } + + if (url->is_tls) { + tls.emplace(std::move(socket), ctx); + tls_handshake(*tls, *url, m_verify_tls); + response = stream_file_request( + *tls, *url, url->target, raw_fd, file_size, options, + m_user_agent, m_max_body); + } else { + response = stream_file_request( + socket, *url, url->target, raw_fd, file_size, options, + m_user_agent, m_max_body); + } + timed_out = deadline.timed_out(); + cancelled = deadline.cancelled(); + response.elapsed = + std::chrono::duration_cast( + std::chrono::steady_clock::now() - start); + return response; + } catch (const CancelledError& e) { + return std::unexpected{ + make_net_error(NetErrorCode::cancelled, e.what())}; + } catch (const TlsError& e) { + return std::unexpected{make_net_error( + NetErrorCode::tls_error, + std::format("Net: TLS upload '{}' failed: {}", + sanitize_url_for_log(url_str), e.what()))}; + } catch (const std::exception& e) { + if (cancelled || options.stop.stop_requested()) { + return std::unexpected{make_net_error( + NetErrorCode::cancelled, "Net: upload cancelled")}; + } + if (timed_out) { + return std::unexpected{make_net_error( + NetErrorCode::timeout, + std::format("Net: upload '{}' timed out: {}", + sanitize_url_for_log(url_str), e.what()))}; + } + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net: upload '{}' failed: {}", + sanitize_url_for_log(url_str), e.what()))}; + } + } + Void::Result::Result HttpClient::get(std::string_view url, std::vector
headers) const { @@ -478,4 +1353,30 @@ namespace Void::Net return send(r); } + Void::Result::Result + HttpClient::put_file(std::string_view url, + const std::filesystem::path& source_path, + std::vector
headers, + std::string content_type) const + { + UploadOptions opts; + opts.method = Method::Put; + opts.headers = std::move(headers); + opts.content_type = std::move(content_type); + return upload_file(url, source_path, opts); + } + + Void::Result::Result + HttpClient::post_file(std::string_view url, + const std::filesystem::path& source_path, + std::vector
headers, + std::string content_type) const + { + UploadOptions opts; + opts.method = Method::Post; + opts.headers = std::move(headers); + opts.content_type = std::move(content_type); + return upload_file(url, source_path, opts); + } + } // namespace Void::Net diff --git a/src/Net/HttpServer.cpp b/src/Net/HttpServer.cpp new file mode 100644 index 0000000..5fb219d --- /dev/null +++ b/src/Net/HttpServer.cpp @@ -0,0 +1,1837 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Net +{ + namespace + { + std::atomic g_temp_upload_seq{0}; + + [[nodiscard]] bool + equal_ascii_ci(std::string_view a, std::string_view b) noexcept + { + return a.size() == b.size() && + std::ranges::equal(a, b, [](char x, char y) { + return std::tolower(static_cast(x)) == + std::tolower(static_cast(y)); + }); + } + + [[nodiscard]] bool + contains_ascii_ci(std::string_view haystack, + std::string_view needle) noexcept + { + if (needle.empty() || needle.size() > haystack.size()) { + return false; + } + for (std::size_t i = 0; i + needle.size() <= haystack.size(); ++i) { + if (equal_ascii_ci(haystack.substr(i, needle.size()), needle)) { + return true; + } + } + return false; + } + + [[nodiscard]] std::string_view trim_ows(std::string_view s) noexcept + { + while (!s.empty() && (s.front() == ' ' || s.front() == '\t')) { + s.remove_prefix(1); + } + while (!s.empty() && (s.back() == ' ' || s.back() == '\t')) { + s.remove_suffix(1); + } + return s; + } + + [[nodiscard]] std::optional + parse_method(std::string_view token) noexcept + { + if (token == "GET") return Method::Get; + if (token == "HEAD") return Method::Head; + if (token == "POST") return Method::Post; + if (token == "PUT") return Method::Put; + if (token == "DELETE") return Method::Delete; + if (token == "PATCH") return Method::Patch; + if (token == "OPTIONS") return Method::Options; + return std::nullopt; + } + + [[nodiscard]] std::string_view method_string(Method m) noexcept + { + switch (m) { + case Method::Get: return "GET"; + case Method::Head: return "HEAD"; + case Method::Post: return "POST"; + case Method::Put: return "PUT"; + case Method::Delete: return "DELETE"; + case Method::Patch: return "PATCH"; + case Method::Options: return "OPTIONS"; + } + return "GET"; + } + + [[nodiscard]] std::string_view reason_phrase(std::uint16_t code) noexcept + { + switch (code) { + case 100: return "Continue"; + case 200: return "OK"; + case 201: return "Created"; + case 204: return "No Content"; + case 301: return "Moved Permanently"; + case 302: return "Found"; + case 304: return "Not Modified"; + case 400: return "Bad Request"; + case 401: return "Unauthorized"; + case 403: return "Forbidden"; + case 404: return "Not Found"; + case 405: return "Method Not Allowed"; + case 408: return "Request Timeout"; + case 413: return "Payload Too Large"; + case 415: return "Unsupported Media Type"; + case 431: return "Request Header Fields Too Large"; + case 500: return "Internal Server Error"; + case 501: return "Not Implemented"; + case 503: return "Service Unavailable"; + default: return "OK"; + } + } + + [[nodiscard]] bool has_crlf_or_nul(std::string_view s) noexcept + { + for (const unsigned char ch : s) { + if (ch == '\r' || ch == '\n' || ch == '\0') { + return true; + } + } + return false; + } + + [[nodiscard]] bool is_valid_token(std::string_view s) noexcept + { + if (s.empty()) { + return false; + } + for (const unsigned char ch : s) { + if (ch <= 0x20 || ch >= 0x7F || ch == ':' || ch == '(' || + ch == ')' || ch == '<' || ch == '>' || ch == '@' || + ch == ',' || ch == ';' || ch == '\\' || ch == '"' || + ch == '/' || ch == '[' || ch == ']' || ch == '?' || + ch == '=' || ch == '{' || ch == '}') { + return false; + } + } + return true; + } + + [[nodiscard]] bool parse_u64_decimal(std::string_view s, + std::uint64_t& out) noexcept + { + if (s.empty()) { + return false; + } + for (const unsigned char ch : s) { + if (ch < '0' || ch > '9') { + return false; + } + } + const auto res = std::from_chars(s.data(), s.data() + s.size(), out); + return res.ec == std::errc{} && res.ptr == s.data() + s.size(); + } + + [[nodiscard]] std::vector split_path(std::string_view path) + { + std::vector segments; + std::size_t begin = path.starts_with('/') ? 1 : 0; + while (begin < path.size()) { + const auto end = path.find('/', begin); + const auto segment = path.substr(begin, end - begin); + if (!segment.empty()) { + segments.emplace_back(segment); + } + if (end == std::string_view::npos) { + break; + } + begin = end + 1; + } + return segments; + } + + [[nodiscard]] bool valid_param_name(std::string_view name) noexcept + { + return !name.empty() && std::ranges::all_of(name, [](char v) { + const auto c = static_cast(v); + return std::isalnum(c) != 0 || v == '_'; + }); + } + + [[nodiscard]] Void::Result::Result> + compile_route_pattern(std::string_view pattern) + { + if (pattern.empty() || !pattern.starts_with('/') || + pattern.find_first_of("?#") != std::string_view::npos) { + return std::unexpected{make_net_error( + NetErrorCode::invalid_argument, + "Net::HttpServer: route patterns must be absolute paths")}; + } + auto segments = split_path(pattern); + std::set> names; + for (std::size_t i = 0; i < segments.size(); ++i) { + const auto& seg = segments[i]; + if (!seg.starts_with(':') && !seg.starts_with('*')) { + continue; + } + const auto name = std::string_view{seg}.substr(1); + if (!valid_param_name(name) || !names.emplace(name).second || + (seg.starts_with('*') && i + 1 != segments.size())) { + return std::unexpected{make_net_error( + NetErrorCode::invalid_argument, + "Net::HttpServer: invalid streaming route pattern")}; + } + } + return segments; + } + + [[nodiscard]] std::optional + match_segments(const std::vector& pattern, + const std::vector& path) + { + RouteParameters params; + std::size_t pi = 0; + for (const auto& seg : pattern) { + if (seg.starts_with('*')) { + std::string val; + for (; pi < path.size(); ++pi) { + if (!val.empty()) { + val.push_back('/'); + } + val += path[pi]; + } + params.emplace(seg.substr(1), std::move(val)); + return params; + } + if (pi >= path.size()) { + return std::nullopt; + } + if (seg.starts_with(':')) { + params.emplace(seg.substr(1), path[pi]); + } else if (seg != path[pi]) { + return std::nullopt; + } + ++pi; + } + if (pi != path.size()) { + return std::nullopt; + } + return params; + } + + [[nodiscard]] int segment_rank(std::string_view s) noexcept + { + if (s.starts_with('*')) return 0; + if (s.starts_with(':')) return 1; + return 2; + } + + [[nodiscard]] bool + more_specific_route(const std::vector& cand, + const std::vector& cur) noexcept + { + const std::size_t n = std::min(cand.size(), cur.size()); + for (std::size_t i = 0; i < n; ++i) { + const int cr = segment_rank(cand[i]); + const int br = segment_rank(cur[i]); + if (cr != br) { + return cr > br; + } + } + return cand.size() > cur.size(); + } + + [[nodiscard]] bool + same_route_shape(const std::vector& lhs, + const std::vector& rhs) noexcept + { + if (lhs.size() != rhs.size()) { + return false; + } + for (std::size_t i = 0; i < lhs.size(); ++i) { + const int lr = segment_rank(lhs[i]); + const int rr = segment_rank(rhs[i]); + if (lr != rr || (lr == 2 && lhs[i] != rhs[i])) { + return false; + } + } + return true; + } + + class OwnedFd + { + public: + + explicit OwnedFd(int fd = -1) noexcept : m_fd(fd) {} + ~OwnedFd() noexcept { reset(); } + OwnedFd(OwnedFd&& other) noexcept + : m_fd(std::exchange(other.m_fd, -1)) + { + } + OwnedFd& operator=(OwnedFd&& other) noexcept + { + if (this != &other) { + reset(std::exchange(other.m_fd, -1)); + } + return *this; + } + OwnedFd(const OwnedFd&) = delete; + OwnedFd& operator=(const OwnedFd&) = delete; + + [[nodiscard]] int get() const noexcept { return m_fd; } + [[nodiscard]] explicit operator bool() const noexcept + { + return m_fd >= 0; + } + [[nodiscard]] int release() noexcept + { + return std::exchange(m_fd, -1); + } + void reset(int fd = -1) noexcept + { + if (m_fd >= 0) { + (void)::close(m_fd); + } + m_fd = fd; + } + + private: + + int m_fd{-1}; + }; + + [[nodiscard]] Void::Result::Result + recv_slice(int fd, std::span dst, + const std::atomic& stopping, + std::chrono::milliseconds timeout) + { + const auto deadline = std::chrono::steady_clock::now() + timeout; + for (;;) { + if (stopping.load(std::memory_order_acquire)) { + return std::unexpected{make_net_error( + NetErrorCode::cancelled, + "Net::HttpServer: server shutting down")}; + } + const auto now = std::chrono::steady_clock::now(); + if (timeout > std::chrono::milliseconds::zero() && + now >= deadline) { + return std::unexpected{make_net_error( + NetErrorCode::timeout, "Net::HttpServer: read timeout")}; + } + int wait_ms = 50; + if (timeout > std::chrono::milliseconds::zero()) { + const auto rem = std::chrono::duration_cast< + std::chrono::milliseconds>(deadline - now) + .count(); + wait_ms = static_cast(std::clamp(rem, 1, 50)); + } + + struct pollfd pfd{}; + pfd.fd = fd; + pfd.events = POLLIN; + const int pr = ::poll(&pfd, 1, wait_ms); + if (pr < 0) { + if (errno == EINTR) { + continue; + } + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net::HttpServer: poll failed: {}", + std::strerror(errno)), + std::error_code{errno, std::generic_category()})}; + } + if (pr == 0) { + continue; + } + const ssize_t n = ::recv(fd, dst.data(), dst.size(), 0); + if (n < 0) { + if (errno == EINTR || errno == EAGAIN || + errno == EWOULDBLOCK) { + continue; + } + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net::HttpServer: recv failed: {}", + std::strerror(errno)), + std::error_code{errno, std::generic_category()})}; + } + return static_cast(n); + } + } + + [[nodiscard]] Void::Result::Result + send_all(int fd, std::span data, + std::chrono::milliseconds timeout) + { + std::size_t off = 0; + const auto deadline = std::chrono::steady_clock::now() + timeout; + while (off < data.size()) { + const auto now = std::chrono::steady_clock::now(); + if (timeout > std::chrono::milliseconds::zero() && + now >= deadline) { + return std::unexpected{make_net_error( + NetErrorCode::timeout, + "Net::HttpServer: write timeout")}; + } + int wait_ms = 100; + if (timeout > std::chrono::milliseconds::zero()) { + const auto rem = std::chrono::duration_cast< + std::chrono::milliseconds>(deadline - now) + .count(); + wait_ms = + static_cast(std::clamp(rem, 1, 100)); + } + + struct pollfd pfd{}; + pfd.fd = fd; + pfd.events = POLLOUT; + const int pr = ::poll(&pfd, 1, wait_ms); + if (pr < 0) { + if (errno == EINTR) { + continue; + } + return std::unexpected{make_net_error( + NetErrorCode::io_error, "Net::HttpServer: send poll failed")}; + } + if (pr == 0) { + continue; + } + const ssize_t n = ::send( + fd, + reinterpret_cast(data.data()) + off, + data.size() - off, MSG_NOSIGNAL); + if (n < 0) { + if (errno == EINTR || errno == EAGAIN || + errno == EWOULDBLOCK) { + continue; + } + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net::HttpServer: send failed: {}", + std::strerror(errno)), + std::error_code{errno, std::generic_category()})}; + } + if (n == 0) { + return std::unexpected{make_net_error( + NetErrorCode::io_error, + "Net::HttpServer: peer closed socket on send")}; + } + off += static_cast(n); + } + return {}; + } + + [[nodiscard]] Void::Result::Result + send_str(int fd, std::string_view s, + std::chrono::milliseconds timeout) + { + return send_all(fd, + std::as_bytes(std::span{s.data(), s.size()}), + timeout); + } + } // namespace + + struct BodyReader::State { + int fd{-1}; + const std::atomic* stopping{nullptr}; + std::chrono::milliseconds read_timeout{}; + std::uint64_t default_max_bytes{0}; + std::string* rx_buf{nullptr}; + std::size_t* rx_off{nullptr}; + + bool chunked{false}; + std::optional declared_length{}; + std::uint64_t total_read{0}; + std::uint64_t remaining_fixed{0}; + bool eof{false}; + + enum class ChunkPhase { + Header, + Data, + AfterDataCrlf, + Trailers, + Done + }; + ChunkPhase chunk_phase{ChunkPhase::Header}; + std::uint64_t chunk_remaining{0}; + + void consume_rx(std::size_t n) noexcept + { + *rx_off += n; + if (*rx_off >= rx_buf->size()) { + rx_buf->clear(); + *rx_off = 0; + } else if (*rx_off > 64ULL * 1024U) { + rx_buf->erase(0, *rx_off); + *rx_off = 0; + } + } + + [[nodiscard]] Void::Result::Result fill_rx() + { + if (*rx_off < rx_buf->size()) { + return true; + } + rx_buf->clear(); + *rx_off = 0; + std::array tmp{}; + auto n = recv_slice(fd, tmp, *stopping, read_timeout); + if (!n.has_value()) { + return std::unexpected{std::move(n.error())}; + } + if (*n == 0) { + return false; + } + rx_buf->append(tmp.data(), *n); + return true; + } + + [[nodiscard]] Void::Result::Result read_line_crlf( + std::size_t max_len = 8192) + { + for (;;) { + const std::size_t pos = rx_buf->find("\r\n", *rx_off); + if (pos != std::string::npos) { + const std::size_t line_len = pos - *rx_off; + if (line_len > max_len) { + return std::unexpected{make_net_error( + NetErrorCode::protocol_error, + "Net::HttpServer: chunk header line too long")}; + } + std::string line = rx_buf->substr(*rx_off, line_len); + consume_rx(line_len + 2U); + return line; + } + if (rx_buf->size() - *rx_off > max_len) { + return std::unexpected{make_net_error( + NetErrorCode::protocol_error, + "Net::HttpServer: chunk line exceeds limit")}; + } + rx_buf->erase(0, *rx_off); + *rx_off = 0; + std::array tmp{}; + auto n = recv_slice(fd, tmp, *stopping, read_timeout); + if (!n.has_value()) { + return std::unexpected{std::move(n.error())}; + } + if (*n == 0) { + return std::unexpected{make_net_error( + NetErrorCode::protocol_error, + "Net::HttpServer: unexpected EOF in chunked body")}; + } + rx_buf->append(tmp.data(), *n); + } + } + }; + + std::optional BodyReader::content_length() const noexcept + { + return m_state ? m_state->declared_length : std::nullopt; + } + + bool BodyReader::is_chunked() const noexcept + { + return m_state != nullptr && m_state->chunked; + } + + std::uint64_t BodyReader::bytes_read() const noexcept + { + return m_state ? m_state->total_read : 0; + } + + Void::Result::Result + BodyReader::read_some(std::span dst) + { + if (m_state == nullptr || m_state->eof) { + return std::size_t{0}; + } + if (dst.empty()) { + return std::size_t{0}; + } + + if (!m_state->chunked) { + if (m_state->remaining_fixed == 0) { + m_state->eof = true; + return std::size_t{0}; + } + const std::size_t avail = + m_state->rx_buf->size() - *m_state->rx_off; + if (avail > 0) { + const std::size_t take = static_cast( + std::min( + std::min(dst.size(), avail), m_state->remaining_fixed)); + std::memcpy(dst.data(), + m_state->rx_buf->data() + *m_state->rx_off, take); + m_state->consume_rx(take); + m_state->remaining_fixed -= take; + m_state->total_read += take; + if (m_state->remaining_fixed == 0) { + m_state->eof = true; + } + return take; + } + const std::size_t want = static_cast( + std::min(dst.size(), m_state->remaining_fixed)); + auto r = recv_slice( + m_state->fd, + std::span{reinterpret_cast(dst.data()), want}, + *m_state->stopping, m_state->read_timeout); + if (!r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + if (*r == 0) { + return std::unexpected{make_net_error( + NetErrorCode::protocol_error, + "Net::HttpServer: unexpected EOF before Content-Length")}; + } + m_state->remaining_fixed -= *r; + m_state->total_read += *r; + if (m_state->remaining_fixed == 0) { + m_state->eof = true; + } + return *r; + } + + for (;;) { + switch (m_state->chunk_phase) { + case State::ChunkPhase::Header: { + auto line = m_state->read_line_crlf(); + if (!line.has_value()) { + return std::unexpected{std::move(line.error())}; + } + const std::size_t semi = line->find(';'); + std::string_view hex_part = + semi == std::string::npos + ? std::string_view{*line} + : std::string_view{*line}.substr(0, semi); + hex_part = trim_ows(hex_part); + if (hex_part.empty()) { + return std::unexpected{make_net_error( + NetErrorCode::protocol_error, + "Net::HttpServer: empty chunk size")}; + } + std::uint64_t csize = 0; + const auto res = std::from_chars( + hex_part.data(), hex_part.data() + hex_part.size(), + csize, 16); + if (res.ec != std::errc{} || + res.ptr != hex_part.data() + hex_part.size()) { + return std::unexpected{make_net_error( + NetErrorCode::protocol_error, + "Net::HttpServer: invalid chunk size")}; + } + m_state->chunk_remaining = csize; + if (csize == 0) { + m_state->chunk_phase = State::ChunkPhase::Trailers; + } else { + m_state->chunk_phase = State::ChunkPhase::Data; + } + break; + } + case State::ChunkPhase::Data: { + const std::size_t avail = + m_state->rx_buf->size() - *m_state->rx_off; + std::size_t got = 0; + if (avail > 0) { + got = static_cast(std::min( + std::min(dst.size(), avail), + m_state->chunk_remaining)); + std::memcpy(dst.data(), + m_state->rx_buf->data() + *m_state->rx_off, + got); + m_state->consume_rx(got); + } else { + const std::size_t want = static_cast( + std::min(dst.size(), + m_state->chunk_remaining)); + auto r = recv_slice( + m_state->fd, + std::span{ + reinterpret_cast(dst.data()), want}, + *m_state->stopping, m_state->read_timeout); + if (!r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + if (*r == 0) { + return std::unexpected{make_net_error( + NetErrorCode::protocol_error, + "Net::HttpServer: unexpected EOF in chunk data")}; + } + got = *r; + } + m_state->chunk_remaining -= got; + m_state->total_read += got; + if (m_state->chunk_remaining == 0) { + m_state->chunk_phase = State::ChunkPhase::AfterDataCrlf; + } + return got; + } + case State::ChunkPhase::AfterDataCrlf: { + auto line = m_state->read_line_crlf(16); + if (!line.has_value()) { + return std::unexpected{std::move(line.error())}; + } + if (!line->empty()) { + return std::unexpected{make_net_error( + NetErrorCode::protocol_error, + "Net::HttpServer: expected CRLF after chunk")}; + } + m_state->chunk_phase = State::ChunkPhase::Header; + break; + } + case State::ChunkPhase::Trailers: { + for (;;) { + auto line = m_state->read_line_crlf(); + if (!line.has_value()) { + return std::unexpected{std::move(line.error())}; + } + if (line->empty()) { + m_state->chunk_phase = State::ChunkPhase::Done; + m_state->eof = true; + return std::size_t{0}; + } + } + } + case State::ChunkPhase::Done: + m_state->eof = true; + return std::size_t{0}; + } + } + } + + Void::Result::Result + BodyReader::read_to_file(const std::filesystem::path& destination, + std::uint64_t max_bytes) + { + if (m_state == nullptr) { + return std::unexpected{make_net_error( + NetErrorCode::invalid_argument, + "Net::BodyReader::read_to_file: invalid reader state")}; + } + + std::uint64_t effective_limit = max_bytes; + if (effective_limit == 0) { + effective_limit = m_state->default_max_bytes; + } else if (m_state->default_max_bytes > 0) { + effective_limit = + std::min(effective_limit, m_state->default_max_bytes); + } + + if (effective_limit > 0 && m_state->declared_length.has_value() && + *m_state->declared_length > effective_limit) { + return std::unexpected{make_net_error( + NetErrorCode::payload_too_large, + "Net::BodyReader::read_to_file: declared body exceeds limit")}; + } + + std::filesystem::path parent = destination.parent_path(); + if (parent.empty()) { + parent = "."; + } + std::error_code ec; + std::filesystem::create_directories(parent, ec); + if (ec) { + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net::BodyReader: create_directories failed: {}", + ec.message()), + ec)}; + } + + const std::filesystem::path tmp_path = + parent / std::format(".void-upload-{}-{}", + static_cast(::getpid()), + g_temp_upload_seq.fetch_add( + 1, std::memory_order_relaxed)); + OwnedFd out_fd{::open(tmp_path.c_str(), + O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | + O_NOFOLLOW, + 0644)}; + if (!out_fd) { + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net::BodyReader: cannot create temp file: {}", + std::strerror(errno)), + std::error_code{errno, std::generic_category()})}; + } + + auto fail_cleanup = [&](Void::Result::Error err) + -> Void::Result::Result { + out_fd.reset(); + std::error_code rm_ec; + std::filesystem::remove(tmp_path, rm_ec); + return std::unexpected{std::move(err)}; + }; + + std::array buf{}; + std::uint64_t written_total = 0; + for (;;) { + auto n = read_some(buf); + if (!n.has_value()) { + return fail_cleanup(std::move(n.error())); + } + if (*n == 0) { + break; + } + const auto amt = static_cast(*n); + if (effective_limit > 0 && amt > effective_limit - written_total) { + return fail_cleanup(make_net_error( + NetErrorCode::payload_too_large, + "Net::BodyReader::read_to_file: streaming body exceeds " + "limit")); + } + std::size_t off = 0; + while (off < *n) { + const ssize_t w = ::write( + out_fd.get(), + reinterpret_cast(buf.data()) + off, + *n - off); + if (w < 0 && errno == EINTR) { + continue; + } + if (w <= 0) { + return fail_cleanup(make_net_error( + NetErrorCode::io_error, + std::format("Net::BodyReader: write temp file failed: " + "{}", + std::strerror(errno)), + std::error_code{errno, std::generic_category()})); + } + off += static_cast(w); + } + written_total += amt; + } + + if (::fsync(out_fd.get()) != 0) { + return fail_cleanup(make_net_error( + NetErrorCode::io_error, + std::format("Net::BodyReader: fsync failed: {}", + std::strerror(errno)), + std::error_code{errno, std::generic_category()})); + } + const int raw = out_fd.release(); + if (::close(raw) != 0) { + return fail_cleanup(make_net_error( + NetErrorCode::io_error, + std::format("Net::BodyReader: close failed: {}", + std::strerror(errno)), + std::error_code{errno, std::generic_category()})); + } + + std::filesystem::rename(tmp_path, destination, ec); + if (ec) { + std::error_code rm_ec; + std::filesystem::remove(tmp_path, rm_ec); + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net::BodyReader: rename failed: {}", ec.message()), + ec)}; + } + return written_total; + } + + namespace + { + struct StreamingRoute { + Method method; + std::string pattern; + std::vector segments; + StreamingRouteHandler handler; + }; + + struct WorkerEntry { + std::uint64_t id{0}; + std::atomic client_fd{-1}; + std::atomic finished{false}; + std::thread thread{}; + }; + } // namespace + + struct HttpServer::Impl { + HttpServerOptions options{}; + std::optional owned_router{}; + Router* router{nullptr}; + + mutable std::shared_mutex stream_mutex{}; + std::vector streaming_routes{}; + + std::atomic running{false}; + std::atomic stopping{false}; + int listen_fd{-1}; + int wake_fd{-1}; + std::uint16_t bound_port{0}; + std::string bind_addr_str{}; + std::thread accept_thread{}; + + std::mutex workers_mutex{}; + std::condition_variable workers_cv{}; + std::uint64_t next_worker_id{0}; + std::map> workers{}; + + ~Impl() noexcept { shutdown(std::chrono::seconds{5}); } + + void reap_finished_workers() + { + std::vector to_join; + { + std::lock_guard lock{workers_mutex}; + for (auto it = workers.begin(); it != workers.end();) { + if (it->second->finished.load( + std::memory_order_acquire)) { + if (it->second->thread.joinable()) { + to_join.push_back(std::move(it->second->thread)); + } + it = workers.erase(it); + } else { + ++it; + } + } + } + for (auto& t : to_join) { + t.join(); + } + } + + [[nodiscard]] std::optional< + std::pair> + match_streaming(Method m, std::string_view path_view) const + { + const auto segments = split_path(path_view); + std::shared_lock lock{stream_mutex}; + const StreamingRoute* best = nullptr; + RouteParameters best_params; + for (const auto& r : streaming_routes) { + if (r.method != m) { + continue; + } + auto matched = match_segments(r.segments, segments); + if (!matched.has_value()) { + continue; + } + if (best == nullptr || + more_specific_route(r.segments, best->segments)) { + best = &r; + best_params = std::move(*matched); + } + } + if (best == nullptr) { + return std::nullopt; + } + return std::pair{ + best->handler, std::move(best_params)}; + } + + [[nodiscard]] std::vector + collect_allowed_methods(std::string_view path_view) const + { + std::vector methods = router->allowed_methods(path_view); + const auto segments = split_path(path_view); + { + std::shared_lock lock{stream_mutex}; + for (const auto& r : streaming_routes) { + if (match_segments(r.segments, segments).has_value() && + std::ranges::find(methods, r.method) == + methods.end()) { + methods.push_back(r.method); + } + } + } + return methods; + } + + void send_response(int fd, Method req_method, ServerResponse resp, + bool keep_alive) + { + std::string file_path_err; + OwnedFd file_fd; + std::uint64_t body_len = resp.body.size(); + std::string content_type_default; + + if (resp.file_body.has_value()) { + OwnedFd f{::open(resp.file_body->c_str(), + O_RDONLY | O_CLOEXEC | O_NOFOLLOW)}; + if (!f) { + const std::uint16_t err_status = + errno == ENOENT ? 404 : 500; + resp.file_body.reset(); + resp.status = err_status; + resp.headers.clear(); + resp.body = err_status == 404 ? "Not Found" + : "Internal Server Error"; + body_len = resp.body.size(); + } else { + struct stat st{}; + if (::fstat(f.get(), &st) != 0 || + !S_ISREG(st.st_mode)) { + resp.file_body.reset(); + resp.status = 500; + resp.headers.clear(); + resp.body = "Internal Server Error"; + body_len = resp.body.size(); + } else { + file_fd = std::move(f); + body_len = static_cast(st.st_size); + content_type_default = + std::string{content_type_for(*resp.file_body)}; + } + } + } + + std::string head = std::format( + "HTTP/1.1 {} {}\r\nContent-Length: {}\r\nConnection: " + "{}\r\n", + resp.status, reason_phrase(resp.status), body_len, + keep_alive ? "keep-alive" : "close"); + bool has_ct = false; + for (const auto& h : resp.headers) { + if (has_crlf_or_nul(h.name) || has_crlf_or_nul(h.value) || + !is_valid_token(h.name)) { + continue; + } + if (equal_ascii_ci(h.name, "Content-Length") || + equal_ascii_ci(h.name, "Connection") || + equal_ascii_ci(h.name, "Transfer-Encoding")) { + continue; + } + if (equal_ascii_ci(h.name, "Content-Type")) { + has_ct = true; + } + head += h.name; + head += ": "; + head += h.value; + head += "\r\n"; + } + if (!has_ct && !content_type_default.empty()) { + head += "Content-Type: "; + head += content_type_default; + head += "\r\n"; + } + head += "\r\n"; + + if (!send_str(fd, head, options.write_timeout).has_value()) { + return; + } + if (req_method == Method::Head) { + return; + } + if (file_fd) { + std::array buf{}; + std::uint64_t remaining = body_len; + while (remaining > 0) { + const std::size_t want = static_cast( + std::min(remaining, buf.size())); + const ssize_t r = ::read(file_fd.get(), buf.data(), want); + if (r < 0 && errno == EINTR) { + continue; + } + if (r <= 0) { + return; + } + if (!send_all(fd, + std::span{ + buf.data(), + static_cast(r)}, + options.write_timeout) + .has_value()) { + return; + } + remaining -= static_cast(r); + } + return; + } + if (!resp.body.empty()) { + (void)send_str(fd, resp.body, options.write_timeout); + } + } + + void send_error_close(int fd, std::uint16_t status, + std::string_view msg, + std::vector
extra = {}) + { + ServerResponse r; + r.status = status; + r.headers = std::move(extra); + r.body = std::string{msg}; + send_response(fd, Method::Get, std::move(r), false); + (void)::shutdown(fd, SHUT_WR); + } + + void serve_connection(int raw_fd, WorkerEntry& entry) + { + OwnedFd fd_guard{raw_fd}; + std::string rx_buf; + std::size_t rx_off = 0; + + while (!stopping.load(std::memory_order_acquire)) { + // 1. Read request headers up to \r\n\r\n. + std::size_t hdr_end = std::string::npos; + bool peer_eof = false; + bool hdr_too_large = false; + while (true) { + const std::size_t found = rx_buf.find("\r\n\r\n", rx_off); + if (found != std::string::npos) { + if (found - rx_off > options.max_header_bytes) { + hdr_too_large = true; + } + hdr_end = found; + break; + } + if (rx_buf.size() - rx_off > options.max_header_bytes) { + hdr_too_large = true; + break; + } + if (rx_off > 0 && rx_buf.size() == rx_off) { + rx_buf.clear(); + rx_off = 0; + } + std::array chunk{}; + auto nr = recv_slice(fd_guard.get(), chunk, stopping, + options.read_timeout); + if (!nr.has_value()) { + peer_eof = true; + break; + } + if (*nr == 0) { + peer_eof = true; + break; + } + rx_buf.append(chunk.data(), *nr); + } + + if (hdr_too_large) { + send_error_close(fd_guard.get(), 431, + "Request Header Fields Too Large"); + break; + } + if (peer_eof || hdr_end == std::string::npos) { + break; + } + + const std::string_view header_block{ + rx_buf.data() + rx_off, hdr_end - rx_off}; + rx_off = hdr_end + 4U; + + // 2. Parse request line. + const std::size_t first_eol = header_block.find("\r\n"); + const std::string_view req_line = + first_eol == std::string_view::npos + ? header_block + : header_block.substr(0, first_eol); + const std::size_t sp1 = req_line.find(' '); + const std::size_t sp2 = + sp1 == std::string_view::npos + ? std::string_view::npos + : req_line.find(' ', sp1 + 1U); + if (sp1 == std::string_view::npos || + sp2 == std::string_view::npos || + req_line.find(' ', sp2 + 1U) != std::string_view::npos) { + send_error_close(fd_guard.get(), 400, "Bad Request"); + break; + } + const auto method_opt = + parse_method(req_line.substr(0, sp1)); + if (!method_opt.has_value()) { + send_error_close(fd_guard.get(), 501, + "Not Implemented"); + break; + } + const std::string_view target = + req_line.substr(sp1 + 1U, sp2 - sp1 - 1U); + const std::string_view version = req_line.substr(sp2 + 1U); + if ((version != "HTTP/1.1" && version != "HTTP/1.0") || + target.empty() || target.front() != '/' || + has_crlf_or_nul(target)) { + send_error_close(fd_guard.get(), 400, "Bad Request"); + break; + } + + std::string_view raw_path = target; + std::string_view raw_query{}; + if (const std::size_t qpos = target.find('?'); + qpos != std::string_view::npos) { + raw_path = target.substr(0, qpos); + raw_query = target.substr(qpos + 1U); + } + if (const std::size_t hpos = raw_query.find('#'); + hpos != std::string_view::npos) { + raw_query = raw_query.substr(0, hpos); + } + + // 3. Parse & validate headers (RFC 9112 smuggling rules). + std::vector
headers; + bool has_te = false; + bool chunked = false; + bool bad_headers = false; + bool too_many_headers = false; + bool expect_continue = false; + std::optional content_length; + std::optional conn_keep_alive; + + std::size_t hpos = + first_eol == std::string_view::npos + ? header_block.size() + : first_eol + 2U; + while (hpos < header_block.size()) { + const std::size_t eol = header_block.find("\r\n", hpos); + const std::string_view line = + eol == std::string_view::npos + ? header_block.substr(hpos) + : header_block.substr(hpos, eol - hpos); + hpos = (eol == std::string_view::npos) + ? header_block.size() + : (eol + 2U); + const std::size_t colon = line.find(':'); + if (colon == std::string_view::npos) { + bad_headers = true; + break; + } + const std::string_view hname = line.substr(0, colon); + const std::string_view hval = + trim_ows(line.substr(colon + 1U)); + if (!is_valid_token(hname) || has_crlf_or_nul(hval)) { + bad_headers = true; + break; + } + if (headers.size() >= options.max_headers) { + too_many_headers = true; + break; + } + + if (equal_ascii_ci(hname, "Content-Length")) { + std::uint64_t cl = 0; + if (!parse_u64_decimal(hval, cl)) { + bad_headers = true; + break; + } + if (content_length.has_value() && + *content_length != cl) { + bad_headers = true; + break; + } + content_length = cl; + } else if (equal_ascii_ci(hname, "Transfer-Encoding")) { + has_te = true; + if (contains_ascii_ci(hval, "chunked")) { + chunked = true; + } + } else if (equal_ascii_ci(hname, "Connection")) { + if (contains_ascii_ci(hval, "close")) { + conn_keep_alive = false; + } else if (contains_ascii_ci(hval, "keep-alive")) { + conn_keep_alive = true; + } + } else if (equal_ascii_ci(hname, "Expect")) { + if (equal_ascii_ci(hval, "100-continue")) { + expect_continue = true; + } + } + headers.push_back( + Header{std::string{hname}, std::string{hval}}); + } + + if (too_many_headers) { + send_error_close(fd_guard.get(), 431, + "Request Header Fields Too Large"); + break; + } + if (bad_headers || (has_te && content_length.has_value())) { + send_error_close(fd_guard.get(), 400, "Bad Request"); + break; + } + if (has_te && !chunked) { + send_error_close(fd_guard.get(), 501, + "Not Implemented"); + break; + } + + bool keep_alive = + conn_keep_alive.has_value() + ? *conn_keep_alive + : (version == "HTTP/1.1"); + if (stopping.load(std::memory_order_acquire)) { + keep_alive = false; + } + + // 4. Check streaming route vs buffered Router. + auto streaming_match = + match_streaming(*method_opt, raw_path); + if (!streaming_match.has_value()) { + // Enforce buffered max_body_bytes before reading body. + if (!chunked && content_length.has_value() && + *content_length > options.max_body_bytes) { + send_error_close(fd_guard.get(), 413, + "Payload Too Large"); + break; + } + } else { + if (!chunked && content_length.has_value() && + options.max_streaming_body_bytes > 0 && + *content_length > + options.max_streaming_body_bytes) { + send_error_close(fd_guard.get(), 413, + "Payload Too Large"); + break; + } + } + + BodyReader::State reader_state; + reader_state.fd = fd_guard.get(); + reader_state.stopping = &stopping; + reader_state.read_timeout = options.read_timeout; + reader_state.default_max_bytes = + streaming_match.has_value() + ? options.max_streaming_body_bytes + : options.max_body_bytes; + reader_state.rx_buf = &rx_buf; + reader_state.rx_off = &rx_off; + reader_state.chunked = chunked; + reader_state.declared_length = content_length; + reader_state.remaining_fixed = + content_length.value_or(0ULL); + reader_state.eof = + (!chunked && reader_state.remaining_fixed == 0); + BodyReader body_reader{reader_state}; + + if (expect_continue && + (chunked || reader_state.remaining_fixed > 0)) { + if (!send_str(fd_guard.get(), + "HTTP/1.1 100 Continue\r\n\r\n", + options.write_timeout) + .has_value()) { + break; + } + } + + if (streaming_match.has_value()) { + ServerRequest req; + req.method = *method_opt; + req.path = std::string{raw_path}; + req.headers = std::move(headers); + req.parameters = std::move(streaming_match->second); + req.query = std::string{raw_query}; + + auto route_res = + streaming_match->first(req, body_reader); + if (!route_res.has_value()) { + if (route_res.error().kind() == + Void::Result::ErrorKind::exhausted) { + send_error_close(fd_guard.get(), 413, + "Payload Too Large"); + } else { + send_error_close(fd_guard.get(), 500, + "Internal Server Error"); + } + break; + } + if (!reader_state.eof) { + keep_alive = false; + } + send_response(fd_guard.get(), *method_opt, + std::move(*route_res), keep_alive); + if (!keep_alive) { + break; + } + continue; + } + + // Buffered body read (respecting max_body_bytes on both + // Content-Length and chunked transfer encoding). + std::string body_str; + bool payload_too_large = false; + bool body_io_err = false; + if (chunked || reader_state.remaining_fixed > 0) { + if (!chunked) { + body_str.reserve(static_cast( + reader_state.remaining_fixed)); + } + std::array tmp{}; + for (;;) { + auto nr = body_reader.read_some(tmp); + if (!nr.has_value()) { + body_io_err = true; + break; + } + if (*nr == 0) { + break; + } + if (body_str.size() + *nr > + options.max_body_bytes) { + payload_too_large = true; + break; + } + body_str.append( + reinterpret_cast(tmp.data()), *nr); + } + } + if (payload_too_large) { + send_error_close(fd_guard.get(), 413, + "Payload Too Large"); + break; + } + if (body_io_err) { + break; + } + + Method dispatch_method = *method_opt; + ServerRequest req; + req.method = dispatch_method; + req.path = std::string{raw_path}; + req.headers = std::move(headers); + req.body = std::move(body_str); + req.query = std::string{raw_query}; + + auto dispatched = router->dispatch(req); + if (!dispatched.has_value()) { + send_error_close(fd_guard.get(), 500, + "Internal Server Error"); + break; + } + if (!dispatched->has_value() && + dispatch_method == Method::Head) { + req.method = Method::Get; + dispatched = router->dispatch(req); + if (!dispatched.has_value()) { + send_error_close(fd_guard.get(), 500, + "Internal Server Error"); + break; + } + } + if (!dispatched->has_value()) { + const auto allowed = collect_allowed_methods(raw_path); + if (!allowed.empty()) { + std::string allow_hdr; + for (std::size_t i = 0; i < allowed.size(); ++i) { + if (i > 0) allow_hdr += ", "; + allow_hdr += method_string(allowed[i]); + } + send_response( + fd_guard.get(), *method_opt, + ServerResponse{ + .status = 405, + .headers = {Header{"Allow", + std::move(allow_hdr)}}, + .body = "Method Not Allowed"}, + keep_alive); + } else { + send_response( + fd_guard.get(), *method_opt, + ServerResponse{.status = 404, + .body = "Not Found"}, + keep_alive); + } + if (!keep_alive) { + break; + } + continue; + } + + send_response(fd_guard.get(), *method_opt, + std::move(**dispatched), keep_alive); + if (!keep_alive) { + break; + } + } + + entry.client_fd.store(-1, std::memory_order_release); + fd_guard.reset(); + } + + void accept_loop() + { + while (!stopping.load(std::memory_order_acquire)) { + std::array pfds{{ + {.fd = listen_fd, .events = POLLIN, .revents = 0}, + {.fd = wake_fd, .events = POLLIN, .revents = 0}, + }}; + const int pr = ::poll(pfds.data(), pfds.size(), 100); + if (pr < 0) { + if (errno == EINTR) { + continue; + } + break; + } + if ((pfds[1].revents & POLLIN) != 0) { + std::uint64_t val = 0; + (void)::read(wake_fd, &val, sizeof(val)); + } + if (stopping.load(std::memory_order_acquire)) { + break; + } + if ((pfds[0].revents & POLLIN) == 0) { + reap_finished_workers(); + continue; + } + + for (;;) { +#ifdef SOCK_CLOEXEC + int client_fd = ::accept4(listen_fd, nullptr, nullptr, + SOCK_CLOEXEC); +#else + int client_fd = ::accept(listen_fd, nullptr, nullptr); + if (client_fd >= 0) { + (void)::fcntl(client_fd, F_SETFD, FD_CLOEXEC); + } +#endif + if (client_fd < 0) { + if (errno == EINTR) { + continue; + } + break; + } + + reap_finished_workers(); + std::lock_guard lock{workers_mutex}; + if (stopping.load(std::memory_order_acquire) || + workers.size() >= + options.max_concurrent_connections) { + // Unlock or immediately decline without unbounded + // thread creation. + const std::string_view busy = + "HTTP/1.1 503 Service Unavailable\r\n" + "Content-Length: 19\r\n" + "Connection: close\r\n\r\n" + "Service Unavailable"; + (void)::send(client_fd, busy.data(), busy.size(), + MSG_NOSIGNAL); + (void)::close(client_fd); + continue; + } + const std::uint64_t id = ++next_worker_id; + auto entry = std::make_unique(); + entry->id = id; + entry->client_fd.store(client_fd, + std::memory_order_release); + WorkerEntry* raw_entry = entry.get(); + entry->thread = + std::thread([this, raw_entry, client_fd]() { + serve_connection(client_fd, *raw_entry); + raw_entry->finished.store( + true, std::memory_order_release); + std::lock_guard lk{workers_mutex}; + workers_cv.notify_all(); + }); + workers.emplace(id, std::move(entry)); + } + } + } + + void shutdown(std::chrono::milliseconds drain_timeout) noexcept + { + const bool was_running = + running.load(std::memory_order_acquire); + if (!was_running && listen_fd < 0 && + !accept_thread.joinable()) { + return; + } + stopping.store(true, std::memory_order_release); + if (wake_fd >= 0) { + const std::uint64_t one = 1; + (void)::write(wake_fd, &one, sizeof(one)); + } + if (accept_thread.joinable()) { + accept_thread.join(); + } + if (listen_fd >= 0) { + (void)::close(listen_fd); + listen_fd = -1; + } + if (wake_fd >= 0) { + (void)::close(wake_fd); + wake_fd = -1; + } + + std::vector to_join; + { + std::unique_lock lock{workers_mutex}; + const auto all_finished = [this]() { + for (const auto& [id, w] : workers) { + (void)id; + if (!w->finished.load(std::memory_order_acquire)) { + return false; + } + } + return true; + }; + if (drain_timeout > std::chrono::milliseconds::zero()) { + (void)workers_cv.wait_for(lock, drain_timeout, + all_finished); + } + for (const auto& [id, w] : workers) { + (void)id; + const int cfd = w->client_fd.exchange( + -1, std::memory_order_acq_rel); + if (cfd >= 0) { + (void)::shutdown(cfd, SHUT_RDWR); + } + } + for (auto& [id, w] : workers) { + (void)id; + if (w->thread.joinable()) { + to_join.push_back(std::move(w->thread)); + } + } + } + for (auto& t : to_join) { + t.join(); + } + { + std::lock_guard lock{workers_mutex}; + workers.clear(); + } + bound_port = 0; + bind_addr_str.clear(); + running.store(false, std::memory_order_release); + stopping.store(false, std::memory_order_release); + } + }; + + HttpServer::HttpServer(HttpServerOptions options) + : m_impl(std::make_unique()) + { + m_impl->options = std::move(options); + m_impl->owned_router.emplace(); + m_impl->router = &(*m_impl->owned_router); + } + + HttpServer::HttpServer(Router& external_router, HttpServerOptions options) + : m_impl(std::make_unique()) + { + m_impl->options = std::move(options); + m_impl->router = &external_router; + } + + HttpServer::~HttpServer() noexcept = default; + HttpServer::HttpServer(HttpServer&&) noexcept = default; + HttpServer& HttpServer::operator=(HttpServer&&) noexcept = default; + + Router& HttpServer::router() noexcept { return *m_impl->router; } + + Void::Result::Result + HttpServer::add_route(Method method, std::string pattern, + RouteHandler handler) + { + return m_impl->router->add(method, std::move(pattern), + std::move(handler)); + } + + Void::Result::Result + HttpServer::add_streaming_route(Method method, std::string pattern, + StreamingRouteHandler handler) + { + if (!handler) { + return std::unexpected{make_net_error( + NetErrorCode::invalid_argument, + "Net::HttpServer: streaming route handler is empty")}; + } + auto compiled = compile_route_pattern(pattern); + if (!compiled.has_value()) { + return std::unexpected{std::move(compiled.error())}; + } + std::unique_lock lock{m_impl->stream_mutex}; + const auto dup = std::ranges::find_if( + m_impl->streaming_routes, [&](const StreamingRoute& r) { + return r.method == method && + same_route_shape(r.segments, *compiled); + }); + if (dup != m_impl->streaming_routes.end()) { + return std::unexpected{make_net_error( + NetErrorCode::invalid_argument, + "Net::HttpServer: duplicate streaming route")}; + } + m_impl->streaming_routes.push_back(StreamingRoute{ + method, std::move(pattern), std::move(*compiled), + std::move(handler)}); + return {}; + } + + Void::Result::Result HttpServer::start() + { + if (m_impl->running.load(std::memory_order_acquire)) { + return std::unexpected{make_net_error( + NetErrorCode::invalid_argument, + "Net::HttpServer::start: server is already running")}; + } + if (m_impl->options.max_concurrent_connections == 0 || + m_impl->options.max_header_bytes == 0 || + m_impl->options.max_headers == 0) { + return std::unexpected{make_net_error( + NetErrorCode::invalid_argument, + "Net::HttpServer::start: limits must be positive")}; + } + + const std::string host = m_impl->options.bind_host.empty() + ? std::string{"127.0.0.1"} + : m_impl->options.bind_host; + const std::string port_str = std::to_string(m_impl->options.port); + + struct addrinfo hints{}; + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags = AI_PASSIVE; + struct addrinfo* res = nullptr; + const int gai = ::getaddrinfo(host.c_str(), port_str.c_str(), &hints, &res); + if (gai != 0 || res == nullptr) { + return std::unexpected{make_net_error( + NetErrorCode::connect_failed, + std::format("Net::HttpServer::start: getaddrinfo '{}' failed: " + "{}", + host, ::gai_strerror(gai)))}; + } + + OwnedFd listen_guard; + int last_errno = 0; + for (struct addrinfo* p = res; p != nullptr; p = p->ai_next) { +#ifdef SOCK_CLOEXEC + int fd = ::socket(p->ai_family, p->ai_socktype | SOCK_CLOEXEC, + p->ai_protocol); +#else + int fd = ::socket(p->ai_family, p->ai_socktype, p->ai_protocol); + if (fd >= 0) { + (void)::fcntl(fd, F_SETFD, FD_CLOEXEC); + } +#endif + if (fd < 0) { + last_errno = errno; + continue; + } + OwnedFd cand{fd}; + int yes = 1; + (void)::setsockopt(cand.get(), SOL_SOCKET, SO_REUSEADDR, &yes, + sizeof(yes)); + if (::bind(cand.get(), p->ai_addr, p->ai_addrlen) == 0 && + ::listen(cand.get(), m_impl->options.listen_backlog) == 0) { + listen_guard = std::move(cand); + break; + } + last_errno = errno; + } + ::freeaddrinfo(res); + + if (!listen_guard) { + return std::unexpected{make_net_error( + NetErrorCode::connect_failed, + std::format("Net::HttpServer::start: bind/listen on {}:{} " + "failed: {}", + host, m_impl->options.port, + std::strerror(last_errno)), + std::error_code{last_errno, std::generic_category()})}; + } + + (void)::fcntl(listen_guard.get(), F_SETFL, + ::fcntl(listen_guard.get(), F_GETFL, 0) | O_NONBLOCK); + + struct sockaddr_storage ss{}; + socklen_t slen = sizeof(ss); + if (::getsockname(listen_guard.get(), reinterpret_cast(&ss), + &slen) != 0) { + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net::HttpServer::start: getsockname failed: {}", + std::strerror(errno)), + std::error_code{errno, std::generic_category()})}; + } + + std::array ip_buf{}; + std::uint16_t actual_port = 0; + if (ss.ss_family == AF_INET) { + const auto* s4 = reinterpret_cast(&ss); + actual_port = ntohs(s4->sin_port); + (void)::inet_ntop(AF_INET, &s4->sin_addr, ip_buf.data(), + ip_buf.size()); + m_impl->bind_addr_str = ip_buf.data(); + } else if (ss.ss_family == AF_INET6) { + const auto* s6 = reinterpret_cast(&ss); + actual_port = ntohs(s6->sin6_port); + (void)::inet_ntop(AF_INET6, &s6->sin6_addr, ip_buf.data(), + ip_buf.size()); + m_impl->bind_addr_str = std::format("[{}]", ip_buf.data()); + } + + int efd = ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); + if (efd < 0) { + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net::HttpServer::start: eventfd failed: {}", + std::strerror(errno)), + std::error_code{errno, std::generic_category()})}; + } + + m_impl->listen_fd = listen_guard.release(); + m_impl->wake_fd = efd; + m_impl->bound_port = actual_port; + m_impl->stopping.store(false, std::memory_order_release); + m_impl->running.store(true, std::memory_order_release); + m_impl->accept_thread = + std::thread([impl = m_impl.get()]() { impl->accept_loop(); }); + return {}; + } + + void HttpServer::shutdown(std::chrono::milliseconds drain_timeout) noexcept + { + if (m_impl) { + m_impl->shutdown(drain_timeout); + } + } + + bool HttpServer::running() const noexcept + { + return m_impl && m_impl->running.load(std::memory_order_acquire); + } + + std::uint16_t HttpServer::bound_port() const noexcept + { + return m_impl ? m_impl->bound_port : 0; + } + + std::string HttpServer::bind_address() const + { + return m_impl ? m_impl->bind_addr_str : std::string{}; + } + + std::string HttpServer::base_url() const + { + if (!m_impl || m_impl->bound_port == 0) { + return {}; + } + return std::format("http://{}:{}", m_impl->bind_addr_str, + m_impl->bound_port); + } + +} // namespace Void::Net diff --git a/src/Net/Server.cpp b/src/Net/Server.cpp index 19460e6..1def1ab 100644 --- a/src/Net/Server.cpp +++ b/src/Net/Server.cpp @@ -260,6 +260,21 @@ namespace Void::Net 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 ServerResponse::header(std::string_view name) const noexcept { @@ -334,6 +349,25 @@ namespace Void::Net return std::optional{std::move(*response)}; } + std::vector 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 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::shared_lock lock{mutex_}; diff --git a/src/Net/module.cmake b/src/Net/module.cmake index 5cffbd2..7708572 100644 --- a/src/Net/module.cmake +++ b/src/Net/module.cmake @@ -9,3 +9,13 @@ void_add_module(Net OpenSSL::Crypto 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 "$<$:-Wno-tsan>" + ) +endif() diff --git a/src/System/DirectoryWatcher.cpp b/src/System/DirectoryWatcher.cpp new file mode 100644 index 0000000..e59bece --- /dev/null +++ b/src/System/DirectoryWatcher.cpp @@ -0,0 +1,833 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__linux__) +#include +#include +#include +#include +#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 wd_to_path{}; + std::map path_to_wd{}; + std::unordered_map pending_moves{}; + std::deque 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 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> 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 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 + drain_inotify_locked() + { + alignas(struct inotify_event) std::array 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( + buf.data() + offset); + process_inotify_event_locked(ev); + offset += static_cast( + 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) noexcept + : impl_(std::move(impl)) +{ +} + +DirectoryWatcher::~DirectoryWatcher() noexcept = default; +DirectoryWatcher::DirectoryWatcher(DirectoryWatcher&&) noexcept = default; +DirectoryWatcher& + DirectoryWatcher::operator=(DirectoryWatcher&&) noexcept = default; + +Void::Result::Result + 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->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, 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 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( + 1, + std::chrono::duration_cast( + wait_until - now) + .count()); + std::array pfds{{ + {ifd, POLLIN, 0}, + {efd, POLLIN, 0}, + }}; + const int rc = + ::poll(pfds.data(), pfds.size(), static_cast(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 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 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) noexcept + : impl_(std::move(impl)) +{ +} + +DirectoryWatcher::~DirectoryWatcher() noexcept = default; +DirectoryWatcher::DirectoryWatcher(DirectoryWatcher&&) noexcept = default; +DirectoryWatcher& + DirectoryWatcher::operator=(DirectoryWatcher&&) noexcept = default; + +Void::Result::Result + 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, 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 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 \ No newline at end of file diff --git a/src/System/Process.cpp b/src/System/Process.cpp index 5136fbd..70cc25e 100644 --- a/src/System/Process.cpp +++ b/src/System/Process.cpp @@ -40,6 +40,7 @@ Child::Child(Child&&) noexcept = default; Child& Child::operator=(Child&&) noexcept = default; bool Child::valid() 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::pgid() const noexcept { return -1; } bool Child::owns_process_group() const noexcept { return false; } @@ -142,6 +143,13 @@ Void::Result::Result reexec( return Void::Result::fail("Process::reexec: not implemented on Windows"); } +Void::Result::Result 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 #else // POSIX @@ -150,6 +158,9 @@ Void::Result::Result reexec( #include #include #include +#if defined(__linux__) && __has_include() +#include +#endif #include #include #include @@ -468,26 +479,102 @@ void write_child_failure(int err_fd, int phase, int err) noexcept 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, pid_t pgid, bool owns_group, + bool leader_reaped, int sig, int& out_errno) noexcept { + bool delivered = false; + out_errno = 0; if (owns_group && pgid > 0) { if (::kill(-pgid, sig) == 0) { - return true; - } - out_errno = errno; - if (out_errno != ESRCH && out_errno != EPERM) { - return false; + delivered = true; + } else { + out_errno = errno; + if (out_errno != ESRCH && out_errno != EPERM) { + return false; + } } } - if (::kill(pid, sig) == 0) { - return true; + if (!leader_reaped && pid > 0) { + if (::kill(pid, sig) == 0) { + delivered = true; + } else { + out_errno = errno; + } } - out_errno = errno; - return false; + return delivered; } [[nodiscard]] std::optional @@ -706,6 +793,13 @@ Child& Child::operator=(Child&& other) noexcept bool Child::valid() const noexcept { return pid_ > 0; } 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(pgid_)); + } + return running(); +} long long Child::pid() const noexcept { return pid_; } long long Child::pgid() const noexcept { return pgid_; } bool Child::owns_process_group() const noexcept { return owns_group_; } @@ -738,7 +832,7 @@ Void::Result::Result Child::send_signal(int sig) noex Void::System::SystemErrorCode::invalid_argument, "Process::Child::send_signal: invalid child")}; } - if (reaped_) { + if (reaped_ && (!owns_group_ || !process_group_alive())) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::busy, "Process::Child::send_signal: child already reaped")}; @@ -747,6 +841,7 @@ Void::Result::Result Child::send_signal(int sig) noex if (!signal_target(static_cast(pid_), static_cast(pgid_), owns_group_, + reaped_, sig, err)) { return std::unexpected{Void::System::make_system_error( @@ -798,35 +893,37 @@ Void::Result::Result Void::System::SystemErrorCode::invalid_argument, "Process::Child::terminate: invalid child")}; } - if (reaped_) { + + const pid_t target_pid = static_cast(pid_); + const pid_t target_pgid = static_cast(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_; } const auto effective_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; - (void)signal_target(static_cast(pid_), - static_cast(pgid_), - owns_group_, - SIGTERM, - sig_err); + (void)signal_target( + target_pid, target_pgid, group_owned, reaped_, SIGTERM, sig_err); const auto grace_deadline = std::chrono::steady_clock::now() + effective_grace; while (std::chrono::steady_clock::now() < grace_deadline) { - auto polled = try_wait(); - if (!polled.has_value()) { - return std::unexpected{polled.error()}; - } - if (polled->has_value()) { - return **polled; + if (group_finished()) { + return cached_status_; } const auto rem = std::chrono::duration_cast( grace_deadline - std::chrono::steady_clock::now()); @@ -834,38 +931,61 @@ Void::Result::Result break; } 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()) { - return std::unexpected{polled.error()}; - } else if (polled->has_value()) { - return **polled; + if (group_finished()) { + return cached_status_; } - (void)signal_target(static_cast(pid_), - static_cast(pgid_), - owns_group_, - SIGKILL, - sig_err); + (void)signal_target( + target_pid, target_pgid, group_owned, reaped_, SIGKILL, sig_err); - int raw = 0; - for (;;) { - const pid_t w = ::waitpid(static_cast(pid_), &raw, 0); - if (w == static_cast(pid_)) { - cached_status_ = decode_wait_status(raw); - reaped_ = true; - return cached_status_; + if (!reaped_) { + int raw = 0; + for (;;) { + const pid_t w = ::waitpid(target_pid, &raw, 0); + if (w == target_pid) { + cached_status_ = decode_wait_status(raw); + 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 Child::wait_blocking( @@ -950,7 +1070,7 @@ void Child::reset_and_reap() noexcept stdin_.reset(); stdout_.reset(); stderr_.reset(); - if (pid_ > 0 && !reaped_) { + if (pid_ > 0 && (!reaped_ || process_group_alive())) { (void)terminate(kill_grace_); } pid_ = -1; @@ -1643,6 +1763,24 @@ Void::Result::Result err)}; } +Void::Result::Result 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 #endif // _WIN32 diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 48c2ecb..2759bda 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -133,6 +133,9 @@ if(_all_generated) if(TARGET OpenSSL::Crypto) target_link_libraries(VoidTests PRIVATE OpenSSL::Crypto) endif() + if(TARGET OpenSSL::SSL) + target_link_libraries(VoidTests PRIVATE OpenSSL::SSL) + endif() if(TARGET SQLite3::SQLite3) target_link_libraries(VoidTests PRIVATE SQLite3::SQLite3) endif() diff --git a/tests/helpers/ProcessHelper.cpp b/tests/helpers/ProcessHelper.cpp index b34ce5a..e020dbf 100644 --- a/tests/helpers/ProcessHelper.cpp +++ b/tests/helpers/ProcessHelper.cpp @@ -194,6 +194,57 @@ int mode_ignore_sigterm(int argc, char** argv) return 0; } +int mode_grandchild_ignore_sigterm(int argc, char** argv) +{ + if (argc < 3) { + return usage_error("grandchild-ignore-sigterm requires "); + } + 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) { if (argc != 3) { @@ -485,6 +536,9 @@ int main(int argc, char** argv) if (mode == "ignore-sigterm") { return mode_ignore_sigterm(argc, argv); } + if (mode == "grandchild-ignore-sigterm") { + return mode_grandchild_ignore_sigterm(argc, argv); + } if (mode == "simultaneous-io") { return mode_simultaneous_io(argc, argv); } diff --git a/tests/package/ArchiveOnly/main.cpp b/tests/package/ArchiveOnly/main.cpp index ef36ad9..a0be98a 100644 --- a/tests/package/ArchiveOnly/main.cpp +++ b/tests/package/ArchiveOnly/main.cpp @@ -12,8 +12,12 @@ int main() .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; - if (!Void::Archive::create_archive(sink, entries).has_value()) { + if (!Void::Archive::create(sink, entries, opts).has_value()) { return 1; } Void::Archive::SpanByteSource src{sink.bytes()}; diff --git a/tests/package/CryptoOnly/main.cpp b/tests/package/CryptoOnly/main.cpp index 97b2726..cb13b84 100644 --- a/tests/package/CryptoOnly/main.cpp +++ b/tests/package/CryptoOnly/main.cpp @@ -9,23 +9,33 @@ int main() if (!digest.has_value() || digest->size() != 32) { return 1; } - auto key = Void::Crypto::Ed25519PrivateKey::generate(); - if (!key.has_value()) { - return 2; - } - auto pub = key->public_key(); - if (!pub.has_value()) { - return 3; + auto b2 = Void::Crypto::blake2b256("abc"); + if (!b2.has_value() || b2->size() != 32) { + return 6; } const std::array msg{std::byte{1}, std::byte{2}, std::byte{3}, std::byte{4}}; - auto sig = Void::Crypto::sign_ed25519(msg, *key); - if (!sig.has_value()) { - return 4; + auto mac = Void::Crypto::hmac_sha256(msg, msg); + if (!mac.has_value() || mac->size() != Void::Crypto::HmacSha256Size) { + return 7; } - auto ok = Void::Crypto::verify_ed25519(msg, *sig, *pub); - if (!ok.has_value() || !*ok) { - return 5; + if (Void::Crypto::has_openssl_backend()) { + auto key = Void::Crypto::Ed25519PrivateKey::generate(); + 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; } diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index e23d018..6bbc122 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -292,6 +292,14 @@ if(_has_fsm) -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) 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. has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core) if(_has_foundation) diff --git a/tests/package/NetOnly/CMakeLists.txt b/tests/package/NetOnly/CMakeLists.txt new file mode 100644 index 0000000..30910ce --- /dev/null +++ b/tests/package/NetOnly/CMakeLists.txt @@ -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) diff --git a/tests/package/NetOnly/main.cpp b/tests/package/NetOnly/main.cpp new file mode 100644 index 0000000..0390d70 --- /dev/null +++ b/tests/package/NetOnly/main.cpp @@ -0,0 +1,31 @@ +#include +#include + +#include + +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; +} diff --git a/tests/package/TestingNativeGxx/dir_a/dup.cpp b/tests/package/TestingNativeGxx/dir_a/dup.cpp new file mode 100644 index 0000000..f2fa72a --- /dev/null +++ b/tests/package/TestingNativeGxx/dir_a/dup.cpp @@ -0,0 +1,12 @@ +#include +#include + +VOID_TEST(NativeGxx, from_dir_a_first) +{ + Void::Testing::expect_eq(10 + 5, 15); +} + +VOID_TEST(NativeGxx, duplicate_name_test) +{ + Void::Testing::expect(true); +} \ No newline at end of file diff --git a/tests/package/TestingNativeGxx/dir_b/dup.cpp b/tests/package/TestingNativeGxx/dir_b/dup.cpp new file mode 100644 index 0000000..06e0e4d --- /dev/null +++ b/tests/package/TestingNativeGxx/dir_b/dup.cpp @@ -0,0 +1,12 @@ +#include +#include + +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); +} \ No newline at end of file diff --git a/tests/standalone/Archive/Archive.cpp b/tests/standalone/Archive/Archive.cpp index bbfd108..32805c8 100644 --- a/tests/standalone/Archive/Archive.cpp +++ b/tests/standalone/Archive/Archive.cpp @@ -3,8 +3,10 @@ #include #include +#include #include #include +#include #include #include #include @@ -13,23 +15,95 @@ #include #include #include +#include +#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE #include #include +#endif namespace { + enum class FixtureEntryType { Regular, Directory, Symlink }; + struct ArchiveEntry { std::string_view path; std::string_view contents; - unsigned int type{AE_IFREG}; + FixtureEntryType type{FixtureEntryType::Regular}; std::string_view link; }; - void write_archive(const std::filesystem::path &path, - std::span - entries) + void write_octal(std::span dst, std::uint64_t val) { + dst.back() = '\0'; + std::size_t pos = dst.size() - 1; + while (pos > 0) { + --pos; + dst[pos] = static_cast('0' + (val & 7ULL)); + val >>= 3ULL; + } + } + + void write_raw_tar(const std::filesystem::path& path, + std::span entries) + { + std::ofstream out{path, std::ios::binary | std::ios::trunc}; + Void::Testing::require(out.is_open()); + + for (const auto& spec : entries) { + std::array hdr{}; + std::memcpy(hdr.data(), spec.path.data(), + std::min(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(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(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(spec.contents.size())); + const std::size_t rem = spec.contents.size() % 512U; + if (rem != 0) { + std::array pad{}; + out.write(pad.data(), + static_cast(512U - rem)); + } + } + } + std::array eof{}; + out.write(eof.data(), eof.size()); + out.close(); + Void::Testing::require(out.good()); + } + + void write_archive(const std::filesystem::path& path, + std::span entries) + { +#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE using Writer = std::unique_ptr; using Entry = std::unique_ptr; @@ -47,14 +121,21 @@ namespace writer.get(), path.c_str()) == ARCHIVE_OK); #endif - for (const auto &specification : entries) { + for (const auto& specification : entries) { Entry entry{archive_entry_new(), &archive_entry_free}; const std::string entryPath{specification.path}; archive_entry_set_pathname(entry.get(), entryPath.c_str()); - archive_entry_set_filetype(entry.get(), specification.type); + 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( - entry.get(), specification.type == AE_IFDIR ? 0755 : 0644); - if (specification.type == AE_IFREG) { + entry.get(), + specification.type == FixtureEntryType::Directory ? 0755 : 0644); + if (specification.type == FixtureEntryType::Regular) { archive_entry_set_size( entry.get(), static_cast(specification.contents.size())); @@ -78,18 +159,22 @@ namespace 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, - 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}}; write_archive(path, entries); } [[nodiscard]] bool - extraction_file_visible(const std::filesystem::path &destination) + extraction_file_visible(const std::filesystem::path& destination) { std::error_code 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_"}; const auto source = temporary / "directory.tar.zst"; const auto destination = temporary / "output"; - const std::array entries{ArchiveEntry{"bin/", {}, AE_IFDIR}, - ArchiveEntry{"bin/tool", "payload"}}; + const std::array entries{ + ArchiveEntry{"bin/", {}, FixtureEntryType::Directory}, + ArchiveEntry{"bin/tool", "payload"}}; write_archive(source, entries); auto extracted = Void::Archive::extract(source, destination); @@ -154,7 +240,8 @@ Void::Testing::Test archive_rejects_traversal_and_links() Void::Testing::expect( !std::filesystem::exists(temporary.path() / "escape")); 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::Archive::extract(symlink, temporary / "out2").has_value()); const auto trailingFile = temporary / "trailing-file.tar.zst"; diff --git a/tests/standalone/Archive/ArchiveHardening.cpp b/tests/standalone/Archive/ArchiveHardening.cpp index 9c2754a..878f646 100644 --- a/tests/standalone/Archive/ArchiveHardening.cpp +++ b/tests/standalone/Archive/ArchiveHardening.cpp @@ -3,12 +3,16 @@ #include #include +#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE #include #include +#endif +#include #include #include #include +#include #include #include #include @@ -16,6 +20,8 @@ #include #include #include +#include +#include #include namespace @@ -39,6 +45,72 @@ namespace std::istreambuf_iterator{}}; } + void write_octal(std::span 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('0' + (val & 7ULL)); + val >>= 3ULL; + } + } + + std::vector make_raw_tar_ustar( + std::span> + entries) + { + std::vector out; + for (const auto& [path, content, typeflag, link] : entries) { + std::array hdr{}; + std::memcpy(hdr.data(), path.data(), + std::min(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(typeflag); + if (!link.empty()) { + std::memcpy(hdr.data() + 157, link.data(), + std::min(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(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 make_raw_tar( std::span> @@ -95,6 +167,7 @@ namespace Void::Testing::require(archive_write_close(writer.get()) == ARCHIVE_OK); return out; } +#endif } // namespace 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_b; - CreationOptions copts{.compression = ArchiveCompression::Zstd, + CreationOptions copts{.compression = default_test_compression(), .reproducible = true}; Void::Testing::require(create_archive(sink_a, order_a, 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()); } - // 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, + 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(ArchiveErrorCode::unsafe_entry)); + +#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE const std::array< std::tuple, @@ -184,26 +275,27 @@ Void::Testing::Test archive_reader_reproducible_skip_and_forensic_listing() {"foo/child", "nested", AE_IFREG, ""}, }}; const auto raw = make_raw_tar(conflict_entries); - SpanByteSource src{raw}; - auto listed = list_entries(src, {}, false); - Void::Testing::require(!listed.has_value()); + SpanByteSource src_la{raw}; + auto listed_la = list_entries(src_la, {}, false); + Void::Testing::require(!listed_la.has_value()); Void::Testing::expect_eq( - listed.error().code().value, + listed_la.error().code().value, static_cast(ArchiveErrorCode::unsafe_entry)); +#endif } // 5. Normal vs forensic listing + sanitized diagnostics. { const std::array< - std::tuple, 3> - mixed{{ - {"safe.txt", "ok", AE_IFREG, ""}, - {"bad\nlink", "", AE_IFLNK, "/etc/passwd"}, - {"../escape", "nope", AE_IFREG, ""}, + mixed_ustar{{ + {"safe.txt", "ok", '0', ""}, + {"bad\nlink", "", '2', "/etc/passwd"}, + {"../escape", "nope", '0', ""}, }}; - const auto raw = make_raw_tar(mixed); + const auto raw = make_raw_tar_ustar(mixed_ustar); SpanByteSource src1{raw}; 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"}); } +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 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 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(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(ArchiveErrorCode::unsupported_format)); + } +} + Void::Testing::Test archive_staged_extraction_atomic_publish_unknown_and_cleanup() { 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"; std::filesystem::create_directories(parent_dir); @@ -243,7 +448,9 @@ Void::Testing::Test archive_staged_extraction_atomic_publish_unknown_and_cleanup .executable = false, .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. 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 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"; std::filesystem::create_directories(parent_dir); @@ -358,7 +566,10 @@ Void::Testing::Test archive_isolated_worker_extracts_verifies_and_publishes() .executable = false, .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{}; iso.worker_executable = VOID_ARCHIVE_WORKER_PATH; diff --git a/tests/standalone/Configuration/Argparse.cpp b/tests/standalone/Configuration/Argparse.cpp index 980573c..18ebe4a 100644 --- a/tests/standalone/Configuration/Argparse.cpp +++ b/tests/standalone/Configuration/Argparse.cpp @@ -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("A description.") != std::string::npos); } + +Void::Testing::Test argparse_subcommands_option_many_and_distinct_outcomes() +{ + bool verbose = false; + std::vector targets; + std::vector 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); + } +} diff --git a/tests/standalone/Crypto/Crypto.cpp b/tests/standalone/Crypto/Crypto.cpp index 7e0b353..a969448 100644 --- a/tests/standalone/Crypto/Crypto.cpp +++ b/tests/standalone/Crypto/Crypto.cpp @@ -6,6 +6,7 @@ #include #include +#include namespace { @@ -20,19 +21,122 @@ Void::Testing::Test crypto_known_hash_vectors() auto sha1 = Void::Crypto::sha1("abc"); auto sha256 = Void::Crypto::sha256("abc"); auto sha512 = Void::Crypto::sha512("abc"); + auto b2_256 = Void::Crypto::blake2b256("abc"); + auto b2_512 = Void::Crypto::blake2b512("abc"); Void::Testing::require(sha1.has_value()); Void::Testing::require(sha256.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( hex(*sha1), std::string{"a9993e364706816aba3e25717850c26c9cd0d89d"}); - Void::Testing::expect_eq(hex(*sha256), - std::string{"ba7816bf8f01cfea414140de5dae2223b0036" - "1a396177a9cb410ff61f20015ad"}); + Void::Testing::expect_eq( + hex(*sha256), + std::string{"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f" + "20015ad"}); Void::Testing::expect_eq( hex(*sha512), std::string{ "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a21" "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{}; + 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() @@ -50,8 +154,45 @@ Void::Testing::Test crypto_streaming_and_file_hash_match() const auto path = temporary / "data"; std::ofstream{path, std::ios::binary} << "abc"; auto file = Void::Crypto::sha256File(path); + auto file_snake = Void::Crypto::sha256_file(path); Void::Testing::require(file.has_value()); + Void::Testing::require(file_snake.has_value()); 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() @@ -67,6 +208,15 @@ Void::Testing::Test crypto_ed25519_rfc8032_vector() std::as_bytes(std::span{publicText->data(), publicText->size()}); const auto signature = 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( + Void::Crypto::CryptoErrorCode::unsupported_algorithm)); + return; + } auto valid = Void::Crypto::verifyEd25519({}, signature, publicKey); Void::Testing::require(valid.has_value()); Void::Testing::expect(*valid); diff --git a/tests/standalone/Crypto/CryptoHardening.cpp b/tests/standalone/Crypto/CryptoHardening.cpp index 12a090c..50b8a98 100644 --- a/tests/standalone/Crypto/CryptoHardening.cpp +++ b/tests/standalone/Crypto/CryptoHardening.cpp @@ -123,6 +123,35 @@ Void::Testing::Test crypto_ed25519_signing_vectors_and_boundaries() { 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(CryptoErrorCode::unsupported_algorithm)); + + const std::array dummy_pub{}; + const std::array dummy_sig{}; + for (const std::size_t bad_key_len : {0U, 1U, 31U, 33U, 64U}) { + std::vector 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(CryptoErrorCode::invalid_key_size)); + } + for (const std::size_t bad_sig_len : {0U, 1U, 63U, 65U}) { + std::vector 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( + CryptoErrorCode::invalid_signature_size)); + } + return; + } + struct Rfc8032Vector { std::string_view seed_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}; })); } + // 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 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 ikm(22, std::byte{0x0b}); + const auto salt = from_hex("000102030405060708090a0b0c"); + const auto info = from_hex("f0f1f2f3f4f5f6f7f8f9"); + std::array 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 const auto a = from_hex("01020304"); const auto b = from_hex("01020304"); diff --git a/tests/standalone/Data/StrictJson.cpp b/tests/standalone/Data/StrictJson.cpp index f314ac1..80991ea 100644 --- a/tests/standalone/Data/StrictJson.cpp +++ b/tests/standalone/Data/StrictJson.cpp @@ -152,3 +152,69 @@ Void::Testing::Test strict_json_decodes_valid_unicode_pairs() Void::Testing::expect( !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 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(ctrl_back->value), + std::string{"a\nb\tc\x01\"\\"}); +} diff --git a/tests/standalone/Data/Toml.cpp b/tests/standalone/Data/Toml.cpp new file mode 100644 index 0000000..84d8cec --- /dev/null +++ b/tests/standalone/Data/Toml.cpp @@ -0,0 +1,235 @@ +#include +#include +#include + +#include +#include +#include +#include + +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::min()); + Void::Testing::expect_eq(*root.find("max_i64")->as_integer(), + std::numeric_limits::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}); +} \ No newline at end of file diff --git a/tests/standalone/Net/HttpClient.cpp b/tests/standalone/Net/HttpClient.cpp index 007e003..ba23c8b 100644 --- a/tests/standalone/Net/HttpClient.cpp +++ b/tests/standalone/Net/HttpClient.cpp @@ -1,19 +1,34 @@ +#include #include +#include +#include #include #include +#include +#include +#include +#include +#include +#include + +#include #include +#include +#include #include +#include #include #include #include #include +#include namespace { // Minimal one-shot HTTP/1.1 server on a chosen loopback port. Accepts one // 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 { int fd = -1; std::uint16_t port = 0; @@ -29,7 +44,7 @@ namespace sockaddr_in addr{}; addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); - addr.sin_port = 0; // ephemeral + addr.sin_port = 0; ::bind(fd, reinterpret_cast(&addr), sizeof(addr)); socklen_t len = sizeof(addr); ::getsockname(fd, reinterpret_cast(&addr), &len); @@ -59,6 +74,126 @@ namespace 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; + using X509Ptr = std::unique_ptr; + using ExtPtr = + std::unique_ptr; + + PkeyPtr pkey{EVP_RSA_gen(2048), &EVP_PKEY_free}; + Void::Testing::require(static_cast(pkey)); + + X509Ptr cert{X509_new(), &X509_free}; + Void::Testing::require(static_cast(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("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(san_value)), + &X509_EXTENSION_free}; + Void::Testing::require(static_cast(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(&addr), + sizeof(addr)) == 0); + socklen_t len = sizeof(addr); + ::getsockname(fd, reinterpret_cast(&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(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 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(200)); Void::Testing::expect_eq(resp->body, std::string{"hello from void"}); 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") != 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::Net::HttpClient client; - // Port 1 on loopback: nothing listening. const auto resp = client.get("http://127.0.0.1:1/"); Void::Testing::expect(!resp.has_value()); } 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 { int fd = -1; std::uint16_t port = 0; @@ -138,14 +268,14 @@ Void::Testing::Test http_client_timeout_bounds_a_stalled_server() ::listen(fd, 1); worker = std::thread([this] { conn = ::accept(fd, nullptr, nullptr); - // Never write a byte; hold the connection open. }); } ~StallServer() { - if (conn >= 0) ::close(conn); + if (fd >= 0) ::shutdown(fd, SHUT_RDWR); if (worker.joinable()) worker.join(); + if (conn >= 0) ::close(conn); 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; 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::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((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(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 slow_entered{false}; + std::atomic 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(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 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(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(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(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("") != 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(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(Void::Net::NetErrorCode::tls_error)); + } +} diff --git a/tests/standalone/Net/HttpServer.cpp b/tests/standalone/Net/HttpServer.cpp new file mode 100644 index 0000000..75b9d6a --- /dev/null +++ b/tests/standalone/Net/HttpServer.cpp @@ -0,0 +1,393 @@ +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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(&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(w); + } + (void)::shutdown(fd, SHUT_WR); + + std::string out; + std::array buf{}; + for (;;) { + const ssize_t r = ::recv(fd, buf.data(), buf.size(), 0); + if (r <= 0) { + break; + } + out.append(buf.data(), static_cast(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{in}, + std::istreambuf_iterator{}}; + } +} // 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 ok_count{0}; + std::vector 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(&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 in_flight_entered{false}; + std::atomic 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('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 + 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"}); + } +} diff --git a/tests/standalone/System/DirectoryWatcher.cpp b/tests/standalone/System/DirectoryWatcher.cpp new file mode 100644 index 0000000..0a88296 --- /dev/null +++ b/tests/standalone/System/DirectoryWatcher.cpp @@ -0,0 +1,176 @@ +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace +{ + +[[nodiscard]] std::vector + collect_events(Void::FileSystem::DirectoryWatcher& watcher, + std::chrono::milliseconds budget) +{ + std::vector 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; + })); + } +} \ No newline at end of file diff --git a/tests/standalone/System/Path.cpp b/tests/standalone/System/Path.cpp index 4134bc2..29f4523 100644 --- a/tests/standalone/System/Path.cpp +++ b/tests/standalone/System/Path.cpp @@ -96,3 +96,119 @@ Void::Testing::Test remove_path_handles_missing_and_recursive() Void::Testing::expect(r2.has_value()); 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(st_target.st_mtim.tv_sec), + kTargetMtime); + Void::Testing::expect_eq(static_cast(st_link.st_mtim.tv_sec), + kLinkMtime); + } +} diff --git a/tests/standalone/System/SystemHardening.cpp b/tests/standalone/System/SystemHardening.cpp index 224e6e6..ca55b8e 100644 --- a/tests/standalone/System/SystemHardening.cpp +++ b/tests/standalone/System/SystemHardening.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include namespace @@ -294,3 +295,72 @@ Void::Testing::Test system_replace_file_temp_ownership_and_metrics() expect(sample.valid); 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 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(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 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); +} diff --git a/tests/standalone/Testing/NativeRegistration.cpp b/tests/standalone/Testing/NativeRegistration.cpp new file mode 100644 index 0000000..a2cf0b5 --- /dev/null +++ b/tests/standalone/Testing/NativeRegistration.cpp @@ -0,0 +1,46 @@ +#include +#include +#include + +#include + +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); +} \ No newline at end of file diff --git a/tests/standalone/Text/Semver.cpp b/tests/standalone/Text/Semver.cpp index c0f4d3c..9d7bdab 100644 --- a/tests/standalone/Text/Semver.cpp +++ b/tests/standalone/Text/Semver.cpp @@ -148,12 +148,97 @@ Void::Testing::Test semver_version_ranges_reject_overflowing_upper_bounds() { Void::Testing::expect( !Void::Semver::parse_range("^4294967295.0.0").has_value()); + Void::Testing::expect( + !Void::Semver::parse_range("^4294967295").has_value()); + Void::Testing::expect( + !Void::Semver::parse_range("~4294967295").has_value()); Void::Testing::expect( !Void::Semver::parse_range("4294967295.x").has_value()); Void::Testing::expect( !Void::Semver::parse_range("1.4294967295.x").has_value()); } +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 ───────────────────────────────────────────────────────────────────── Void::Testing::Test semver_bump_major()