94 Commits
Author SHA1 Message Date
Void agent 3d80649b8c ci: add native VBS workflow (template)
VoidLibrary (VBS) / vbs-build (push) Failing after 49s
VoidLibrary (VBS) / vbs-build (pull_request) Failing after 44s
2026-12-05 10:46:26 +03:00
Void agent e44612b505 build: install rules, packaging and profile definitions 2026-12-05 10:41:11 +03:00
Void agent 9f0fa67f56 build: add native VoidBuildSystem description (all modules) 2026-12-05 10:32:24 +03:00
faumaray 0002e74a7d Merge issue-38-targets: Windows select backend foundation and Alpine/musl test qualification 2026-12-03 17:59:21 +03:00
faumaray 0751a4155b Merge issue-52-ed25519-manual: built-in Ed25519 backend (closes #52) 2026-12-03 17:58:18 +03:00
faumaray 86cb94c844 Crypto: add a built-in Ed25519 backend (closes #52) 2026-12-03 17:58:13 +03:00
faumaray f8c62c9851 Build: qualify Alpine/musl test suite (refs #38) 2026-12-03 17:51:20 +03:00
faumaray 7d25251e21 IO: add Windows select backend foundation (refs #38) 2026-12-03 17:49:09 +03:00
faumaray 06641947bd Merge issue-38-targets: wasm test-suite qualification 2026-12-03 17:43:23 +03:00
faumaray f0820b778f Build: qualify wasm test suite with portable libc++ fallbacks (refs #38) 2026-12-03 17:43:14 +03:00
faumaray 62df9b3d7f Merge issue-38-targets: Alpine/musl, wasm and reflection-gated qualification 2026-12-03 17:39:30 +03:00
faumaray 92d60231e5 tests: fix warnings exposed by -Werror and a non-recursive Storage copy 2026-12-03 17:37:14 +03:00
faumaray 2c8d853af0 Net: consume read/write/send results in the HTTP server (VL-NET-W01) 2026-12-03 17:37:14 +03:00
faumaray 1ba60d5d6a Build: gate reflection-only tests on VOID_HAS_CXX26_REFLECTION (refs #38) 2026-12-03 17:29:04 +03:00
faumaray b1933d9906 Build: qualify wasm library subset with Emscripten (refs #38) 2026-12-03 17:18:29 +03:00
faumaray 9f8c56a7ee Build: qualify Alpine/musl target support (refs #38) 2026-12-03 17:16:29 +03:00
faumaray 08a40ad5fc Merge issue-38-targets follow-up: Windows runtime qualification and MinGW portability 2026-12-03 17:10:16 +03:00
faumaray 35774f18cc docs: mark X-QA-01..04 verified in the roadmap task board 2026-12-03 17:08:21 +03:00
faumaray 5d4589056a Build: qualify Windows runtime and fix MinGW portability (refs #38) 2026-12-03 17:07:16 +03:00
faumaray df4103700e Merge xqa-03-scanner: discover wrapped test declarations (X-QA-03) 2026-12-03 17:05:33 +03:00
faumaray 4bc8a7c59b cmake: discover wrapped test declarations in the scanner (X-QA-03) 2026-12-03 17:04:20 +03:00
faumaray 898968d7c6 TestingMock: reset failure tally when clearing captured assertions (X-QA-02) 2026-12-03 17:03:35 +03:00
faumaray 6e636d23e3 Merge issue-45-mcp: MCP protocol and transport foundations (closes #45) 2026-12-03 16:58:25 +03:00
faumaray 77a2bce73f cmake: apply -Werror to generated test TUs and fix exposed warnings (X-QA-01) 2026-12-03 16:57:22 +03:00
faumaray 32569bbfef MCP: add reusable protocol and transport foundations (closes #45) 2026-12-03 16:55:20 +03:00
faumaray 65185f251c Async: cover retry stop interleavings and classifier failures (X-QA-04) 2026-12-03 16:50:03 +03:00
faumaray fe231b0149 Merge issue-38-targets: qualify target support (closes #38) 2026-12-03 16:44:26 +03:00
faumaray 1335fa86c3 Build: qualify target support (closes #38) 2026-12-03 16:43:25 +03:00
faumaray 2501c4d7ac Merge xqa-02-runner-count: count failures independently of retention (X-QA-02) 2026-12-03 16:42:31 +03:00
faumaray 430deab07a Testing: count failures independently of assertion retention (X-QA-02) 2026-12-03 16:41:16 +03:00
faumaray 7b3258a450 cmake: ignore comments and EXCLUDE_SOURCES in module dependency parsing 2026-12-03 16:41:08 +03:00
faumaray d51dd171ef Merge issue-48-tls-smtp: TLS client stream and SMTP submission (closes #48) 2026-12-03 16:39:02 +03:00
faumaray 44686a4444 Net: add TLS client stream and SMTP submission (closes #48) 2026-12-03 16:37:13 +03:00
faumaray f158d7b1cc Text: add Void::Text base32 encode/decode facade (closes #49) 2026-12-03 16:33:06 +03:00
faumaray 62c2082fb3 Merge issue-40-windows-process: Windows process and handle support (closes #40) 2026-12-03 16:11:40 +03:00
faumaray 29b46839fd System: Windows process and handle support for the runner subset (closes #40) 2026-12-03 16:11:23 +03:00
faumaray 72148da7b2 Merge issue-37-duplex-http: duplex HTTP response streaming (closes #37) 2026-12-03 16:03:51 +03:00
faumaray a6dd7fd927 Net: add duplex HTTP response streaming (closes #37) 2026-12-03 16:03:31 +03:00
faumaray 7cfd30e550 Merge issue-44-binary-session: binary subprocess session (closes #44) 2026-12-03 15:51:05 +03:00
faumaray 9b773a4553 Merge issue-41-hmac-pbkdf2: HMAC-SHA1 and PBKDF2-HMAC-SHA256 (closes #41) 2026-12-03 15:51:04 +03:00
faumaray 540c3d9117 System: add binary subprocess session (#44) 2026-12-03 15:50:28 +03:00
faumaray 74bd01aac5 Crypto: add HMAC-SHA1 and PBKDF2-HMAC-SHA256 (#41) 2026-12-03 15:50:15 +03:00
faumaray a14d063598 Merge issue-46-toml-limits: TOML parser limits (closes #46) 2026-12-03 15:49:39 +03:00
faumaray a535f352d6 Merge issue-47-sqlite-wal: WAL frame admission and rollback reporting (closes #47) 2026-12-03 15:49:27 +03:00
faumaray 9ccfbf7838 Data: qualify TOML parser limits (#46) 2026-12-03 15:49:25 +03:00
faumaray 963aface67 Merge issue-39-lua-adapter: bounded Lua adapter (closes #39) 2026-12-03 15:48:32 +03:00
faumaray a40882522a Sqlite: WAL frame admission and automatic rollback reporting (#47) 2026-12-03 15:48:31 +03:00
faumaray ae7bedb755 Script: add optional bounded Lua runtime adapter (#39) 2026-12-03 15:47:39 +03:00
faumaray be8dd73607 Merge issue-42-bounded-diff: bounded diff APIs (#42) 2026-12-03 15:46:43 +03:00
faumaray 4ad13ce94f Text: add bounded diff APIs (#42) 2026-12-03 15:46:30 +03:00
faumaray f146df97f4 Merge issue-36-ed25519: Ed25519 sign/verify (#36) 2026-12-03 15:46:14 +03:00
faumaray f5842b97c8 Crypto: add Ed25519 sign/verify (#36) 2026-12-03 15:46:05 +03:00
faumaray add599917c Merge issue-43-base32: Text base32 codecs (#43) 2026-12-03 15:44:26 +03:00
faumaray 2eb3bd230a Text: add base32 codecs (#43) 2026-12-03 15:44:14 +03:00
faumaray b3c566ed4d Merge pull request 'Build containers, toolchains and portability fixes' (#35) from chore/toolchains-and-portability into main 2026-12-03 08:10:30 +00:00
faumaray d5cfd9cd7a chore(build): containers, toolchains and portability fixes 2026-12-03 08:10:22 +00:00
faumaray aebc38791a chore(build): containers, toolchains and portability fixes 2026-12-03 08:10:18 +00:00
faumaray c8f0113d48 chore(build): containers, toolchains and portability fixes 2026-12-03 08:10:14 +00:00
faumaray 12ba8d8e2c chore(build): containers, toolchains and portability fixes 2026-12-03 08:10:10 +00:00
faumaray 496d9fc582 chore(build): containers, toolchains and portability fixes 2026-12-03 08:10:07 +00:00
faumaray 5a74233a4d chore(build): containers, toolchains and portability fixes 2026-12-03 08:10:02 +00:00
faumaray 774df0fd1e chore(build): containers, toolchains and portability fixes 2026-12-03 08:09:58 +00:00
faumaray f8e183b7ab chore(build): containers, toolchains and portability fixes 2026-12-03 08:09:54 +00:00
faumaray 216a14e6fa chore(build): containers, toolchains and portability fixes 2026-12-03 08:09:52 +00:00
faumaray 7686be1b23 chore(build): containers, toolchains and portability fixes 2026-12-03 08:09:47 +00:00
faumaray 71fcad80d3 chore(build): containers, toolchains and portability fixes 2026-12-03 08:09:44 +00:00
faumaray 905e44635e chore(build): containers, toolchains and portability fixes 2026-12-03 08:09:42 +00:00
faumaray 5d5a8bf345 chore(build): containers, toolchains and portability fixes 2026-12-03 08:09:40 +00:00
faumaray fe6e2124ad chore(build): containers, toolchains and portability fixes 2026-12-03 08:09:36 +00:00
faumaray f9bde1d19f chore(build): containers, toolchains and portability fixes 2026-12-03 08:09:34 +00:00
faumaray 65595362e2 chore(build): containers, toolchains and portability fixes 2026-12-03 08:09:32 +00:00
faumaray 43d94e2837 chore(build): containers, toolchains and portability fixes 2026-12-03 08:09:30 +00:00
faumaray f6002c1996 Merge pull request 'Bounded PCM playback with owned samples and voice lifetimes (#18)' (#34) from issue/18-windows-pcm-playback into main 2026-12-03 08:08:41 +00:00
faumaray 706383e13f Merge pull request 'Bounded Lua evaluator with transactional host results (#17)' (#33) from issue/17-bounded-lua into main 2026-12-03 08:08:39 +00:00
faumaray 81e1d54ac3 Merge pull request 'Bounded admission gated on an exact retained publication (#16)' (#32) from issue/16-publication-gated-queue into main 2026-12-03 08:08:37 +00:00
faumaray f57b508b0a Merge pull request 'Deterministic completion-order helpers (#15)' (#31) from issue/15-completion-observer into main 2026-12-03 08:08:35 +00:00
faumaray b381d682c8 Merge pull request 'Bounded sparse 3D pages with atomic revision-checked batches (#14)' (#30) from issue/14-sparse-page-table into main 2026-12-03 08:08:33 +00:00
faumaray 8c576fdcbf Merge pull request 'Bounded epoch-qualified revision read sets (#13)' (#29) from issue/13-revision-read-set into main 2026-12-03 08:08:31 +00:00
faumaray caebb7f7f1 feat(System): bounded PCM playback with owned samples and voice lifetimes (#18) 2026-12-03 07:03:09 +00:00
faumaray df2ed107e2 feat(System): bounded PCM playback with owned samples and voice lifetimes (#18) 2026-12-03 07:03:05 +00:00
faumaray e8565c6857 feat(Script): bounded Lua evaluator with transactional host results (#17) 2026-12-03 07:02:57 +00:00
faumaray 2c6e4eab82 feat(Script): bounded Lua evaluator with transactional host results (#17) 2026-12-03 07:02:55 +00:00
faumaray 359e0630c7 feat(Script): bounded Lua evaluator with transactional host results (#17) 2026-12-03 07:02:53 +00:00
faumaray 025d97c6f6 feat(Script): bounded Lua evaluator with transactional host results (#17) 2026-12-03 07:02:50 +00:00
faumaray 08038000cc feat(Script): bounded Lua evaluator with transactional host results (#17) 2026-12-03 07:02:48 +00:00
faumaray ba49098798 feat(Script): bounded Lua evaluator with transactional host results (#17) 2026-12-03 07:02:45 +00:00
faumaray 60860d167a feat(Async): bounded admission gated on an exact retained publication (#16) 2026-12-03 07:02:35 +00:00
faumaray 5a076cd8f2 feat(Async): bounded admission gated on an exact retained publication (#16) 2026-12-03 07:02:33 +00:00
faumaray 82c3558524 feat(Testing): deterministic completion-order helpers (#15) 2026-12-03 07:02:26 +00:00
faumaray 3953891511 feat(Testing): deterministic completion-order helpers (#15) 2026-12-03 07:02:24 +00:00
faumaray ba3c5a6734 feat(Containers): bounded sparse 3D pages with atomic revision-checked batches (#14) 2026-12-03 06:53:44 +00:00
faumaray 00eefe0521 feat(Containers): bounded sparse 3D pages with atomic revision-checked batches (#14) 2026-12-03 06:53:42 +00:00
faumaray b062e759ba feat(Algorithms): bounded epoch-qualified revision read sets (#13) 2026-12-03 06:53:36 +00:00
faumaray dddcc2b2f0 feat(Algorithms): bounded epoch-qualified revision read sets (#13) 2026-12-03 06:53:34 +00:00
134 changed files with 20036 additions and 476 deletions

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
{
"name": "VoidLibrary (GCC 16, CMake 4, Ninja)",
"build": {
"dockerfile": "../Dockerfile",
"context": ".."
},
"workspaceFolder": "/src",
"workspaceMount": "source=${localWorkspaceFolder},target=/src,type=bind",
"remoteUser": "root",
"customizations": {
"vscode": {
"extensions": [
"ms-vscode.cpptools",
"ms-vscode.cmake-tools",
"twxs.cmake"
],
"settings": {
"cmake.generator": "Ninja",
"cmake.configureSettings": {
"CMAKE_CXX_COMPILER": "g++-16",
"CMAKE_C_COMPILER": "gcc-16",
"CMAKE_BUILD_TYPE": "Debug"
},
"C_Cpp.default.cppStandard": "c++26"
}
}
},
"postCreateCommand": "cmake --version && g++-16 --version && ninja --version"
}
+64
View File
@@ -0,0 +1,64 @@
# Windows builds: MSYS2 (native) and MinGW-w64 (cross)
## MSYS2 (native Windows, recommended for a full build)
Install the MINGW64 toolchain and the optional libraries used by the modules:
```bash
pacman -S --needed base-devel \
mingw-w64-x86_64-toolchain \
mingw-w64-x86_64-cmake \
mingw-w64-x86_64-ninja \
mingw-w64-x86_64-boost \
mingw-w64-x86_64-openssl \
mingw-w64-x86_64-libsodium \
mingw-w64-x86_64-libarchive \
mingw-w64-x86_64-sqlite3 \
mingw-w64-x86_64-lua
```
Then, from a **MINGW64** shell (not the MSYS shell):
```bash
cmake -B build -S . -G Ninja -DCMAKE_BUILD_TYPE=Debug
cmake --build build
ctest --test-dir build --output-on-failure
```
Notes:
- C++26 reflection requires GCC 16 or newer (`-freflection`). The build
probes for it; on older GCC some reflection-only tests are skipped.
- `Void::IO` currently has a POSIX (epoll) backend only; select the modules
you need with `-DVOID_ENABLED_MODULES=...` if a module is not yet available
on Windows.
- The Windows branches of `Void::System` (paths, bounded reads, audio) are
compiled by this configuration.
## MinGW-w64 cross build (Linux container)
`Dockerfile.mingw` uses the LLVM-MinGW toolchain (Clang + libc++ + the
MinGW-w64 runtime) on top of Ubuntu, together with CMake 4 and Ninja. The
matching devcontainer is in `.devcontainer/mingw/`.
```bash
docker build -f Dockerfile.mingw -t voidlibrary-mingw .
docker run --rm -v "$PWD:/src" -w /src voidlibrary-mingw bash -lc '
cmake -B build-mingw -S . -G Ninja \
-DCMAKE_TOOLCHAIN_FILE=cmake/toolchains/mingw-w64.cmake \
-DCMAKE_BUILD_TYPE=Debug \
-DVOID_ENABLE_TESTING=OFF \
-DVOID_ENABLED_MODULES="Core;Functional;Containers;Math;Text;Algorithms;Unicode;Time;LogState"
cmake --build build-mingw
'
```
Cross-compiling cannot use the host's Boost/OpenSSL/libsodium/libarchive/SQLite/
Lua libraries. Modules that need them (or the POSIX-only IO backend) are
therefore excluded from a cross build; use MSYS2 on Windows for those.
- The toolchain file accepts GCC- or Clang-based MinGW prefixes and picks
whichever compiler exists.
- `CMAKE_CXX_STANDARD` can be pinned for older toolchains
(`-DCMAKE_CXX_STANDARD=23`); the build probes capabilities against the
selected standard.
+28
View File
@@ -0,0 +1,28 @@
{
"name": "VoidLibrary (MinGW-w64 cross build)",
"build": {
"dockerfile": "../../Dockerfile.mingw",
"context": "../.."
},
"workspaceFolder": "/src",
"workspaceMount": "source=${localWorkspaceFolder},target=/src,type=bind",
"remoteUser": "root",
"customizations": {
"vscode": {
"extensions": [
"ms-vscode.cpptools",
"ms-vscode.cmake-tools",
"twxs.cmake"
],
"settings": {
"cmake.generator": "Ninja",
"cmake.configureSettings": {
"CMAKE_TOOLCHAIN_FILE": "cmake/toolchains/mingw-w64.cmake",
"CMAKE_BUILD_TYPE": "Debug"
},
"C_Cpp.default.cppStandard": "c++26"
}
}
},
"postCreateCommand": "cmake --version && x86_64-w64-mingw32-g++ --version && ninja --version"
}
+6
View File
@@ -0,0 +1,6 @@
build*
.git
.gitea
.github
.dockerignore
Dockerfile
+38
View File
@@ -0,0 +1,38 @@
# Native VoidBuildSystem build for VoidLibrary.
# Template: adapt runner labels and toolchain packages to the actual CI runner.
name: VoidLibrary (VBS)
on:
push:
branches: [main, build-vbs]
pull_request:
jobs:
vbs-build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install toolchain and system libraries
run: |
sudo apt-get update
sudo apt-get install -y cmake ninja-build g++ libssl-dev libboost-all-dev \
libsqlite3-dev libsodium-dev liblua5.4-dev
- name: Bootstrap VoidBuildSystem
run: |
git clone --depth 1 https://git.faumaray.com/Void/Build-System.git /tmp/vbs-src
cmake -S /tmp/vbs-src -B /tmp/vbs-build -G Ninja -DCMAKE_BUILD_TYPE=Release
cmake --build /tmp/vbs-build --parallel 4 --target vbs
- name: Native build
run: /tmp/vbs-build/bin/vbs build --project . --build-dir build-vbs --jobs 4
- name: Native smoke test
run: /tmp/vbs-build/bin/vbs test --project . --build-dir build-vbs --target void_smoke --jobs 4
- name: Install check
run: |
/tmp/vbs-build/bin/vbs install --project . --build-dir build-vbs \
--prefix "$PWD/dist" --package-name VoidLibrary --package-version 0.1.0
test -d dist/include/Void
test -n "$(ls dist/lib/*.a | head -1)"
+30 -4
View File
@@ -14,11 +14,23 @@ option(VOID_ENABLE_ASAN "Enable AddressSanitizer (Clang/GCC)" OFF)
option(VOID_ENABLE_UBSAN "Enable UndefinedBehaviorSanitizer (Clang/GCC)" OFF)
option(VOID_ENABLE_TSAN "Enable ThreadSanitizer (Clang/GCC)" OFF)
option(VOID_ENABLE_COVERAGE "Enable code coverage instrumentation" OFF)
option(VOID_SCRIPT_ENABLE_LUA "Build the optional bounded Lua adapter" ON)
option(VOID_FETCH_LUA "Fetch Lua 5.4 when no system package is found" ON)
set(CMAKE_CXX_STANDARD 26)
# C++26 is the default. Cross/toolchain-limited builds (e.g. MinGW-w64
# with an older GCC) may pin a lower standard explicitly.
if(NOT DEFINED CMAKE_CXX_STANDARD)
set(CMAKE_CXX_STANDARD 26)
endif()
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_CXX_MODULE_MAP_FORMAT "gcc")
if(NOT DEFINED CMAKE_CXX_MODULE_MAP_FORMAT)
if(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
set(CMAKE_CXX_MODULE_MAP_FORMAT "clang")
else()
set(CMAKE_CXX_MODULE_MAP_FORMAT "gcc")
endif()
endif()
set(CXX_SCAN_FOR_MODULES OFF)
# <Void/Data/Reflect.hpp>, <Void/Configuration/Bind.hpp>, etc.
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16)
@@ -33,6 +45,7 @@ set(EXPORT_SET_NAME ${PROJECT_NAME}Targets)
include(cmake/Capabilities.cmake)
void_probe_capabilities()
include(cmake/Module.cmake)
include(cmake/Targets.cmake)
# Modules to configure, with the modules they need (INTERNAL_DEPS, followed
# transitively); empty configures every module. OPTIONAL_DEPS are used only
@@ -56,11 +69,14 @@ if(VOID_ENABLED_MODULES)
list(APPEND _void_selected ${_void_module})
if(EXISTS "${_void_module_file}")
file(READ "${_void_module_file}" _void_text)
# The words after INTERNAL_DEPS up to the next keyword or ')'.
# Drop comments so prose between keywords is never parsed as a
# dependency name, then read the words after INTERNAL_DEPS up to
# the next keyword or ')'.
string(REGEX REPLACE "#[^\n]*" "" _void_text "${_void_text}")
if(_void_text MATCHES "INTERNAL_DEPS([^)]*)")
separate_arguments(_void_words UNIX_COMMAND "${CMAKE_MATCH_1}")
foreach(_void_word IN LISTS _void_words)
if(_void_word MATCHES "^(INTERNAL_DEPS|EXTERNAL_DEPS|OPTIONAL_DEPS|DEPS_WIN32|DEPS_UNIX|OPTIONS_WIN32|OPTIONS_UNIX|EXTRA_HEADERS|EXCLUDE_HEADERS)$")
if(_void_word MATCHES "^(INTERNAL_DEPS|EXTERNAL_DEPS|OPTIONAL_DEPS|DEPS_WIN32|DEPS_UNIX|OPTIONS_WIN32|OPTIONS_UNIX|EXTRA_HEADERS|EXCLUDE_HEADERS|EXCLUDE_SOURCES_WIN32|EXCLUDE_SOURCES_UNIX)$")
break()
endif()
list(APPEND _void_pending ${_void_word})
@@ -71,6 +87,12 @@ if(VOID_ENABLED_MODULES)
endif()
file(GLOB children RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}/src ${CMAKE_CURRENT_SOURCE_DIR}/src/*)
if(_void_selected)
# Fail on unsupported target/module combinations before resolving any
# dependency, so a browser engine requesting native networking gets the
# target message instead of a Boost/OpenSSL one.
void_validate_target_modules(${_void_selected})
endif()
foreach(module_path ${children})
if(_void_selected AND NOT module_path IN_LIST _void_selected)
continue()
@@ -84,6 +106,9 @@ foreach(module_path ${children})
endif()
endforeach()
void_finalize_modules()
void_validate_target_modules()
void_write_target_manifest(
"${CMAKE_CURRENT_BINARY_DIR}/void-target-manifest.cmake")
void_report_capabilities()
if(VOID_ENABLE_TESTING)
@@ -132,6 +157,7 @@ install(EXPORT ${EXPORT_SET_NAME}
install(FILES
"${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake"
"${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake"
"${CMAKE_CURRENT_BINARY_DIR}/void-target-manifest.cmake"
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/VoidTesting.cmake"
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/VoidTestScanner.cmake"
DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}"
+52
View File
@@ -0,0 +1,52 @@
# Development image for VoidLibrary.
#
# Toolchain: GCC 16 (C++26 reflection), CMake 4, Ninja.
# Optional dependencies used by the modules: Boost, OpenSSL, libsodium,
# libarchive, SQLite3 and Lua 5.4.
#
# The image does not copy or build the sources: mount the repository at /src
# (the devcontainer does this) and configure/build there.
FROM ubuntu:24.04
ARG DEBIAN_FRONTEND=noninteractive
ARG GCC_VERSION=16
ARG CMAKE_VERSION=4.2.3
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
build-essential \
ca-certificates \
curl \
git \
gnupg \
ninja-build \
pkg-config \
software-properties-common \
libboost-all-dev \
libssl-dev \
libsodium-dev \
libarchive-dev \
libsqlite3-dev \
liblua5.4-dev \
zlib1g-dev \
&& add-apt-repository -y ppa:ubuntu-toolchain-r/test \
&& apt-get update \
&& apt-get install -y --no-install-recommends \
gcc-${GCC_VERSION} \
g++-${GCC_VERSION} \
&& update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-${GCC_VERSION} 100 \
&& update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-${GCC_VERSION} 100 \
&& rm -rf /var/lib/apt/lists/*
RUN curl -fsSL -o /tmp/cmake.tar.gz \
"https://github.com/Kitware/CMake/releases/download/v${CMAKE_VERSION}/cmake-${CMAKE_VERSION}-linux-x86_64.tar.gz" \
&& tar -xzf /tmp/cmake.tar.gz -C /opt \
&& ln -s "/opt/cmake-${CMAKE_VERSION}-linux-x86_64/bin/cmake" /usr/local/bin/cmake \
&& ln -s "/opt/cmake-${CMAKE_VERSION}-linux-x86_64/bin/ctest" /usr/local/bin/ctest \
&& ln -s "/opt/cmake-${CMAKE_VERSION}-linux-x86_64/bin/cpack" /usr/local/bin/cpack \
&& rm /tmp/cmake.tar.gz
WORKDIR /src
CMD ["bash"]
+29
View File
@@ -0,0 +1,29 @@
# MinGW-w64 cross-build environment for VoidLibrary (Windows x64 from Linux).
#
# Uses the LLVM-MinGW toolchain (Clang + libc++ + MinGW-w64 runtime), which is
# new enough for the C++26 features this project uses. Reflection is not
# available on Clang, so the reflection-only tests are skipped exactly as on
# any non-reflecting compiler.
FROM mstorsjo/llvm-mingw:latest
ARG CMAKE_VERSION=4.2.3
# The base image is Ubuntu 24.04 with CMake 3.28; Void requires CMake 4.
RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates curl git \
&& rm -rf /var/lib/apt/lists/*
RUN curl -fsSL -o /tmp/cmake.tar.gz \
"https://github.com/Kitware/CMake/releases/download/v${CMAKE_VERSION}/cmake-${CMAKE_VERSION}-linux-x86_64.tar.gz" \
&& tar -xzf /tmp/cmake.tar.gz -C /opt \
&& ln -sf "/opt/cmake-${CMAKE_VERSION}-linux-x86_64/bin/cmake" /usr/local/bin/cmake \
&& ln -sf "/opt/cmake-${CMAKE_VERSION}-linux-x86_64/bin/ctest" /usr/local/bin/ctest \
&& ln -sf "/opt/cmake-${CMAKE_VERSION}-linux-x86_64/bin/cpack" /usr/local/bin/cpack \
&& rm /tmp/cmake.tar.gz
ENV PATH="/opt/llvm-mingw/bin:${PATH}"
WORKDIR /src
CMD ["bash"]
+13 -1
View File
@@ -48,6 +48,15 @@ ctest --test-dir build-asan
Format code with `clang-format -i <file>`.
## Supported targets
Void is qualified per target profile: Linux (reference), Linux/musl, the
Windows client subset, and a browser/Wasm subset of the pure computation
modules. The profile is detected from the toolchain, validated against the
selected modules, and recorded in `void-target-manifest.cmake`. See
[docs/targets.md](docs/targets.md) for the exact compiler/standard-library
tuples, module allowlists and qualification status.
## Modules
Functionality is grouped into umbrella modules (one CMake target each).
@@ -101,4 +110,7 @@ Tests are free functions or methods on a `Void::Testing::Fixture` subclass
returning `Void::Testing::Test` (or `Void::Testing::DisabledTest`).
Registration is automatic — the CMake test scanner parses each `.cpp` at
configure time and generates the registration shim. Free-function tests can
use `// @tag` and `// @skip` comment metadata.
use `// @tag` and `// @skip` comment metadata. A file whose tests all need
C++26 reflection can declare `// @requires-reflection`; it is skipped when
the compiler lacks the `VOID_HAS_CXX26_REFLECTION` capability, because the
scanner cannot evaluate `#ifdef` guards around test functions.
+171
View File
@@ -0,0 +1,171 @@
#include "VoidLibraryModules.hpp"
#include <algorithm>
#include <filesystem>
#include <map>
#include <set>
#include <stdexcept>
namespace Void::Build::Recipes {
namespace {
struct ModuleDef {
std::vector<std::string> internal_deps;
bool needs_threads{false};
};
const std::map<std::string, ModuleDef, std::less<>> &known_modules() {
static const std::map<std::string, ModuleDef, std::less<>> kDefs = {
{"Core", {{}, false}},
{"Functional", {{}, false}},
{"Math", {{}, false}},
{"Algorithms", {{"Core", "Math"}, false}},
{"Memory", {{"Core"}, false}},
{"Time", {{}, false}},
{"Text", {{}, false}},
{"Unicode", {{"Core", "Text"}, false}},
{"LogState", {{}, false}},
{"Data", {{"Core", "Math", "Time"}, false}},
{"System", {{"Functional", "Time", "LogState"}, true}},
{"Async", {{"Functional", "Time", "LogState"}, true}},
{"Crypto", {{"Functional"}, false}},
{"Archive", {{"Functional", "Time", "System"}, false}},
{"Configuration", {{"Core", "Functional", "System", "Data", "Time", "LogState"}, true}},
{"Log", {{"Async", "Core", "Data", "Functional", "Memory", "Time", "LogState"}, true}},
{"Testing",
{{"Core", "Functional", "Time", "LogState", "Async", "Configuration", "Text"}, true}},
{"Containers", {{"Core", "Memory"}, false}},
{"Binary", {{"Functional", "Memory"}, false}},
{"IO", {{"Core", "Functional", "Time", "Memory", "Async"}, false}},
{"Service", {{"Core", "Functional", "Time", "Async", "LogState"}, false}},
{"ObservabilityHooks", {{}, false}},
{"Resilience", {{"Functional", "Time", "ObservabilityHooks"}, false}},
{"Storage", {{"Core", "Functional", "Time", "Memory", "Binary", "IO", "Async"}, false}},
{"IPC",
{{"Core", "Functional", "Memory", "Time", "Binary", "Async", "IO", "Resilience"},
false}},
{"Fsm", {{"Async", "Core", "Data", "Functional", "Time", "Log", "Service"}, false}},
// External dependencies (linked by the embedding build): OpenSSL/Boost for Net,
// SQLite3 for Sqlite.
{"Net", {{"Functional", "Text"}, true}},
{"Sqlite", {{"Functional", "Time"}, false}},
{"ConfigurationAsync", {{"Configuration", "SystemAsync", "Async", "Time", "Functional", "LogState"}, false}},
{"CryptoAsync", {{"Crypto", "IO", "Async", "Time", "Functional"}, true}},
{"Discovery", {{"Core", "Functional", "Time", "Async"}, false}},
{"DiscoveryRpc", {{"Discovery", "RPC"}, false}},
{"FunctionalCoreFormatting", {{"Functional", "Core"}, false}},
{"IPC", {{"Core", "Functional", "Memory", "Time", "Binary", "Async", "IO", "Resilience"}, false}},
{"LogConfig", {{"Log", "Configuration", "Functional"}, false}},
{"MCP", {{"Functional", "Data"}, false}},
{"Messaging", {{"Core", "Functional", "Binary", "Time", "Async"}, false}},
{"MessagingRpc", {{"Messaging", "RPC"}, false}},
{"MessagingStorage", {{"Messaging", "Storage"}, false}},
{"Observability", {{"ObservabilityHooks", "Core", "Functional", "Time", "Memory"}, false}},
{"Plugin", {{"Core", "Functional", "System", "Data", "Time", "Async", "LogState", "Text", "Service"}, false}},
{"RPC", {{"Core", "Functional", "Binary", "Data", "Time", "Async", "Net"}, false}},
{"ResilienceAsync", {{"Resilience", "Async", "Functional", "Time", "ObservabilityHooks"}, false}},
{"Runtime", {{"Core", "Functional", "Time", "Memory", "Algorithms", "Async", "IO"}, false}},
{"Scheduler", {{"Core", "Functional", "Time", "Async"}, false}},
{"SchedulerStorage", {{"Scheduler", "Storage"}, false}},
{"Script", {{}, false}},
{"Security", {{"Functional", "Time"}, false}},
{"SecurityAsync", {{"Security", "Async", "Time", "Resilience", "Functional"}, true}},
{"ServicePlugin", {{"Service", "Plugin", "LogState"}, false}},
{"ShortUrl", {{"Service", "Time"}, false}},
{"ShortUrlRemote", {{"ShortUrl", "Net", "Data"}, false}},
{"ShortUrlStorage", {{"ShortUrl", "Storage", "Security"}, false}},
{"SqliteAsync", {{"Sqlite", "Async", "Time", "Functional"}, false}},
{"Stacktrace", {{"Functional", "Time", "LogState"}, true}},
{"SystemAsync", {{"System", "Async", "IO", "Time", "Functional", "LogState"}, true}},
{"Testing", {{"Core", "Functional", "Time", "LogState", "Stacktrace", "Log", "Async", "Configuration", "Text"}, false}},
{"TestingMock", {{"Core", "Testing", "Functional"}, false}},
{"Update", {{"Archive", "Crypto", "Data", "Functional", "System", "Text", "Time"}, false}},
};
return kDefs;
}
std::vector<std::string> collect_sources(const std::filesystem::path &src_dir) {
std::vector<std::string> files;
std::error_code ec;
if (!std::filesystem::is_directory(src_dir, ec)) {
return files;
}
for (const auto &ent : std::filesystem::recursive_directory_iterator(src_dir, ec)) {
if (ent.is_regular_file(ec) && ent.path().extension() == ".cpp") {
files.push_back(ent.path().lexically_normal().string());
}
}
std::ranges::sort(files);
return files;
}
} // namespace
VoidLibraryTargets add_void_library_native(Project &project,
const std::filesystem::path &void_source_dir,
const std::vector<std::string> &enabled_modules) {
const auto &defs = known_modules();
// Compute transitive module closure in deterministic topological order.
std::set<std::string> visited;
std::vector<std::string> topo;
auto visit = [&](auto &&self, const std::string &mod) -> void {
if (!visited.insert(mod).second) {
return;
}
const auto it = defs.find(mod);
if (it == defs.end()) {
throw std::invalid_argument{"VoidLibraryRecipe: unsupported native module '" + mod +
"'"};
}
for (const auto &dep : it->second.internal_deps) {
self(self, dep);
}
topo.push_back(mod);
};
for (const auto &mod : enabled_modules) {
visit(visit, mod);
}
const auto include_dir = (void_source_dir / "include").lexically_normal().string();
VoidLibraryTargets result;
for (const auto &mod : topo) {
const auto &def = defs.at(mod);
const auto srcs = collect_sources(void_source_dir / "src" / mod);
const std::string target_name = "Void_" + mod;
Target tgt = srcs.empty() ? project.header_only_library(target_name)
: project.static_library(target_name);
tgt.cxx_standard(CxxStandard::Cxx26).include_directory(include_dir, Visibility::Public);
if (project.context().compiler == CompilerFamily::Gcc) {
tgt.compile_option("-freflection", Visibility::Public);
}
for (const auto &s : srcs) {
tgt.sources(SourceSet::file(s));
}
for (const auto &dep : def.internal_deps) {
tgt.link(result.modules.at(dep), Visibility::Public);
}
if (def.needs_threads) {
tgt.link_option("-pthread", Visibility::Public);
}
if (mod == "Crypto") {
tgt.define("VOID_CRYPTO_HAS_OPENSSL=0", Visibility::Public);
}
if (mod == "Archive") {
tgt.define("VOID_ARCHIVE_HAS_LIBARCHIVE=0", Visibility::Public);
}
if (mod == "Testing") {
tgt.define("VOID_HAS_ASYNC", Visibility::Public)
.define("VOID_HAS_CONFIGURATION", Visibility::Public)
.define("VOID_HAS_TEXT", Visibility::Public);
}
result.modules.emplace(mod, tgt);
}
return result;
}
} // namespace Void::Build::Recipes
+24
View File
@@ -0,0 +1,24 @@
#pragma once
#include <Void/Build.hpp>
#include <filesystem>
#include <map>
#include <string>
#include <vector>
namespace Void::Build::Recipes {
// Pure native VBS recipe for VoidLibrary (pinned commit 0002e74a7da94a756f55a4a5574d20b77736c185).
// Translates VoidLibrary's module closure directly into native VBS targets without invoking
// CMake or modifying the VoidLibrary source checkout (Plan 18).
struct VoidLibraryTargets {
std::map<std::string, Target, std::less<>> modules;
};
[[nodiscard]] VoidLibraryTargets
add_void_library_native(Project &project, const std::filesystem::path &void_source_dir,
const std::vector<std::string> &enabled_modules = {
"Configuration", "Text", "Unicode", "Async", "Testing"});
} // namespace Void::Build::Recipes
+52
View File
@@ -0,0 +1,52 @@
// Native VoidBuildSystem description for VoidLibrary itself (migration trial).
// The module closure is declared in build-support/vl/VoidLibraryModules.{hpp,cpp}.
#include "build-support/vl/VoidLibraryModules.hpp"
void build(Void::Build::Project &project) {
const auto &ctx = project.context();
(void)ctx;
auto libs = Void::Build::Recipes::add_void_library_native(
project, ".",
{"Algorithms", "Archive", "Async", "Binary", "Configuration", "ConfigurationAsync", "Containers", "Core", "Data", "Discovery", "DiscoveryRpc", "Fsm", "Functional", "FunctionalCoreFormatting", "IO", "IPC", "Log", "LogConfig", "LogState", "MCP", "Math", "Memory", "Messaging", "MessagingRpc", "MessagingStorage", "Observability", "ObservabilityHooks", "Plugin", "RPC", "Resilience", "ResilienceAsync", "Runtime", "Scheduler", "SchedulerStorage", "Service", "ServicePlugin", "ShortUrl", "ShortUrlRemote", "ShortUrlStorage", "SqliteAsync", "Storage", "Testing", "TestingMock", "Text", "Time", "Unicode", "Update", "Net", "Sqlite", "Security", "SecurityAsync", "Script", "Stacktrace", "SystemAsync", "CryptoAsync" });
// System libraries for the externally dependent modules (provided by the shell).
if (auto it = libs.modules.find("Net"); it != libs.modules.end()) {
it->second.link_option("-lssl", Void::Build::Visibility::Public)
.link_option("-lcrypto", Void::Build::Visibility::Public)
.link_option("-lboost_url", Void::Build::Visibility::Public)
.link_option("-ldl", Void::Build::Visibility::Public);
}
if (auto it = libs.modules.find("Sqlite"); it != libs.modules.end()) {
it->second.link_option("-lsqlite3", Void::Build::Visibility::Public);
}
for (const char *secure : {"Security", "SecurityAsync"}) {
if (auto it = libs.modules.find(secure); it != libs.modules.end()) {
it->second.link_option("-lsodium", Void::Build::Visibility::Public);
}
}
if (auto it = libs.modules.find("Script"); it != libs.modules.end()) {
it->second.link_option("-llua", Void::Build::Visibility::Public);
}
if (auto it = libs.modules.find("Stacktrace"); it != libs.modules.end()) {
it->second.link_option("-lboost_stacktrace_addr2line", Void::Build::Visibility::Public)
.link_option("-ldl", Void::Build::Visibility::Public);
}
// Install/packaging rules: module archives, public headers and license metadata.
for (auto &[name, target] : libs.modules) {
if (target.record().kind == Void::Build::TargetKind::HeaderOnly) {
continue;
}
target.install("lib");
}
project.install_directory("include", "include");
project.install_file("README.md", "share/doc/VoidLibrary");
// Smoke test exercising the native VoidLibrary closure through VBS.
auto smoke = project.test("void_smoke");
smoke.cxx_standard(Void::Build::CxxStandard::Cxx26)
.sources({"tests/vl/smoke.cpp"})
.link(libs.modules.at("Testing"))
.link(libs.modules.at("Configuration"));
}
+8
View File
@@ -0,0 +1,8 @@
#include <Void/Build.hpp>
// VoidLibrary native profiles: debug (default) and release, plus an optimized
// "relwithdebinfo" variant useful for sanitizer and benchmark runs.
void profiles(Void::Build::Profiles &descriptions) {
descriptions = Void::Build::default_profiles();
descriptions.add("relwithdebinfo", {"-O2", "-g"});
}
+6 -4
View File
@@ -33,7 +33,7 @@ function(void_probe_capabilities)
endif()
cmake_push_check_state(RESET)
set(CMAKE_REQUIRED_FLAGS "-std=c++26")
set(CMAKE_REQUIRED_FLAGS "-std=c++${CMAKE_CXX_STANDARD}")
check_cxx_source_compiles(
"#include <expected>\nint main() { std::expected<int, int> e{0}; return *e; }\n"
VOID_HAS_STD_EXPECTED
@@ -46,10 +46,12 @@ function(void_probe_capabilities)
endif()
cmake_push_check_state(RESET)
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16)
set(CMAKE_REQUIRED_FLAGS "-std=c++26 -freflection")
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND
CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16 AND
CMAKE_CXX_STANDARD GREATER_EQUAL 26)
set(CMAKE_REQUIRED_FLAGS "-std=c++${CMAKE_CXX_STANDARD} -freflection")
else()
set(CMAKE_REQUIRED_FLAGS "-std=c++26")
set(CMAKE_REQUIRED_FLAGS "-std=c++${CMAKE_CXX_STANDARD}")
endif()
check_cxx_source_compiles(
"#include <meta>\nconsteval bool probe() { constexpr auto r = ^^int; return std::meta::is_type(r); }\nstatic_assert(probe());\nint main() { return 0; }\n"
+41
View File
@@ -265,6 +265,47 @@ function(void_fetch_dependency DEP_NAME)
endif()
return()
endif()
if(DEP_NAME STREQUAL "Lua")
if(TARGET Lua::Lua)
return()
endif()
# Prefer a system Lua 5.4 development package.
find_package(Lua 5.4 QUIET)
if(LUA_FOUND)
add_library(Lua::Lua INTERFACE IMPORTED)
set_property(TARGET Lua::Lua PROPERTY
INTERFACE_INCLUDE_DIRECTORIES "${LUA_INCLUDE_DIR}")
set_property(TARGET Lua::Lua PROPERTY
INTERFACE_LINK_LIBRARIES "${LUA_LIBRARIES}")
return()
endif()
if(NOT VOID_FETCH_LUA)
message(FATAL_ERROR
"[Void] Lua 5.4 not found and VOID_FETCH_LUA=OFF")
endif()
message(STATUS "[Void] Lua 5.4 not found - falling back to FetchContent")
FetchContent_Declare(Lua
URL https://www.lua.org/ftp/lua-5.4.9.tar.gz
URL_HASH SHA256=2335b6c582a52654f94612bf10d2f4672805d05329aa6568b1d8cd9e5c6fb8e6
SYSTEM
)
FetchContent_MakeAvailable(Lua)
file(GLOB _void_lua_sources "${lua_SOURCE_DIR}/src/*.c")
list(REMOVE_ITEM _void_lua_sources
"${lua_SOURCE_DIR}/src/lua.c"
"${lua_SOURCE_DIR}/src/luac.c")
add_library(void_lua STATIC ${_void_lua_sources})
set_target_properties(void_lua PROPERTIES
POSITION_INDEPENDENT_CODE ON
C_STANDARD 99
SYSTEM TRUE)
target_include_directories(void_lua SYSTEM PUBLIC
"${lua_SOURCE_DIR}/src")
add_library(Lua::Lua ALIAS void_lua)
return()
endif()
# FIXME: Add if needed external
# if(DEP_NAME STREQUAL "glaze")
# if(NOT glaze_POPULATED)
+18 -4
View File
@@ -5,13 +5,27 @@ set_property(GLOBAL PROPERTY VOID_ACTIVE_PUBLIC_HEADERS "")
function(void_add_module MODULE_NAME)
cmake_parse_arguments(ARG "" ""
"INTERNAL_DEPS;EXTERNAL_DEPS;OPTIONAL_DEPS;DEPS_WIN32;DEPS_UNIX;OPTIONS_WIN32;OPTIONS_UNIX;EXTRA_HEADERS;EXCLUDE_HEADERS"
"INTERNAL_DEPS;EXTERNAL_DEPS;OPTIONAL_DEPS;DEPS_WIN32;DEPS_UNIX;OPTIONS_WIN32;OPTIONS_UNIX;EXTRA_HEADERS;EXCLUDE_HEADERS;EXCLUDE_SOURCES_WIN32;EXCLUDE_SOURCES_UNIX"
${ARGN})
set(TGT ${PROJECT_NAME}_${MODULE_NAME})
set(ALIAS ${PROJECT_NAME}::${MODULE_NAME})
file(GLOB_RECURSE SRC CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/${MODULE_NAME}/*.cpp")
# Platform-specific source selection: a module may be fully portable at the
# header level while some translation units only build on one platform.
# Exclusions are relative to the module directory so callers do not depend
# on the global source layout.
if(WIN32 AND ARG_EXCLUDE_SOURCES_WIN32)
foreach(_excl IN LISTS ARG_EXCLUDE_SOURCES_WIN32)
list(REMOVE_ITEM SRC "${CMAKE_CURRENT_SOURCE_DIR}/${_excl}")
endforeach()
endif()
if(NOT WIN32 AND ARG_EXCLUDE_SOURCES_UNIX)
foreach(_excl IN LISTS ARG_EXCLUDE_SOURCES_UNIX)
list(REMOVE_ITEM SRC "${CMAKE_CURRENT_SOURCE_DIR}/${_excl}")
endforeach()
endif()
file(GLOB_RECURSE HDR CONFIGURE_DEPENDS
"${CMAKE_CURRENT_SOURCE_DIR}/include/Void/${MODULE_NAME}/*.hpp"
"${CMAKE_CURRENT_SOURCE_DIR}/include/Void/${MODULE_NAME}/*.h")
@@ -33,7 +47,7 @@ function(void_add_module MODULE_NAME)
set(LIB_TYPE "INTERFACE")
set(SCOPE "INTERFACE")
add_library(${TGT} INTERFACE)
target_compile_features(${TGT} INTERFACE cxx_std_26)
target_compile_features(${TGT} INTERFACE cxx_std_${CMAKE_CXX_STANDARD})
else()
set(SCOPE "PUBLIC")
if (MODULE_NAME STREQUAL "Testing")
@@ -45,7 +59,7 @@ function(void_add_module MODULE_NAME)
add_library(${TGT})
endif()
target_sources(${TGT} PRIVATE ${SRC})
target_compile_features(${TGT} PUBLIC cxx_std_26)
target_compile_features(${TGT} PUBLIC cxx_std_${CMAKE_CXX_STANDARD})
endif()
get_target_property(_module_target_type ${TGT} TYPE)
if(_module_target_type STREQUAL "SHARED_LIBRARY" OR
@@ -221,7 +235,7 @@ function(void_add_module MODULE_NAME)
endif()
set_target_properties(${TGT} PROPERTIES
CXX_STANDARD 26
CXX_STANDARD ${CMAKE_CXX_STANDARD}
CXX_STANDARD_REQUIRED ON
CXX_EXTENSIONS OFF
EXPORT_NAME ${MODULE_NAME}
+241
View File
@@ -0,0 +1,241 @@
# Target qualification for VoidLibrary.
#
# A "target" is a platform profile with a known compiler/standard-library
# tuple and an explicit set of modules that are expected to work there. The
# profile is detected from the toolchain, can be overridden for
# qualification runs with -DVOID_TARGET=..., and is validated against the
# selected modules so unsupported combinations fail at configure time with a
# useful message instead of deep inside a cross build.
#
# See docs/targets.md for the recorded tuples and their qualification status.
set(VOID_KNOWN_TARGETS linux linux-musl windows wasm)
set(VOID_TARGET "auto" CACHE STRING
"Target profile: auto (detect from the toolchain), ${VOID_KNOWN_TARGETS}")
set_property(CACHE VOID_TARGET PROPERTY STRINGS auto ${VOID_KNOWN_TARGETS})
# Browser/Wasm subset: pure computation modules only. Nothing here performs
# native I/O, spawns processes, loads shared libraries, uses SQLite, or needs
# C++26 reflection. Keep this list fail-closed: a module is added only after
# it has been configured and compiled for wasm32-unknown-emscripten.
# Qualified with Emscripten 6.0.9 (Clang 22, libc++) for configure, build,
# install, consume and run under Node, including the test suite with
# -pthread (see docs/targets.md).
set(VOID_WASM_MODULES
Algorithms
Binary
Containers
Core
Data
Functional
LogState
Math
Memory
Testing
TestingMock
Text
Time
Unicode
)
# Windows client subset: modules qualified with x86_64-w64-mingw32 (MinGW-w64).
# Filled from the cross-build and Wine runtime observations in
# docs/targets.md. IO is deliberately absent: it builds on Windows but its
# native backend is Linux-only (EpollBackend), so only the mock backend works.
set(VOID_WINDOWS_MODULES
Algorithms
Async
Binary
Containers
Core
Data
Discovery
Fsm
Functional
IO
Log
LogState
Math
Memory
Messaging
Observability
ObservabilityHooks
Scheduler
Service
Testing
TestingMock
Text
Time
Unicode
)
function(void_detect_target out_var)
if(NOT VOID_TARGET STREQUAL "auto")
set(${out_var} "${VOID_TARGET}" PARENT_SCOPE)
return()
endif()
if(EMSCRIPTEN OR CMAKE_SYSTEM_NAME STREQUAL "Emscripten")
set(_target wasm)
elseif(WIN32)
set(_target windows)
elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux")
execute_process(
COMMAND "${CMAKE_C_COMPILER}" -dumpmachine
OUTPUT_VARIABLE _triple
ERROR_QUIET
OUTPUT_STRIP_TRAILING_WHITESPACE)
if(_triple MATCHES "musl" OR
CMAKE_C_LIBRARY_ARCHITECTURE MATCHES "musl" OR
CMAKE_C_FLAGS MATCHES "musl")
set(_target linux-musl)
else()
set(_target linux)
endif()
else()
set(_target unsupported)
endif()
set(${out_var} "${_target}" PARENT_SCOPE)
endfunction()
function(_void_target_allowlist target out_var)
if(target STREQUAL "wasm")
set(${out_var} "${VOID_WASM_MODULES}" PARENT_SCOPE)
elseif(target STREQUAL "windows")
set(${out_var} "${VOID_WINDOWS_MODULES}" PARENT_SCOPE)
else()
# Linux and Linux/musl qualify every module: platform-specific code is
# selected inside the module sources.
set(${out_var} "" PARENT_SCOPE)
endif()
endfunction()
# Validate the detected/forced target against a module selection. Called
# from the top-level CMakeLists as soon as the selection is expanded (before
# any module dependency is resolved, so an unsupported browser-engine
# combination fails with the target message, not a missing-package error),
# and again after void_finalize_modules() for the all-modules default.
# With no arguments the configured module list is validated.
function(void_validate_target_modules)
void_detect_target(_target)
if(_target STREQUAL "unsupported")
message(FATAL_ERROR
"[Void] Unsupported target '${CMAKE_SYSTEM_NAME} "
"${CMAKE_SYSTEM_PROCESSOR}'. Known targets: ${VOID_KNOWN_TARGETS}. "
"Pass -DVOID_TARGET=<target> only for a qualification run; "
"see docs/targets.md.")
endif()
if(NOT _target IN_LIST VOID_KNOWN_TARGETS)
message(FATAL_ERROR
"[Void] Unknown VOID_TARGET='${_target}'. Known targets: "
"${VOID_KNOWN_TARGETS}.")
endif()
if(_target STREQUAL "wasm" AND VOID_ENABLE_TSAN)
message(FATAL_ERROR
"[Void] ThreadSanitizer is not supported on the wasm target; "
"run native sanitizer builds separately (docs/targets.md).")
endif()
if(ARGN)
set(_modules ${ARGN})
else()
get_property(_modules GLOBAL PROPERTY VOID_MODULES)
endif()
_void_target_allowlist(${_target} _allowed)
if(_allowed)
set(_rejected "")
foreach(_module IN LISTS _modules)
if(NOT _module IN_LIST _allowed)
list(APPEND _rejected ${_module})
endif()
endforeach()
if(_rejected)
message(FATAL_ERROR
"[Void] Modules not supported on target '${_target}': "
"${_rejected}. Supported modules: ${_allowed}. "
"Select a supported subset with -DVOID_ENABLED_MODULES=... "
"or use a native target (docs/targets.md).")
endif()
endif()
if(NOT DEFINED VOID_TARGET_DETECTED OR
NOT VOID_TARGET_DETECTED STREQUAL _target)
set(VOID_TARGET_DETECTED "${_target}" CACHE INTERNAL
"Detected or forced Void target profile" FORCE)
if(NOT VOID_TARGET STREQUAL "auto")
message(STATUS "[Void] Target forced to '${_target}' by VOID_TARGET")
else()
message(STATUS "[Void] Target: ${_target}")
endif()
endif()
endfunction()
# Record the exact tuple this build was configured with. The manifest is
# installed next to VoidConfig.cmake so consumers can inspect what they got,
# and the qualification fixtures assert on it.
function(void_write_target_manifest path)
get_property(_modules GLOBAL PROPERTY VOID_MODULES)
list(JOIN _modules ";" _modules_value)
if(VOID_HAS_CXX26_REFLECTION)
set(_reflection yes)
else()
set(_reflection no)
endif()
if(VOID_HAS_STD_EXPECTED)
set(_expected yes)
else()
set(_expected no)
endif()
if(BUILD_SHARED_LIBS)
set(_linkage shared)
else()
set(_linkage static)
endif()
set(_sanitizers "")
if(VOID_ENABLE_ASAN)
list(APPEND _sanitizers ASan)
endif()
if(VOID_ENABLE_UBSAN)
list(APPEND _sanitizers UBSan)
endif()
if(VOID_ENABLE_TSAN)
list(APPEND _sanitizers TSan)
endif()
if(NOT _sanitizers)
set(_sanitizers none)
else()
string(REPLACE ";" "+" _sanitizers "${_sanitizers}")
endif()
execute_process(
COMMAND "${CMAKE_C_COMPILER}" -dumpmachine
OUTPUT_VARIABLE _triple
ERROR_QUIET
OUTPUT_STRIP_TRAILING_WHITESPACE)
set(_content
"# Generated by VoidLibrary's build system (cmake/Targets.cmake).
# Describes the exact target tuple this build was configured with.
set(VOID_TARGET_MANIFEST_TARGET \"${VOID_TARGET_DETECTED}\")
set(VOID_TARGET_MANIFEST_TARGET_ORIGIN \"${VOID_TARGET}\")
set(VOID_TARGET_MANIFEST_TRIPLE \"${_triple}\")
set(VOID_TARGET_MANIFEST_SYSTEM_NAME \"${CMAKE_SYSTEM_NAME}\")
set(VOID_TARGET_MANIFEST_SYSTEM_PROCESSOR \"${CMAKE_SYSTEM_PROCESSOR}\")
set(VOID_TARGET_MANIFEST_COMPILER_ID \"${CMAKE_CXX_COMPILER_ID}\")
set(VOID_TARGET_MANIFEST_COMPILER_VERSION \"${CMAKE_CXX_COMPILER_VERSION}\")
set(VOID_TARGET_MANIFEST_CXX_STANDARD \"${CMAKE_CXX_STANDARD}\")
set(VOID_TARGET_MANIFEST_LINKAGE \"${_linkage}\")
set(VOID_TARGET_MANIFEST_REFLECTION \"${_reflection}\")
set(VOID_TARGET_MANIFEST_STD_EXPECTED \"${_expected}\")
set(VOID_TARGET_MANIFEST_SANITIZERS \"${_sanitizers}\")
set(VOID_TARGET_MANIFEST_TESTING \"${VOID_ENABLE_TESTING}\")
set(VOID_TARGET_MANIFEST_WARNINGS_AS_ERRORS \"${VOID_WARNINGS_AS_ERRORS}\")
set(VOID_TARGET_MANIFEST_MODULES \"${_modules_value}\")
")
file(WRITE "${path}" "${_content}")
endfunction()
+37 -2
View File
@@ -22,6 +22,15 @@ set(fixture_class_name "")
set(fixture_indent "")
set(line_number 0)
# A Test/DisabledTest declaration may wrap across lines. These patterns let
# the loop join such a declaration into one logical line instead of silently
# dropping it (X-QA-03).
set(_test_decl_regex "(Void::Testing::)?(Test|DisabledTest)[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]*\\(\\s*\\)")
set(_test_decl_start_regex "^[ \t]*(Void::Testing::)?(Test|DisabledTest)([ \t]|$)")
set(_test_decl_partial_regex "^[ \t]*(Void::Testing::)?(Test|DisabledTest)([ \t]+[A-Za-z_][A-Za-z0-9_]*)?[ \t]*\\(?[ \t]*$")
set(pending_decl "")
set(pending_decl_line 0)
# Accumulators for preceding comments
set(current_tags "")
set(current_skip "")
@@ -33,6 +42,32 @@ foreach(line IN LISTS lines)
string(REPLACE "__VOID_SCAN_SC__" ";" line "${line}")
string(REPLACE "__VOID_SCAN_BS__" "\\" line "${line}")
# Join a wrapped test declaration before any other per-line handling so
# tags/skip comments that precede it stay associated with it.
set(registration_line ${line_number})
if(pending_decl)
string(APPEND pending_decl " ${line}")
if(pending_decl MATCHES "${_test_decl_regex}")
# Complete: process the joined declaration as one logical line.
set(line "${pending_decl}")
set(registration_line ${pending_decl_line})
set(pending_decl "")
elseif(pending_decl MATCHES "${_test_decl_partial_regex}")
continue()
else()
# Not a wrapped test declaration after all; handle this line
# normally and drop the accumulated prefix.
set(pending_decl "")
endif()
elseif(line MATCHES "${_test_decl_start_regex}" AND NOT line MATCHES "${_test_decl_regex}")
set(pending_decl "${line}")
set(pending_decl_line ${line_number})
if(pending_decl MATCHES "${_test_decl_partial_regex}")
continue()
endif()
set(pending_decl "")
endif()
# Parse preceding comments for @tag and @skip
string(REGEX MATCH "//[ \t]*@tag[ \t]+(.*)" _tag_match "${line}")
if(_tag_match)
@@ -129,11 +164,11 @@ foreach(line IN LISTS lines)
if(in_fixture_class)
string(APPEND registrations
"static Void::Testing::Detail::test_registrar<&${fixture_class_name}::${func_name}> _auto_reg_${safe_func_name}{\"${SUITE_NAME}\", \"${INPUT_FILE_FORWARD}\", ${line_number}, \"${func_name}\", std::vector<std::string>${tags_cpp}, ${is_skipped_str}, ${current_skip}};\n"
"static Void::Testing::Detail::test_registrar<&${fixture_class_name}::${func_name}> _auto_reg_${safe_func_name}{\"${SUITE_NAME}\", \"${INPUT_FILE_FORWARD}\", ${registration_line}, \"${func_name}\", std::vector<std::string>${tags_cpp}, ${is_skipped_str}, ${current_skip}};\n"
)
else()
string(APPEND registrations
"static Void::Testing::Detail::test_registrar<&${func_name}> _auto_reg_${safe_func_name}{\"${SUITE_NAME}\", \"${INPUT_FILE_FORWARD}\", ${line_number}, \"${func_name}\", std::vector<std::string>${tags_cpp}, ${is_skipped_str}, ${current_skip}};\n"
"static Void::Testing::Detail::test_registrar<&${func_name}> _auto_reg_${safe_func_name}{\"${SUITE_NAME}\", \"${INPUT_FILE_FORWARD}\", ${registration_line}, \"${func_name}\", std::vector<std::string>${tags_cpp}, ${is_skipped_str}, ${current_skip}};\n"
)
endif()
+33
View File
@@ -0,0 +1,33 @@
# CMake toolchain for cross-compiling to Windows x64 with MinGW-w64.
#
# Works with the GCC-based mingw-w64 package and with the LLVM-MinGW
# toolchain (Dockerfile.mingw). Override the compiler paths for your install.
#
# Usage:
# cmake -B build-mingw -S . -G Ninja \
# -DCMAKE_TOOLCHAIN_FILE=cmake/toolchains/mingw-w64.cmake \
# -DCMAKE_BUILD_TYPE=Debug
set(CMAKE_SYSTEM_NAME Windows)
set(CMAKE_SYSTEM_PROCESSOR x86_64)
if(NOT DEFINED VOID_MINGW_PREFIX)
set(VOID_MINGW_PREFIX x86_64-w64-mingw32)
endif()
find_program(VOID_MINGW_CXX NAMES "${VOID_MINGW_PREFIX}-clang++"
"${VOID_MINGW_PREFIX}-g++" REQUIRED)
find_program(VOID_MINGW_C NAMES "${VOID_MINGW_PREFIX}-clang"
"${VOID_MINGW_PREFIX}-gcc" REQUIRED)
find_program(VOID_MINGW_RC NAMES "${VOID_MINGW_PREFIX}-windres")
set(CMAKE_CXX_COMPILER "${VOID_MINGW_CXX}")
set(CMAKE_C_COMPILER "${VOID_MINGW_C}")
if(VOID_MINGW_RC)
set(CMAKE_RC_COMPILER "${VOID_MINGW_RC}")
endif()
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
+4 -4
View File
@@ -189,9 +189,9 @@ specs' observed baselines (D-035); not separately scheduled.
| ID | Finding | Source | State |
| --- | --- | --- | --- |
| X-QA-01 | `VOID_WARNINGS_AS_ERRORS=ON` does not reach the generated `VoidTests` translation units, so test code is not compiled with `-Werror` | M-FUNCTIONAL-03 implementer report | PLANNED (verify, then fix in `tests/CMakeLists.txt`) |
| X-QA-02 | `src/Testing/Runner.cpp` recomputes pass/fail from only the first 1,000 retained assertions per test (`kMaxRetainedAssertionsPerTest`); later failures in one test can pass silently | M-FUNCTIONAL-03 implementer report | PLANNED (verify, then count failures independently of retention) |
| X-QA-03 | Test scanner is line-anchored; a wrapped test declaration is silently dropped | M-FUNCTIONAL-03 implementer report | PLANNED (scanner hardening or lint) |
| X-QA-01 | `VOID_WARNINGS_AS_ERRORS=ON` does not reach the generated `VoidTests` translation units, so test code is not compiled with `-Werror` | M-FUNCTIONAL-03 implementer report | VERIFIED (`77a2bce`): `tests/CMakeLists.txt` applies `-Wall -Wextra -Wpedantic -Werror` to `VoidTests` (with `-Wno-subobject-linkage` for GCC coroutine-frame noise); exposed warnings fixed in `Core/Meta.hpp` and `Time/Bench.cpp` |
| X-QA-02 | `src/Testing/Runner.cpp` recomputes pass/fail from only the first 1,000 retained assertions per test (`kMaxRetainedAssertionsPerTest`); later failures in one test can pass silently | M-FUNCTIONAL-03 implementer report | VERIFIED (`430deab`, merged `2501c4d`): `TestResult::failed_assertions` is counted in `Assert.cpp` at record time and both Runner paths use it, keeping the bounded retention for reporting; regression test `testing_runner_counts_failure_after_retention_cap` failed before and passes after; follow-up `898968d` resets the tally in the TestingMock failure-capture helper |
| X-QA-03 | Test scanner is line-anchored; a wrapped test declaration is silently dropped | M-FUNCTIONAL-03 implementer report | VERIFIED (`4bc8a7c`, merged `df41037`): `VoidTestScanner.cmake` joins wrapped `Test`/`DisabledTest` declarations; `ScannerWrapped` fixture covers wrapped return type, name and fixture member (4/4 discovered) |
| X-WF-01 | Agent `isolation: worktree` checkouts start at `main` (`38436b1`), not the wave branch tip; dispatches must fast-forward the worktree to the stated HEAD first | Observed in A1 | RECORDED (dispatch rule) |
## VoidForge upstream requests — M04 identity batch (received 2026-11-29; D-041)
@@ -202,4 +202,4 @@ specs' observed baselines (D-035); not separately scheduled.
| VL-CRYPTO-02 | P1 | `pbkdf2_hmac_sha256(password, salt, iterations, out_len)` (RFC 8018 §5.2) on the builtin HMAC path; RFC 7914 §11 vectors; bounded iterations/output | PLANNED |
| VL-NET-02 | P1 (blocks Forge production email) | Public TLS client stream (TCP+TLS, CA + hostname verification, STARTTLS upgrade) + minimal SMTP submission client (EHLO, STARTTLS-required or implicit TLS, AUTH PLAIN over TLS only, MAIL/RCPT/DATA with dot-stuffing, bounded size, deadlines) | PLANNED |
| VL-TEXT-01 | P2 | RFC 4648 base32 + Crockford base32 encode/decode | PLANNED |
| X-QA-04 | AsyncRetry follow-ups from W11-REVIEW-B1b: race test only exercises the late-stop interleaving (add handshake/alternation); add direct checks of `detail::retry_backoff_stop_reason`; add a throwing-classifier test | W11-REVIEW-B1b P3-1/2/4 | PLANNED |
| X-QA-04 | AsyncRetry follow-ups from W11-REVIEW-B1b: race test only exercises the late-stop interleaving (add handshake/alternation); add direct checks of `detail::retry_backoff_stop_reason`; add a throwing-classifier test | W11-REVIEW-B1b P3-1/2/4 | VERIFIED (`65185f2`): added `async_retry_backoff_stop_reason_mapping`, `async_retry_stop_poll_handshake_alternation` (stop-first and poll-first orders) and `async_retry_throwing_classifier_propagates` |
+249
View File
@@ -0,0 +1,249 @@
# Target support
VoidLibrary is qualified per **target profile**: a platform, a compiler and
standard library, the external dependencies that are expected to exist, and
the set of modules that are expected to build there. The profile is detected
from the toolchain at configure time, validated against the selected modules,
and recorded in `void-target-manifest.cmake` (installed next to
`VoidConfig.cmake`).
```bash
# Native Linux (default)
cmake -S . -B build -G Ninja -DVOID_ENABLE_TESTING=ON
# Force a profile for a qualification run (normally auto-detected)
cmake -S . -B build-wasm -G Ninja -DVOID_TARGET=wasm \
-DVOID_ENABLED_MODULES="Core;Functional;Text;Data"
# Cross build (Windows client example)
cmake -S . -B build-mingw -G Ninja \
-DCMAKE_TOOLCHAIN_FILE=cmake/toolchains/mingw-w64.cmake \
-DVOID_ENABLED_MODULES="Core;Functional;Text;Data"
```
`VOID_TARGET` is `auto` by default. The recognized values are `linux`,
`linux-musl`, `windows` and `wasm`; anything else fails at configure time with
the list of known targets. `cmake/Targets.cmake` holds the allowlists and the
validation rules.
## Manifest
Every configure writes `void-target-manifest.cmake`:
| Field | Meaning |
|-------|---------|
| `VOID_TARGET_MANIFEST_TARGET` | detected/forced profile (`linux`, `linux-musl`, `windows`, `wasm`) |
| `VOID_TARGET_MANIFEST_TARGET_ORIGIN` | `auto` or the forced `VOID_TARGET` value |
| `VOID_TARGET_MANIFEST_TRIPLE` | `CMAKE_C_COMPILER -dumpmachine` |
| `VOID_TARGET_MANIFEST_SYSTEM_NAME` / `..._SYSTEM_PROCESSOR` | CMake system identification |
| `VOID_TARGET_MANIFEST_COMPILER_ID` / `..._COMPILER_VERSION` | compiler tuple |
| `VOID_TARGET_MANIFEST_CXX_STANDARD` | language standard |
| `VOID_TARGET_MANIFEST_LINKAGE` | `shared` or `static` |
| `VOID_TARGET_MANIFEST_REFLECTION` | C++26 reflection available (`yes`/`no`) |
| `VOID_TARGET_MANIFEST_STD_EXPECTED` | `<expected>` available |
| `VOID_TARGET_MANIFEST_SANITIZERS` | `none`, `ASan`, `UBSan`, `TSan` or a combination |
| `VOID_TARGET_MANIFEST_TESTING` | `VOID_ENABLE_TESTING` |
| `VOID_TARGET_MANIFEST_MODULES` | configured modules |
Consumers can read it after `find_package(Void)`:
```cmake
include("${Void_DIR}/void-target-manifest.cmake")
message(STATUS "Void target: ${VOID_TARGET_MANIFEST_TARGET}")
```
## Qualified tuples
### Linux (qualified)
| Item | Value |
|------|-------|
| Triple | `x86_64-unknown-linux-gnu` (NixOS, glibc) |
| Compiler | GCC 16.2.0 (`dev cpp-gcc`) |
| Standard library | libstdc++ 16 |
| CMake / generator | CMake 4.5.0, Ninja 1.13.2 |
| Language | C++26, reflection `yes` (`-freflection`) |
| Dependencies | Boost (headers/url/beast/asio), OpenSSL, SQLite3, Lua 5.4 (optional) |
| Modules | all |
| Observed | `Testing;Core` configure/build clean; `ctest` 3/3 (VoidTests, installed consumers, target qualification) |
The Linux profile is the reference target: every module is allowed and the
per-module platform code selects the native implementation.
### Linux / musl (configure/build/install/consume qualified)
| Item | Value |
|------|-------|
| Triple | `x86_64-alpine-linux-musl` (Alpine 3.23.8, musl 1.2.5-r24) |
| Compiler | Alpine GCC 15.2.0 (Clang accepted by the allowlist) |
| Standard library | libstdc++ with musl 1.2.5 |
| CMake / generator | CMake 4.1.3, Ninja 1.13.2 |
| Dependencies | `boost-dev` 1.84.0, `openssl-dev` 3.5.10, `sqlite-dev` 3.53.4, `lua5.4-dev` 5.4.8, `linux-headers` from apk |
| Language | C++26, reflection `no` (GCC 15), `<expected>` `yes` |
| Modules | `Async Binary Containers Core Crypto Data Functional FunctionalCoreFormatting IO IPC LogState Math Memory Net ObservabilityHooks Resilience Sqlite System SystemAsync Text Time` |
| Observed | RelWithDebInfo with `-DVOID_WARNINGS_AS_ERRORS=ON` and `-DVOID_ENABLE_TESTING=OFF`: configure detected `linux-musl`, build passed, `cmake --install` to a prefix succeeded, and the isolated `TargetProfile` consumer configured, linked, and ran (`VoidTargetProfileConsumer` 1/1) recording `target=linux-musl triple=x86_64-alpine-linux-musl compiler=GNU-15.2.0 linkage=shared reflection=no`. Test suite with `-DVOID_ENABLE_TESTING=ON`: 1226 tests, 1221 passed, 5 skipped, 0 failed |
The test suite is qualified too: with `VOID_ENABLE_TESTING=ON` (modules
`Async Binary Containers Core Crypto Data Functional FunctionalCoreFormatting
IO IPC LogState Math Memory Net ObservabilityHooks Resilience Sqlite System
SystemAsync Testing Text Time`) the Alpine 3.23 container build ran
**1226 tests: 1221 passed, 5 skipped, 0 failed**. Reflection-only tests are
skipped through `// @requires-reflection`. The run also exposed a test bug in
`Net/HttpDuplex.cpp` (`recv_until` consumed body bytes past the header
marker); the helper now reads byte-wise and the duplex tests pass on musl and
glibc.
Detection uses `CMAKE_C_COMPILER -dumpmachine` (or
`CMAKE_C_LIBRARY_ARCHITECTURE`/`CMAKE_C_FLAGS`) matching `musl`. The profile is
recognized and configured like Linux; musl-specific behaviour (subprocess
`/proc`, `dl`, locale) must still be verified before claiming full support.
### Windows client (compile/install/consume + Wine runtime qualified)
| Item | Value |
|------|-------|
| Triple | `x86_64-w64-mingw32` |
| Compiler | MinGW-w64 GCC 16.2.0 |
| Standard library | libstdc++ + mingw-w64 CRT (mcfgthread threading in the Nix wrapper) |
| CMake / generator | CMake 4.5.0, Ninja 1.13.2 |
| Language | C++26, reflection `yes` |
| Runtime | Wine 11.0 (`wine64`), no native Windows runner available |
| Modules | `Algorithms Async Binary Containers Core Data Discovery Fsm Functional Log LogState Math Memory Messaging Observability ObservabilityHooks Scheduler Service Testing TestingMock Text Time Unicode` |
| Observed | configure, compile, `cmake --install`, consume (`TargetProfile.exe` linked); `VoidTests.exe` under Wine: **1364 tests, 1360 passed, 4 skipped, 0 failed** |
Notes from the runtime run:
- `IO` is **not** in the Windows allowlist. It builds, but its native backend
is Linux-only (`EpollBackend`); on Windows `Driver::create` returns
`IoErrorCode::unsupported` unless the mock backend is selected. A Windows
IO backend (IOCP) is a separate task.
- `Observability` links after replacing the namespace-scope
`inline thread_local` hook stack with a function-local `thread_local`
accessor (MinGW emitted duplicate TLS init functions).
- Test code is portable: POSIX-only descriptor assertions are guarded, the
Log hardening test closes its `ifstream` before removing the file, and the
subprocess-isolation test skips when `current_executable_path()` is not
implemented (Windows has no subprocess isolation yet).
- MinGW test builds need `-Wa,-mbig-obj`: the Fsm hardening test TU exceeds
the COFF section limit with the default object format.
- Runtime observations come from Wine, not a native Windows runner; a
Windows CI runner should confirm them.
The Nix MinGW wrapper needs the mcfgthread include/library paths explicitly:
```bash
MINGW=/nix/store/...-x86_64-w64-mingw32-gcc-wrapper-16.2.0/bin
MCFG=/nix/store/...-mcfgthread-x86_64-w64-mingw32-2.5.1/lib
MCFGINC=/nix/store/...-mcfgthread-x86_64-w64-mingw32-2.5.1-dev/include
cmake -S . -B build-mingw -G Ninja \
-DCMAKE_SYSTEM_NAME=Windows \
-DCMAKE_C_COMPILER="$MINGW/x86_64-w64-mingw32-gcc" \
-DCMAKE_CXX_COMPILER="$MINGW/x86_64-w64-mingw32-g++" \
-DCMAKE_C_FLAGS="-I$MCFGINC" -DCMAKE_CXX_FLAGS="-I$MCFGINC" \
-DCMAKE_EXE_LINKER_FLAGS="-L$MCFG" \
-DCMAKE_SHARED_LINKER_FLAGS="-L$MCFG"
```
A regular MinGW-w64 installation with winpthreads does not need those extra
flags.
### Browser / Wasm subset (qualified)
| Item | Value |
|------|-------|
| Triple | `wasm32-unknown-emscripten` |
| Compiler | Emscripten 6.0.9 (Clang 22.1.8) |
| Standard library | libc++ + Emscripten libc |
| CMake / generator | CMake 4.5 via `emcmake`, Ninja, Node 24.22.3 as the test emulator |
| Language | C++26 without reflection (`VOID_HAS_CXX26_REFLECTION=no`) |
| Modules | `Algorithms Binary Containers Core Data Functional LogState Math Memory Testing TestingMock Text Time Unicode` |
| Observed | library: configure, compile, install, consume and run under Node; tests: **901 tests, 895 passed, 6 skipped, 0 failed** under Node |
The allowlist is fail-closed: native networking (`Net`, `RPC`), processes and
filesystem (`System`, `SystemAsync`), IPC, SQLite, plugins and anything that
needs threads or reflection stay out. Do not add a module until it has been
configured and compiled with `emcmake`.
Verified commands:
```bash
# Library subset
emcmake cmake -S . -B build-wasm -G Ninja -DCMAKE_BUILD_TYPE=Debug \
-DCMAKE_CXX_SCAN_FOR_MODULES=OFF \
-DVOID_ENABLE_TESTING=OFF \
-DVOID_ENABLED_MODULES="Algorithms;Binary;Containers;Core;Data;Functional;LogState;Math;Memory;Testing;TestingMock;Text;Time;Unicode"
cmake --build build-wasm
cmake --install build-wasm --prefix "$PWD/build-wasm-install"
# Consumer (the install lives outside the Emscripten sysroot)
emcmake cmake -S tests/package/TargetProfile -B build-wasm-consumer -G Ninja \
-DCMAKE_PREFIX_PATH="$PWD/build-wasm-install" \
-DCMAKE_FIND_ROOT_PATH_MODE_PACKAGE=BOTH \
-DCMAKE_CXX_SCAN_FOR_MODULES=OFF \
-DVOID_EXPECTED_TARGET=wasm
cmake --build build-wasm-consumer
node build-wasm-consumer/void_target_profile_consumer.js
```
`CMAKE_CXX_SCAN_FOR_MODULES=OFF` avoids CMake's C++20 module dependency
scanner calling Emscripten's `emscan-deps`, which is not shipped by every
Emscripten package. `CMAKE_FIND_ROOT_PATH_MODE_PACKAGE=BOTH` is needed
because the Emscripten toolchain restricts package lookup to its sysroot.
The **test suite** is qualified with pthreads, exception handling and a
larger stack:
```bash
emcmake cmake -S . -B build-wasm-tests -G Ninja -DCMAKE_BUILD_TYPE=Debug \
-DCMAKE_CXX_SCAN_FOR_MODULES=OFF \
-DBUILD_SHARED_LIBS=OFF \
-DCMAKE_CXX_FLAGS="-fexceptions -pthread" \
-DCMAKE_EXE_LINKER_FLAGS="-fexceptions -pthread -sSTACK_SIZE=16777216 \
-sINITIAL_MEMORY=134217728 -sALLOW_MEMORY_GROWTH=1 -sMAXIMUM_MEMORY=1073741824" \
-DVOID_ENABLE_TESTING=ON \
-DVOID_ENABLED_MODULES="Algorithms;Binary;Containers;Core;Data;Functional;LogState;Math;Memory;Testing;TestingMock;Text;Time;Unicode"
cmake --build build-wasm-tests
node build-wasm-tests/tests/VoidTests.js --no-color
```
Static linking (`BUILD_SHARED_LIBS=OFF`) is required for exception handling
across the test binary; `-fexceptions` enables catching, `-pthread` enables
the threading tests, and the stack/memory flags accommodate the deepest
recursive tests.
Portable fallbacks added for libc++ without the C++23/26 pieces:
`Core/Publication` uses a mutex-protected `shared_ptr` when
`__cpp_lib_atomic_shared_ptr` is absent, and `TestingMock` uses an internal
move-only function wrapper when `__cpp_lib_move_only_function` is absent.
Reflection-dependent test files are gated with `// @requires-reflection`
(Core/Meta, Core/FlagsReflect, Data/CsvReflect, Data/Reflect*,
Functional/ResultReflectionFormat, Testing/ContainerFixture,
TestingMock/Reflect, Configuration/Fsm annotation tests) and are skipped when
`VOID_HAS_CXX26_REFLECTION` is false, so a non-reflecting compiler no longer
fails on scanner-generated registrations for functions hidden by `#ifdef`.
Runtime observations use Node; a browser runner should confirm them.
## Sanitizers
Sanitizer builds are native-only qualification configurations, not target
profiles: `VOID_ENABLE_ASAN`, `VOID_ENABLE_UBSAN` and `VOID_ENABLE_TSAN`
instrument the host build and are recorded in the manifest. Production
packages are built with sanitizers off. ASan+TSan is rejected; TSan is
rejected on `wasm`.
## Qualification test
`tests/package/TargetQualification.cmake` (ctest
`VoidTargetQualification`) installs the build tree and:
1. Consumes the install through `tests/package/TargetProfile`, asserting the
manifest target/triple/compiler/linkage/reflection fields and running one
Core behaviour.
2. Rejects an unknown `VOID_TARGET`.
3. Rejects a native module (`IPC`) and native networking (`Net`) on the
`wasm` profile.
4. Rejects a missing external dependency (`Sqlite` without SQLite3).
5. Configures the pure wasm subset and asserts the manifest records
`wasm`.
+156
View File
@@ -0,0 +1,156 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include <map>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
namespace Void::Algorithms
{
enum class ReadSetStatus : std::uint8_t {
/// A new key/revision pair was recorded.
recorded = 0,
/// The same key with the same revision was already recorded.
unchanged,
/// The same key was observed with a different revision.
conflicting,
/// The entry bound is reached; nothing was recorded.
capacity_exceeded,
/// The key is empty.
invalid_key,
};
enum class ReadSetValidation : std::uint8_t {
valid = 0,
/// A recorded key is missing or has a different revision.
invalidated,
/// The validating view belongs to another epoch.
epoch_changed,
/// A conflicting observation was reported; the set cannot be published.
conflicted,
/// An observation was rejected for capacity; the set is incomplete.
incomplete,
};
struct ReadSetLimits {
std::size_t max_entries{256};
};
/// Bounded set of distinct key/revision pairs consulted while computing a
/// result, qualified by an epoch.
///
/// Repeated reads of one unchanged key consume one entry. Observing the same
/// key with a different revision is reported as a conflict, and an entry over
/// the bound as capacity exhaustion; `validate` refuses to report a conflicted
/// or incomplete set as valid so a result cannot be published from it.
///
/// Validation compares the recorded set against a stable read view supplied by
/// the caller (a revision lookup per key plus the view's epoch). An epoch
/// change invalidates the set even when every numeric revision matches. Keys
/// not in the set (unrelated edits) do not affect the result.
class RevisionReadSet
{
public:
using Limits = ReadSetLimits;
explicit RevisionReadSet(std::uint64_t epoch, Limits limits = {})
: epoch_(epoch)
, limits_(limits)
{
}
[[nodiscard]] std::uint64_t epoch() const noexcept { return epoch_; }
[[nodiscard]] ReadSetStatus observe(std::string key,
std::uint64_t revision)
{
if (key.empty()) {
return ReadSetStatus::invalid_key;
}
if (const auto found = entries_.find(key);
found != entries_.end()) {
if (found->second == revision) {
return ReadSetStatus::unchanged;
}
conflicted_ = true;
return ReadSetStatus::conflicting;
}
if (entries_.size() >= limits_.max_entries) {
incomplete_ = true;
return ReadSetStatus::capacity_exceeded;
}
entries_.emplace(std::move(key), revision);
return ReadSetStatus::recorded;
}
[[nodiscard]] bool contains(std::string_view key) const
{
return entries_.contains(std::string{key});
}
[[nodiscard]] std::optional<std::uint64_t>
revision_of(std::string_view key) const
{
const auto found = entries_.find(std::string{key});
if (found == entries_.end()) {
return std::nullopt;
}
return found->second;
}
[[nodiscard]] std::size_t size() const noexcept
{
return entries_.size();
}
[[nodiscard]] bool conflicted() const noexcept { return conflicted_; }
[[nodiscard]] bool incomplete() const noexcept { return incomplete_; }
/// Recorded observations, sorted by key.
[[nodiscard]] const std::map<std::string, std::uint64_t>&
entries() const noexcept
{
return entries_;
}
/// Validate against a stable read view.
///
/// `lookup(key)` returns the current revision of `key`, or `nullopt`
/// when it no longer exists. `view_epoch` is the epoch of the view.
template <typename Lookup>
[[nodiscard]] ReadSetValidation
validate(std::uint64_t view_epoch, Lookup&& lookup) const
{
if (view_epoch != epoch_) {
return ReadSetValidation::epoch_changed;
}
if (conflicted_) {
return ReadSetValidation::conflicted;
}
if (incomplete_) {
return ReadSetValidation::incomplete;
}
for (const auto& [key, revision] : entries_) {
const auto current = lookup(key);
if (!current.has_value() || *current != revision) {
return ReadSetValidation::invalidated;
}
}
return ReadSetValidation::valid;
}
private:
std::uint64_t epoch_{0};
Limits limits_{};
std::map<std::string, std::uint64_t> entries_;
bool conflicted_{false};
bool incomplete_{false};
};
} // namespace Void::Algorithms
@@ -0,0 +1,137 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include <deque>
#include <mutex>
#include <optional>
#include <utility>
namespace Void::Async
{
/// Bounded work queue whose admission is conditioned on an exact retained
/// publication token.
///
/// A producer validates a publication (and may retain its value elsewhere),
/// then submits work with that token. Comparison against the current token and
/// the capacity reservation happen under one lock, so a replacement published
/// between validation and submission is detected: the work is not moved and
/// the queue is unchanged.
///
/// Refusal outcomes are distinct: `publication_changed`, `saturated` and
/// `closed` (checked in that order). The payload is moved only when the result
/// is `admitted`. Admitted work is popped exactly once.
///
/// Thread-safe.
template <typename Work, typename Token = std::uint64_t>
class PublicationGatedQueue
{
public:
struct Limits {
std::size_t capacity{64};
};
enum class Status : std::uint8_t {
admitted = 0,
/// The current token differs from the expected one.
publication_changed,
/// The queue is at capacity.
saturated,
/// The queue no longer accepts submissions.
closed,
};
explicit PublicationGatedQueue(Token initial,
Limits limits = Limits{})
: token_(std::move(initial))
, limits_(limits)
{
}
PublicationGatedQueue(const PublicationGatedQueue&) = delete;
PublicationGatedQueue& operator=(const PublicationGatedQueue&) =
delete;
/// Publish a replacement token. Returns false once closed.
bool publish(Token next)
{
std::lock_guard lock{mutex_};
if (closed_) {
return false;
}
token_ = std::move(next);
return true;
}
[[nodiscard]] Token current() const
{
std::lock_guard lock{mutex_};
return token_;
}
/// Admit `work` only if `expected` is still the current publication and
/// capacity is available. `work` is moved only on `admitted`.
[[nodiscard]] Status try_submit(const Token& expected, Work&& work)
{
std::lock_guard lock{mutex_};
if (closed_) {
return Status::closed;
}
if (!(token_ == expected)) {
return Status::publication_changed;
}
if (queue_.size() >= limits_.capacity) {
return Status::saturated;
}
queue_.push_back(std::move(work));
return Status::admitted;
}
/// Remove one admitted item, if any.
[[nodiscard]] std::optional<Work> try_pop()
{
std::lock_guard lock{mutex_};
if (queue_.empty()) {
return std::nullopt;
}
Work work = std::move(queue_.front());
queue_.pop_front();
return work;
}
void close()
{
std::lock_guard lock{mutex_};
closed_ = true;
}
[[nodiscard]] bool closed() const
{
std::lock_guard lock{mutex_};
return closed_;
}
[[nodiscard]] std::size_t size() const
{
std::lock_guard lock{mutex_};
return queue_.size();
}
[[nodiscard]] Limits limits() const
{
std::lock_guard lock{mutex_};
return limits_;
}
private:
mutable std::mutex mutex_;
Token token_;
Limits limits_{};
std::deque<Work> queue_;
bool closed_{false};
};
} // namespace Void::Async
+323
View File
@@ -0,0 +1,323 @@
#pragma once
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <map>
#include <optional>
#include <set>
#include <span>
#include <utility>
#include <vector>
namespace Void::Containers
{
/// Finite sparse 3D page table with revision-checked atomic edit batches.
///
/// Cells are grouped into fixed `PageSize`-cubed pages. Pages are allocated on
/// demand (a missing page reads as `empty` with revision 0) and bounded by
/// `Limits::max_pages`. `apply` validates every precondition, budget and
/// revision before touching the table; on failure nothing changes.
///
/// Batch semantics:
/// - Duplicate cell addresses in one batch are rejected.
/// - An edit whose value equals the current cell does not allocate a page and
/// does not bump a revision.
/// - `expected_revision` is checked against the page revision at batch start
/// (0 for a missing page).
/// - A changed page whose revision is already the maximum fails the batch.
/// - The result lists changed pages sorted by page identity with their new
/// revisions.
///
/// Single-threaded by contract; callers synchronize concurrent access.
template <typename Cell, std::size_t PageSize = 32> class SparsePageTable
{
public:
static_assert(PageSize > 0);
static constexpr std::size_t kPageSize = PageSize;
static constexpr std::size_t kCellsPerPage =
PageSize * PageSize * PageSize;
using Revision = std::uint64_t;
struct PageId {
std::int64_t x{0};
std::int64_t y{0};
std::int64_t z{0};
[[nodiscard]] auto
operator<=>(const PageId&) const noexcept = default;
[[nodiscard]] bool
operator==(const PageId&) const noexcept = default;
};
struct CellAddress {
std::int64_t x{0};
std::int64_t y{0};
std::int64_t z{0};
[[nodiscard]] auto
operator<=>(const CellAddress&) const noexcept = default;
[[nodiscard]] bool
operator==(const CellAddress&) const noexcept = default;
};
struct Edit {
CellAddress address;
Cell value;
std::optional<Revision> expected_revision{};
[[nodiscard]] bool
operator==(const Edit&) const = default;
};
struct Limits {
std::size_t max_pages{1024};
};
enum class EditStatus : std::uint8_t {
committed = 0,
/// A page's expected revision did not match the current one.
stale_revision,
/// A changed page already has the maximum revision.
revision_exhausted,
/// The batch would allocate more pages than the budget allows.
page_budget_exceeded,
/// The same cell address appears twice in the batch.
duplicate_edit,
};
struct ChangedPage {
PageId page;
Revision revision{0};
[[nodiscard]] bool
operator==(const ChangedPage&) const = default;
};
struct EditResult {
EditStatus status{EditStatus::committed};
std::vector<ChangedPage> changed{};
[[nodiscard]] bool committed() const noexcept
{
return status == EditStatus::committed;
}
};
struct PageState {
PageId page;
Revision revision{0};
std::array<Cell, kCellsPerPage> cells{};
[[nodiscard]] bool operator==(const PageState&) const = default;
};
struct State {
std::vector<PageState> pages;
[[nodiscard]] bool operator==(const State&) const = default;
};
explicit SparsePageTable(Limits limits = Limits{},
Cell empty = Cell{})
: limits_(limits)
, empty_(std::move(empty))
{
}
[[nodiscard]] const Limits& limits() const noexcept { return limits_; }
[[nodiscard]] const Cell& empty_value() const noexcept
{
return empty_;
}
[[nodiscard]] std::size_t page_count() const noexcept
{
return pages_.size();
}
/// Cell value; a missing page yields `empty_value()`.
[[nodiscard]] Cell get(CellAddress address) const
{
const auto [id, offset] = locate(address);
const auto found = pages_.find(id);
if (found == pages_.end()) {
return empty_;
}
return found->second.cells[offset];
}
/// Page revision, or `nullopt` when the page is not allocated.
[[nodiscard]] std::optional<Revision>
page_revision(PageId page) const
{
const auto found = pages_.find(page);
if (found == pages_.end()) {
return std::nullopt;
}
return found->second.revision;
}
/// Apply all edits or none.
[[nodiscard]] EditResult apply(std::span<const Edit> edits)
{
if (edits.empty()) {
return EditResult{};
}
std::set<CellAddress> seen;
std::map<PageId, std::vector<const Edit*>> grouped;
for (const auto& edit : edits) {
if (!seen.insert(edit.address).second) {
return EditResult{.status =
EditStatus::duplicate_edit};
}
grouped[page_of(edit.address)].push_back(&edit);
}
std::map<PageId, bool> changes;
std::size_t new_pages = 0;
for (const auto& [id, page_edits] : grouped) {
const auto found = pages_.find(id);
const Page* page =
found == pages_.end() ? nullptr : &found->second;
const Revision revision = page == nullptr ? 0
: page->revision;
for (const Edit* edit : page_edits) {
if (edit->expected_revision.has_value() &&
*edit->expected_revision != revision) {
return EditResult{
.status = EditStatus::stale_revision};
}
}
bool changed = false;
for (const Edit* edit : page_edits) {
const auto offset = offset_of(edit->address);
const Cell& current =
page == nullptr ? empty_ : page->cells[offset];
if (!(current == edit->value)) {
changed = true;
break;
}
}
if (!changed) {
continue;
}
if (revision ==
std::numeric_limits<Revision>::max()) {
return EditResult{
.status = EditStatus::revision_exhausted};
}
changes.emplace(id, true);
if (page == nullptr) {
++new_pages;
}
}
if (pages_.size() + new_pages > limits_.max_pages) {
return EditResult{.status =
EditStatus::page_budget_exceeded};
}
EditResult result;
for (const auto& [id, changed] : changes) {
(void)changed;
auto& page = pages_[id];
for (const Edit* edit : grouped.at(id)) {
page.cells[offset_of(edit->address)] = edit->value;
}
++page.revision;
result.changed.push_back(
ChangedPage{.page = id, .revision = page.revision});
}
return result;
}
[[nodiscard]] State save() const
{
State state;
state.pages.reserve(pages_.size());
for (const auto& [id, page] : pages_) {
state.pages.push_back(PageState{
.page = id, .revision = page.revision, .cells = page.cells});
}
return state;
}
/// Restore saved pages. Rejects duplicate page ids, more pages than the
/// limit, or a page with no revision left for an edit.
[[nodiscard]] static std::optional<SparsePageTable>
restore(State state, Limits limits = Limits{},
Cell empty = Cell{})
{
if (state.pages.size() > limits.max_pages) {
return std::nullopt;
}
SparsePageTable table{limits, std::move(empty)};
for (auto& saved : state.pages) {
if (!table.pages_
.emplace(saved.page,
Page{.cells = saved.cells,
.revision = saved.revision})
.second) {
return std::nullopt;
}
}
return table;
}
private:
struct Page {
std::array<Cell, kCellsPerPage> cells{};
Revision revision{0};
};
[[nodiscard]] static std::pair<std::int64_t, std::size_t>
split(std::int64_t coordinate)
{
constexpr auto size = static_cast<std::int64_t>(PageSize);
std::int64_t page = coordinate / size;
std::int64_t offset = coordinate % size;
if (offset < 0) {
--page;
offset += size;
}
return {page, static_cast<std::size_t>(offset)};
}
[[nodiscard]] static PageId page_of(CellAddress address)
{
return PageId{.x = split(address.x).first,
.y = split(address.y).first,
.z = split(address.z).first};
}
[[nodiscard]] static std::size_t offset_of(CellAddress address)
{
const auto [px, ox] = split(address.x);
const auto [py, oy] = split(address.y);
const auto [pz, oz] = split(address.z);
(void)px;
(void)py;
(void)pz;
return (oz * PageSize + oy) * PageSize + ox;
}
[[nodiscard]] static std::pair<PageId, std::size_t>
locate(CellAddress address)
{
return {page_of(address), offset_of(address)};
}
Limits limits_{};
Cell empty_{};
std::map<PageId, Page> pages_;
};
} // namespace Void::Containers
+3 -1
View File
@@ -253,7 +253,9 @@ namespace Void::Meta
out += "?";
}
out += '{';
bool first = true;
// Reflectable types with no members (e.g. std::optional) leave this
// unread; the diagnostic is about a deliberately empty loop body.
[[maybe_unused]] bool first = true;
template for (constexpr auto m : members_v<T>)
{
if (!first) {
+48
View File
@@ -7,6 +7,10 @@
#include <optional>
#include <utility>
#if !defined(__cpp_lib_atomic_shared_ptr)
#include <mutex>
#endif
namespace Void::Core
{
@@ -226,7 +230,51 @@ template <typename T> class Publication
private:
#if defined(__cpp_lib_atomic_shared_ptr)
std::atomic<std::shared_ptr<State>> current_;
#else
// Older libc++ (e.g. Emscripten) does not implement the
// atomic<shared_ptr> specialization. Keep the same load /
// compare-exchange surface with a mutex-protected pointer; the
// publication is still coherent for single-writer/multi-reader use.
class AtomicStatePtr
{
public:
explicit AtomicStatePtr(std::shared_ptr<State> initial)
: current_(std::move(initial))
{
}
[[nodiscard]] std::shared_ptr<State>
load(std::memory_order) const
{
std::lock_guard lock{mutex_};
return current_;
}
bool compare_exchange_weak(std::shared_ptr<State>& expected,
std::shared_ptr<State> desired,
std::memory_order,
std::memory_order)
{
std::lock_guard lock{mutex_};
if (current_ != expected) {
expected = current_;
return false;
}
current_ = std::move(desired);
return true;
}
private:
mutable std::mutex mutex_;
std::shared_ptr<State> current_;
};
AtomicStatePtr current_;
#endif
};
} // namespace Void::Core
+62
View File
@@ -5,6 +5,7 @@
#include <Void/Functional/Result.hpp>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <memory>
#include <span>
@@ -166,6 +167,48 @@ namespace Void::Crypto
const Ed25519PublicKey& public_key,
const ProviderOptions& provider = {});
/// Convenience key pair returned by ed25519_keypair(). The secret seed is
/// a move-only, self-wiping handle; prefer the typed Ed25519PrivateKey APIs
/// when the key can stay inside an owning handle.
struct Ed25519KeyPair {
Ed25519Seed secret_key;
Ed25519PublicKey public_key;
};
/// Generate a fresh Ed25519 key pair. Requires the OpenSSL backend.
[[nodiscard]] Void::Result::Result<Ed25519KeyPair>
ed25519_keypair(const ProviderOptions& provider = {});
/// Sign exact message bytes with a 32-byte Ed25519 seed/secret key. The
/// temporary private-key handle is wiped when it goes out of scope; prefer
/// sign_ed25519() when the caller already owns an Ed25519PrivateKey.
[[nodiscard]] Void::Result::Result<Ed25519Signature>
ed25519_sign(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
const ProviderOptions& provider = {});
/// Verify a detached Ed25519 signature over exact message bytes.
/// Malformed key/signature sizes are errors; a well-formed but invalid
/// signature returns false.
[[nodiscard]] Void::Result::Result<bool>
ed25519_verify(std::span<const std::byte> public_key,
std::span<const std::byte> message,
std::span<const std::byte> signature,
const ProviderOptions& provider = {});
/// Compute HMAC-SHA-1 (RFC 2104) into a caller-owned 20-byte buffer.
/// Wipes output on backend failure and rejects overlapping buffers.
[[nodiscard]] Void::Result::Result<void>
hmac_sha1_into(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
std::span<std::byte> output,
const ProviderOptions& provider = {});
[[nodiscard]] Void::Result::Result<Digest>
hmac_sha1(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
const ProviderOptions& provider = {});
/// Compute HMAC-SHA-256 into a caller-owned 32-byte buffer.
/// Wipes output on backend failure and rejects overlapping buffers.
[[nodiscard]] Void::Result::Result<void>
@@ -179,6 +222,25 @@ namespace Void::Crypto
std::span<const std::byte> message,
const ProviderOptions& provider = {});
/// Derive key material with RFC 8018 PBKDF2-HMAC-SHA-256 into a
/// caller-owned buffer. iterations must be 1..kMaxPbkdf2Iterations, salt
/// at most kMaxPbkdf2SaltBytes and output 1..kMaxPbkdf2OutputBytes.
/// Rejects overlapping buffers and wipes output on any failure after
/// validation.
[[nodiscard]] Void::Result::Result<void>
pbkdf2_hmac_sha256_into(std::span<const std::byte> password,
std::span<const std::byte> salt,
std::uint32_t iterations,
std::span<std::byte> output,
const ProviderOptions& provider = {});
[[nodiscard]] Void::Result::Result<Digest>
pbkdf2_hmac_sha256(std::span<const std::byte> password,
std::span<const std::byte> salt,
std::uint32_t iterations,
std::size_t output_length,
const ProviderOptions& provider = {});
/// Derive key material with RFC 5869 HKDF-SHA-256 into a caller-owned
/// buffer (1..CryptoLimits::kMaxHkdfOutputBytes). Rejects overlapping
/// buffers and wipes secret_output on any failure after validation.
+6 -1
View File
@@ -16,12 +16,16 @@ namespace Void::Crypto
inline constexpr std::size_t Ed25519PublicKeySize = 32;
inline constexpr std::size_t Ed25519SignatureSize = 64;
inline constexpr std::size_t Ed25519SeedSize = 32;
inline constexpr std::size_t HmacSha1Size = 20;
inline constexpr std::size_t HmacSha256Size = 32;
struct CryptoLimits {
static constexpr std::size_t kMaxOneShotMessageBytes =
16ULL * 1024ULL * 1024ULL;
static constexpr std::size_t kMaxHkdfOutputBytes = 4ULL * 1024ULL;
static constexpr std::uint32_t kMaxPbkdf2Iterations = 10'000'000U;
static constexpr std::size_t kMaxPbkdf2SaltBytes = 64ULL * 1024ULL;
static constexpr std::size_t kMaxPbkdf2OutputBytes = 1024ULL;
static constexpr std::size_t kStreamChunkBytes = 64ULL * 1024ULL;
static constexpr std::size_t kDefaultMaxConcurrentFileHashes = 8;
static constexpr std::size_t kDefaultMaxWaitingFileHashes = 32;
@@ -256,7 +260,8 @@ namespace Void::Crypto
ed25519_sign,
ed25519_verify,
hmac,
hkdf
hkdf,
pbkdf2
};
struct FaultConfig {
+60 -5
View File
@@ -347,8 +347,17 @@ namespace Void::Data::Toml
};
struct ParseOptions {
/// Maximum nesting level reached from the document root. It is
/// enforced uniformly for values (arrays, inline tables), dotted key
/// paths, table headers and array-of-tables headers.
std::size_t max_depth{64};
std::size_t max_input_bytes{16ULL * 1024ULL * 1024ULL};
/// Maximum number of document nodes (table entries, array elements
/// and array-of-tables entries plus their tables). Zero disables the
/// limit, preserving the historical behaviour. `max_input_bytes`
/// already bounds node count linearly; this knob bounds the constant
/// memory factor for untrusted input.
std::size_t max_nodes{0};
};
namespace Detail
@@ -534,7 +543,7 @@ namespace Void::Data::Toml
parse_table_header(doc);
} else {
parse_key_value_into(*current_table_, *current_meta_,
false, 0U);
false, table_depth_);
skip_ws();
skip_comment_to_eol();
if (pos_ < input_.size() && !consume_newline()) {
@@ -914,11 +923,19 @@ namespace Void::Data::Toml
return KeyPart{std::move(bare), start};
}
[[nodiscard]] std::vector<KeyPart> parse_key_path()
/// Parse a dotted key path, rejecting it as soon as it grows past
/// `max_segments`. Checking while parsing keeps a pathologically
/// long path from being materialised before the depth limit applies.
[[nodiscard]] std::vector<KeyPart>
parse_key_path(std::size_t max_segments)
{
std::vector<KeyPart> path;
path.push_back(parse_simple_key());
while (true) {
if (path.size() > max_segments) {
fail("key path exceeds max_depth",
path.back().origin);
}
skip_ws();
if (pos_ < input_.size() && input_[pos_] == '.') {
(void)advance_byte();
@@ -931,6 +948,32 @@ namespace Void::Data::Toml
return path;
}
/// A dotted key of N segments nests its value N-1 levels below the
/// current base depth, so it may hold one more segment than a table
/// header at the same limit.
[[nodiscard]] std::size_t
key_path_budget(std::size_t depth) const noexcept
{
if (depth > options_.max_depth) {
return 0;
}
const std::size_t remaining = options_.max_depth - depth;
if (remaining == std::numeric_limits<std::size_t>::max()) {
return remaining;
}
return remaining + 1U;
}
void note_node()
{
++node_count_;
if (options_.max_nodes != 0 &&
node_count_ > options_.max_nodes) {
fail(std::format("TOML document exceeds max_nodes ({})",
options_.max_nodes));
}
}
void parse_table_header(Document& doc)
{
const Origin hdr_origin = here();
@@ -941,7 +984,8 @@ namespace Void::Data::Toml
(void)advance_byte();
}
skip_ws();
auto path = parse_key_path();
auto path = parse_key_path(options_.max_depth);
table_depth_ = path.size();
skip_ws();
if (pos_ >= input_.size() || input_[pos_] != ']') {
fail("expected ']' closing table header", hdr_origin);
@@ -975,6 +1019,7 @@ namespace Void::Data::Toml
auto [mit, mok] = cur_meta->children.emplace(
seg.name, std::move(meta_ptr));
static_cast<void>(mok);
note_node();
cur_tbl = it->second.as_table();
cur_meta = mit->second.get();
} else {
@@ -1014,6 +1059,7 @@ namespace Void::Data::Toml
auto [mit, mok] = cur_meta->children.emplace(
leaf.name, std::move(meta_ptr));
static_cast<void>(mok);
note_node();
current_table_ = it->second.as_table();
current_meta_ = mit->second.get();
return;
@@ -1046,6 +1092,8 @@ namespace Void::Data::Toml
MetaNode* next_meta = meta_ptr->aot_items.back().get();
cur_meta->children.emplace(leaf.name,
std::move(meta_ptr));
note_node(); // the array-of-tables value
note_node(); // its first table
current_table_ =
&it->second.as_array_of_tables()->tables.back();
current_meta_ = next_meta;
@@ -1061,6 +1109,7 @@ namespace Void::Data::Toml
}
auto* aot = existing->as_array_of_tables();
aot->tables.push_back(Table{});
note_node();
auto elem_meta = std::make_unique<MetaNode>();
elem_meta->state = NodeState::ExplicitTable;
leaf_meta->aot_items.push_back(std::move(elem_meta));
@@ -1072,14 +1121,15 @@ namespace Void::Data::Toml
void parse_key_value_into(Table& root_tbl, MetaNode& root_meta,
bool in_inline, std::size_t depth)
{
auto path = parse_key_path();
auto path = parse_key_path(key_path_budget(depth));
const std::size_t value_depth = depth + path.size() - 1U;
skip_ws();
if (pos_ >= input_.size() || input_[pos_] != '=') {
fail("expected '=' after key");
}
(void)advance_byte();
skip_ws();
Value val = parse_value(depth);
Value val = parse_value(value_depth);
Table* cur_tbl = &root_tbl;
MetaNode* cur_meta = &root_meta;
@@ -1097,6 +1147,7 @@ namespace Void::Data::Toml
auto [mit, mok] = cur_meta->children.emplace(
seg.name, std::move(meta_ptr));
static_cast<void>(mok);
note_node();
cur_tbl = it->second.as_table();
cur_meta = mit->second.get();
} else {
@@ -1134,6 +1185,7 @@ namespace Void::Data::Toml
meta_ptr->state = val_state;
cur_meta->children.emplace(leaf.name, std::move(meta_ptr));
cur_tbl->entries.emplace(leaf.name, std::move(val));
note_node();
}
[[nodiscard]] Value parse_value(std::size_t depth)
@@ -1173,6 +1225,7 @@ namespace Void::Data::Toml
return Value{std::move(arr), start};
}
arr.elements.push_back(parse_value(depth + 1U));
note_node();
skip_ws_and_comments(true);
if (pos_ >= input_.size()) {
fail("unterminated array", start);
@@ -1681,6 +1734,8 @@ namespace Void::Data::Toml
MetaNode root_meta_{};
Table* current_table_{nullptr};
MetaNode* current_meta_{nullptr};
std::size_t table_depth_{0};
std::size_t node_count_{0};
};
inline void append_escaped_basic(std::string& out, std::string_view s)
+82
View File
@@ -0,0 +1,82 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <Void/MCP/Types.hpp>
#include <cstddef>
#include <optional>
#include <string>
#include <string_view>
namespace Void::MCP
{
/// Newline-delimited JSON-RPC framing used by the stdio transport
/// (and any custom transport built on a reliable byte stream).
///
/// A frame is one JSON-RPC message followed by `\n`; embedded newlines
/// are not allowed. A trailing `\r` is tolerated before the newline.
class LineFramer
{
public:
explicit LineFramer(McpLimits limits = {});
/// Append bytes from the stream. Fails when the unterminated
/// tail exceeds `limits.max_line_bytes`.
[[nodiscard]] Void::Result::Result<void>
append(std::string_view bytes);
/// Pop the next complete line (without the newline). Empty
/// lines are skipped. `nullopt` means more bytes are needed.
[[nodiscard]] Void::Result::Result<std::optional<std::string>>
next();
[[nodiscard]] std::size_t buffered() const noexcept;
void reset() noexcept;
private:
McpLimits m_limits;
std::string m_buffer;
};
/// One Server-Sent Events event used by Streamable HTTP responses.
struct SseEvent {
std::string event{};
std::string data{};
std::string id{};
};
/// Serialize one SSE event (`event:`/`id:`/`data:` lines terminated by
/// a blank line). Multi-line data is split into multiple `data:` lines.
[[nodiscard]] Void::Result::Result<std::string>
encode_sse_event(const SseEvent& event, const McpLimits& limits = {});
/// Bounded incremental SSE parser. Comment lines and unknown fields
/// are ignored; `data` lines are joined with `\n`.
class SseParser
{
public:
explicit SseParser(McpLimits limits = {});
[[nodiscard]] Void::Result::Result<void>
append(std::string_view bytes);
[[nodiscard]] Void::Result::Result<std::optional<SseEvent>>
next();
[[nodiscard]] std::size_t buffered() const noexcept;
void reset() noexcept;
private:
McpLimits m_limits;
std::string m_buffer;
};
/// Append the stdio frame terminator and validate the line bound.
[[nodiscard]] Void::Result::Result<std::string>
frame_line(std::string_view json, const McpLimits& limits = {});
} // namespace Void::MCP
+88
View File
@@ -0,0 +1,88 @@
#pragma once
#include <Void/Data/StrictJson.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/MCP/Types.hpp>
#include <cstdint>
#include <optional>
#include <string>
#include <string_view>
#include <variant>
namespace Void::MCP
{
using JsonValue = Void::Json::Strict::Value;
/// JSON-RPC request id: null, an integer, or a string.
struct JsonRpcId {
std::variant<std::monostate, std::int64_t, std::string> value{};
[[nodiscard]] bool is_null() const noexcept
{
return std::holds_alternative<std::monostate>(value);
}
[[nodiscard]] bool
operator==(const JsonRpcId&) const noexcept = default;
};
struct ErrorObject {
std::int32_t code{0};
std::string message{};
std::optional<JsonValue> data{};
};
struct Request {
JsonRpcId id{};
std::string method{};
std::optional<JsonValue> params{};
RequestMetadata metadata{};
};
struct Notification {
std::string method{};
std::optional<JsonValue> params{};
RequestMetadata metadata{};
};
struct Response {
JsonRpcId id{};
std::optional<JsonValue> result{};
std::optional<ErrorObject> error{};
};
using Message = std::variant<Request, Notification, Response>;
/// Encode one JSON-RPC message. Request/notification metadata is merged
/// into `params._meta`; responses carry exactly one of result or error.
[[nodiscard]] Void::Result::Result<std::string>
encode_message(const Message& message, const McpLimits& limits = {});
/// Decode exactly one JSON-RPC message, rejecting malformed envelopes,
/// duplicate keys, unknown id types, and limit violations.
[[nodiscard]] Void::Result::Result<Message>
decode_message(std::string_view text, const McpLimits& limits = {});
/// Parse `_meta` metadata out of a params object (or a `_meta` object).
[[nodiscard]] Void::Result::Result<RequestMetadata>
parse_metadata(const JsonValue& params, const McpLimits& limits = {});
/// Build the `_meta` object for a request metadata value.
[[nodiscard]] Void::Result::Result<JsonValue>
metadata_to_json(const RequestMetadata& metadata,
const McpLimits& limits = {});
[[nodiscard]] Void::Result::Result<std::string>
encode_json(const JsonValue& value, const McpLimits& limits = {});
[[nodiscard]] Void::Result::Result<JsonValue>
decode_json(std::string_view text, const McpLimits& limits = {});
/// Error response helper (null id is used for transport-level failures).
[[nodiscard]] Response
make_error_response(const JsonRpcId& id, std::int32_t code,
std::string message,
std::optional<JsonValue> data = {});
} // namespace Void::MCP
+180
View File
@@ -0,0 +1,180 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <Void/MCP/Codec.hpp>
#include <Void/MCP/Envelope.hpp>
#include <Void/MCP/Types.hpp>
#include <chrono>
#include <cstddef>
#include <functional>
#include <map>
#include <memory>
#include <optional>
#include <stop_token>
#include <string>
#include <string_view>
#include <vector>
namespace Void::MCP
{
struct HttpHeader {
std::string name{};
std::string value{};
};
struct HttpRequest {
std::string method{};
std::string target{};
std::vector<HttpHeader> headers{};
std::string body{};
};
struct HttpResponse {
int status{200};
std::vector<HttpHeader> headers{};
std::string body{};
};
/// Case-insensitive header lookup. Returns the first match.
[[nodiscard]] std::optional<std::string_view>
header_value(const HttpRequest& request, std::string_view name);
/// Authorization boundary: validate the bearer token (or any scheme the
/// application chooses) and return an authenticated principal. MCP does
/// not implement OAuth, consent, or scope mapping itself.
using AuthorizationCallback =
std::function<Void::Result::Result<AuthContext>(const HttpRequest&)>;
using RequestHandler =
std::function<Void::Result::Result<Message>(const Request&)>;
using NotificationHandler =
std::function<Void::Result::Result<void>(const Notification&)>;
struct StreamableHttpOptions {
McpLimits limits{};
/// Called for every POST before the message is dispatched.
AuthorizationCallback authorize{};
bool require_authorization{false};
/// Respond to requests with `text/event-stream` instead of a
/// single `application/json` object.
bool prefer_sse{false};
/// Protocol revisions accepted in `_meta`/headers.
std::vector<std::string> supported_versions{
std::string{kProtocolVersion}};
};
/// Streamable HTTP binding for the 2026-07-28 revision: one MCP endpoint
/// accepting POST only (GET/DELETE answer 405), protocol/method/name
/// header validation, JSON or request-scoped SSE responses, and no
/// session ids or resumability.
class StreamableHttpEndpoint
{
public:
StreamableHttpEndpoint(RequestHandler requests,
NotificationHandler notifications,
StreamableHttpOptions options = {});
~StreamableHttpEndpoint();
StreamableHttpEndpoint(const StreamableHttpEndpoint&) = delete;
StreamableHttpEndpoint&
operator=(const StreamableHttpEndpoint&) = delete;
[[nodiscard]] HttpResponse
handle(const HttpRequest& request) const;
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
};
/// Newline-delimited stdio (or any reliable bidirectional byte stream)
/// transport. Reads are bounded by `McpLimits::max_line_bytes`; writes
/// honour cancellation and a bounded timeout on non-blocking fds.
class StdioTransport
{
public:
StdioTransport(int read_fd, int write_fd,
RequestHandler requests,
NotificationHandler notifications,
McpLimits limits = {},
std::chrono::milliseconds io_timeout =
std::chrono::seconds{30});
~StdioTransport();
StdioTransport(const StdioTransport&) = delete;
StdioTransport& operator=(const StdioTransport&) = delete;
/// Read one message. `nullopt` means clean end of stream.
[[nodiscard]] Void::Result::Result<std::optional<Message>>
read_message(std::stop_token stop = {});
[[nodiscard]] Void::Result::Result<void>
write_message(const Message& message,
std::stop_token stop = {});
/// Read-dispatch-write until EOF, cancellation, or an I/O error.
/// Malformed JSON frames are answered with a parse-error
/// response and do not terminate the loop.
[[nodiscard]] Void::Result::Result<void>
run(std::stop_token stop = {});
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
};
struct LegacySession {
std::string id{};
std::string protocol_version{};
bool initialized{false};
};
struct LegacySessionOptions {
/// Revisions of the initialize/session era this adapter accepts,
/// newest first.
std::vector<std::string> supported_versions{
"2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"};
std::string server_name{"Void MCP"};
std::string server_version{"1.0"};
std::function<std::string()> session_id_factory{};
};
/// Explicit compatibility adapter for the pre-2026-07-28
/// initialization/session semantics: `initialize` negotiation,
/// `initialized` notification, and session ids. Kept separate from the
/// modern transport so the two behaviors cannot bleed into each other.
class LegacySessionAdapter
{
public:
explicit LegacySessionAdapter(LegacySessionOptions options = {});
~LegacySessionAdapter();
LegacySessionAdapter(const LegacySessionAdapter&) = delete;
LegacySessionAdapter&
operator=(const LegacySessionAdapter&) = delete;
/// Handle one inbound message. `initialize` creates a session and
/// returns the negotiated response; `initialized` marks it ready and
/// returns no reply; everything else is rejected until a session is
/// initialized.
[[nodiscard]] Void::Result::Result<std::optional<Message>>
handle(const Message& inbound,
std::string_view session_id = {});
[[nodiscard]] const LegacySession*
find(std::string_view session_id) const;
bool terminate(std::string_view session_id);
[[nodiscard]] std::size_t session_count() const;
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
};
} // namespace Void::MCP
+213
View File
@@ -0,0 +1,213 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace Void::MCP
{
/// Protocol revision this module pins its modern behavior to.
inline constexpr std::string_view kProtocolVersion{"2026-07-28"};
inline constexpr std::string_view kJsonRpcVersion{"2.0"};
/// `_meta` keys defined by the MCP 2026-07-28 revision.
inline constexpr std::string_view kMetaProtocolVersion{
"io.modelcontextprotocol/protocolVersion"};
inline constexpr std::string_view kMetaClientInfo{
"io.modelcontextprotocol/clientInfo"};
inline constexpr std::string_view kMetaClientCapabilities{
"io.modelcontextprotocol/clientCapabilities"};
inline constexpr std::string_view kMetaServerInfo{
"io.modelcontextprotocol/serverInfo"};
inline constexpr std::string_view kMetaSubscriptionId{
"io.modelcontextprotocol/subscriptionId"};
inline constexpr std::string_view kMetaProgressToken{"progressToken"};
/// Streamable HTTP request metadata headers (2026-07-28).
inline constexpr std::string_view kProtocolHeader{"MCP-Protocol-Version"};
inline constexpr std::string_view kMethodHeader{"Mcp-Method"};
inline constexpr std::string_view kNameHeader{"Mcp-Name"};
/// Legacy session/resumption headers; ignored by the modern transport.
inline constexpr std::string_view kSessionHeader{"Mcp-Session-Id"};
inline constexpr std::string_view kLastEventIdHeader{"Last-Event-ID"};
inline constexpr std::string_view kJsonContentType{"application/json"};
inline constexpr std::string_view kSseContentType{"text/event-stream"};
/// Error domain owned by the MCP module.
inline constexpr std::int32_t kMcpErrorDomain{33};
enum class McpErrorCode : std::int32_t {
none = 0,
parse_error = 1,
invalid_request = 2,
method_not_found = 3,
invalid_params = 4,
internal_error = 5,
header_mismatch = 6,
unsupported_protocol_version = 7,
unauthorized = 8,
forbidden = 9,
not_acceptable = 10,
unsupported_media_type = 11,
method_not_allowed = 12,
payload_too_large = 13,
cancelled = 14,
timeout = 15,
transport_closed = 16,
protocol_error = 17,
session_not_found = 18,
};
[[nodiscard]] inline Void::Result::Error
make_mcp_error(McpErrorCode code, std::string message)
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case McpErrorCode::none:
case McpErrorCode::internal_error:
kind = ErrorKind::internal;
break;
case McpErrorCode::parse_error:
case McpErrorCode::invalid_request:
case McpErrorCode::invalid_params:
case McpErrorCode::header_mismatch:
case McpErrorCode::protocol_error:
kind = ErrorKind::corrupt;
break;
case McpErrorCode::method_not_found:
kind = ErrorKind::not_found;
break;
case McpErrorCode::unsupported_protocol_version:
case McpErrorCode::not_acceptable:
case McpErrorCode::unsupported_media_type:
case McpErrorCode::method_not_allowed:
kind = ErrorKind::unsupported;
break;
case McpErrorCode::unauthorized:
case McpErrorCode::forbidden:
kind = ErrorKind::invalid_argument;
break;
case McpErrorCode::payload_too_large:
kind = ErrorKind::exhausted;
break;
case McpErrorCode::cancelled:
kind = ErrorKind::cancelled;
break;
case McpErrorCode::timeout:
kind = ErrorKind::timeout;
break;
case McpErrorCode::transport_closed:
case McpErrorCode::session_not_found:
kind = ErrorKind::conflict;
break;
}
return Error{kind, std::move(message),
ErrorCode{kMcpErrorDomain,
static_cast<std::int32_t>(code)}};
}
/// JSON-RPC 2.0 error code emitted for an MCP error.
[[nodiscard]] inline std::int32_t
json_rpc_error_code(McpErrorCode code) noexcept
{
switch (code) {
case McpErrorCode::parse_error:
return -32700;
case McpErrorCode::invalid_request:
return -32600;
case McpErrorCode::method_not_found:
return -32601;
case McpErrorCode::invalid_params:
return -32602;
case McpErrorCode::header_mismatch:
return -32020;
case McpErrorCode::unsupported_protocol_version:
return -32022;
case McpErrorCode::unauthorized:
return -32001;
default:
return -32603;
}
}
struct MetadataEntry {
std::string key{};
std::string value{};
[[nodiscard]] bool operator==(
const MetadataEntry&) const noexcept = default;
};
struct ClientInfo {
std::string name{};
std::string version{};
[[nodiscard]] bool operator==(
const ClientInfo&) const noexcept = default;
};
/// Per-request metadata carried inline in `_meta` (stdio) or mirrored in
/// HTTP headers (Streamable HTTP). Unknown entries are preserved as
/// bounded key/value strings.
struct RequestMetadata {
std::string protocol_version{std::string{kProtocolVersion}};
ClientInfo client_info{};
std::optional<std::string> progress_token{};
std::optional<std::string> subscription_id{};
/// Compact JSON object for `clientCapabilities` (empty when
/// absent). Kept as text so Types.hpp stays independent of Data.
std::string client_capabilities_json{};
std::vector<MetadataEntry> extra{};
[[nodiscard]] bool operator==(
const RequestMetadata&) const noexcept = default;
};
struct ServerInfo {
std::string name{};
std::string version{};
[[nodiscard]] bool operator==(
const ServerInfo&) const noexcept = default;
};
/// Authenticated principal produced by the authorization callback. The
/// MCP module only defines the boundary; token validation, scopes, and
/// consent remain application concerns.
struct AuthContext {
std::string subject{};
std::vector<std::string> scopes{};
[[nodiscard]] bool operator==(
const AuthContext&) const noexcept = default;
};
struct McpLimits {
/// Maximum bytes in one encoded JSON-RPC message.
std::size_t max_message_bytes{4ULL * 1024 * 1024};
/// Maximum bytes in one newline-delimited stdio frame.
std::size_t max_line_bytes{1ULL * 1024 * 1024};
/// Maximum metadata entries accepted from `_meta`.
std::size_t max_metadata_entries{16};
/// Maximum bytes in one metadata key or value.
std::size_t max_metadata_value_bytes{4096};
/// Maximum bytes in one SSE event.
std::size_t max_sse_event_bytes{1ULL * 1024 * 1024};
/// Maximum compiled SSE events buffered by the parser.
std::size_t max_sse_events{1024};
/// Maximum JSON nesting depth accepted by the codec.
std::size_t max_json_depth{64};
};
} // namespace Void::MCP
+11 -1
View File
@@ -31,7 +31,10 @@ namespace Void::Net
io_error = 9,
redirect_blocked = 10,
payload_too_large = 11,
headers_too_large = 12
headers_too_large = 12,
smtp_rejected = 13,
auth_failed = 14,
tls_required = 15
};
[[nodiscard]] inline Void::Result::Error
@@ -71,6 +74,13 @@ namespace Void::Net
case NetErrorCode::headers_too_large:
kind = ErrorKind::exhausted;
break;
case NetErrorCode::smtp_rejected:
case NetErrorCode::auth_failed:
kind = ErrorKind::conflict;
break;
case NetErrorCode::tls_required:
kind = ErrorKind::invalid_argument;
break;
}
return Error{kind, std::move(message),
ErrorCode{Void::Result::kNetErrorDomain,
+87
View File
@@ -13,7 +13,9 @@
#include <memory>
#include <optional>
#include <span>
#include <stop_token>
#include <string>
#include <vector>
namespace Void::Net
{
@@ -27,6 +29,10 @@ namespace Void::Net
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}};
/// Bounded per-exchange output buffer used by duplex response
/// writers. Producers block (or observe a short accepted count)
/// once this much framed data is pending.
std::size_t duplex_write_buffer_bytes{64ULL * 1024};
int listen_backlog{128};
};
@@ -64,6 +70,83 @@ namespace Void::Net
using StreamingRouteHandler =
std::function<RouteResult(const ServerRequest&, BodyReader&)>;
/// Scoped, move-only writer for a live duplex HTTP exchange.
///
/// Exactly one writer may be active at a time (`begin`, `write_some` and
/// `finish` fail with `overloaded` if another thread is inside the
/// writer). `write_some` returns how many payload bytes it accepted; the
/// writer applies bounded buffering and downstream backpressure. Fixed
/// length, chunked and bodyless responses are selected by `begin`.
///
/// After the exchange returns the writer is invalidated. A moved-from or
/// retained writer observes `valid() == false` and every operation fails
/// with `invalid_argument` instead of touching the connection.
class ResponseWriter
{
public:
struct State;
ResponseWriter() noexcept = default;
~ResponseWriter() = default;
ResponseWriter(const ResponseWriter&) = delete;
ResponseWriter& operator=(const ResponseWriter&) = delete;
ResponseWriter(ResponseWriter&&) noexcept = default;
ResponseWriter& operator=(ResponseWriter&&) noexcept = default;
[[nodiscard]] bool valid() const noexcept;
[[nodiscard]] bool begun() const noexcept;
[[nodiscard]] bool finished() const noexcept;
[[nodiscard]] bool cancelled() const noexcept;
[[nodiscard]] bool chunked() const noexcept;
[[nodiscard]] std::optional<std::uint64_t>
content_length() const noexcept;
[[nodiscard]] std::uint64_t bytes_accepted() const noexcept;
[[nodiscard]] std::uint64_t bytes_sent() const noexcept;
[[nodiscard]] std::size_t buffered_bytes() const noexcept;
/// Token cancelled by `cancel()`, peer disconnect, server shutdown
/// or the end of the exchange.
[[nodiscard]] std::stop_token stop_token() const noexcept;
void cancel() noexcept;
void set_write_timeout(std::chrono::milliseconds timeout) noexcept;
[[nodiscard]] std::chrono::milliseconds
write_timeout() const noexcept;
/// Send the response head. Chooses fixed length when a
/// `Content-Length` header is supplied, chunked otherwise (HTTP/1.1),
/// and a bodyless frame for HEAD, 1xx, 204 and 304 responses.
[[nodiscard]] Void::Result::Result<void>
begin(std::uint16_t status, std::vector<Header> headers = {});
/// Accept up to `bytes.size()` payload bytes, bounded by the
/// configured write buffer. Returns the accepted count.
[[nodiscard]] Void::Result::Result<std::size_t>
write_some(std::span<const std::byte> bytes);
/// Terminate the framed response. Fails if a fixed-length body was
/// not fully written.
[[nodiscard]] Void::Result::Result<void> finish();
private:
friend struct ResponseWriterAccess;
explicit ResponseWriter(std::shared_ptr<State> state) noexcept
: m_state{std::move(state)}
{
}
std::shared_ptr<State> m_state;
};
/// Handler for a duplex route: the request body can be read while the
/// response is produced. Returning an error before `begin` lets the server
/// emit an error response; after `begin` the stream is terminated without
/// reporting success.
using DuplexRouteHandler = std::function<Void::Result::Result<void>(
const ServerRequest&, BodyReader&, ResponseWriter&)>;
/// Concrete POSIX TCP HTTP/1.1 listener dispatching buffered routes through
/// `Void::Net::Router` and streaming routes via `BodyReader`.
class HttpServer
@@ -90,6 +173,10 @@ namespace Void::Net
add_streaming_route(Method method, std::string pattern,
StreamingRouteHandler handler);
[[nodiscard]] Void::Result::Result<void>
add_duplex_route(Method method, std::string pattern,
DuplexRouteHandler handler);
/// Register a RFC 6455 WebSocket upgrade endpoint backed by
/// `sessions` (caller must keep `sessions` alive until after
/// `shutdown()`).
+112
View File
@@ -0,0 +1,112 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <optional>
#include <stop_token>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Net
{
enum class SmtpSecurity {
/// TLS from the first byte (typically port 465).
implicit_tls,
/// Plaintext greeting/EHLO, then a required STARTTLS upgrade
/// (typically port 587 or 25).
starttls_required,
};
struct SmtpCredentials {
std::string username{};
std::string password{};
};
struct SmtpLimits {
/// Maximum raw message body accepted by `send()`.
std::uint64_t max_message_bytes{10ULL * 1024ULL * 1024ULL};
/// Maximum bytes in one complete (possibly multi-line) reply.
std::uint64_t max_response_bytes{64ULL * 1024ULL};
/// Maximum bytes in one reply line.
std::size_t max_line_bytes{4096};
/// Maximum recipients accepted by `send()`.
std::size_t max_recipients{100};
};
struct SmtpOptions {
std::string host{};
std::uint16_t port{587};
SmtpSecurity security{SmtpSecurity::starttls_required};
/// Identity verified against the server certificate; defaults
/// to `host`. Peer and hostname verification are always on.
std::string server_name{};
/// PEM trust store; empty uses the system default store.
std::string ca_file{};
/// Credentials are sent with AUTH PLAIN and only over TLS.
std::optional<SmtpCredentials> credentials{};
/// Name announced in EHLO.
std::string client_domain{"localhost"};
std::chrono::milliseconds connect_timeout{
std::chrono::seconds{10}};
std::chrono::milliseconds io_timeout{std::chrono::seconds{30}};
SmtpLimits limits{};
std::stop_token stop{};
};
struct SmtpMessage {
std::string from{};
std::vector<std::string> recipients{};
std::string data{};
};
/// Synchronous SMTP submission client over a verified TLS connection.
///
/// Supports implicit TLS and STARTTLS-required dialogue, AUTH PLAIN
/// (TLS only), MAIL/RCPT/DATA with CRLF normalization and dot-stuffing,
/// bounded replies, bounded message size, deadlines, and cancellation.
/// A failed send invalidates the client.
class SmtpClient final
{
public:
SmtpClient() noexcept;
~SmtpClient() noexcept;
SmtpClient(SmtpClient&&) noexcept;
SmtpClient& operator=(SmtpClient&&) noexcept;
SmtpClient(const SmtpClient&) = delete;
SmtpClient& operator=(const SmtpClient&) = delete;
/// Connect, greet, negotiate TLS (when required), authenticate
/// (when credentials are configured), and prepare submission.
[[nodiscard]] static Void::Result::Result<SmtpClient>
connect(SmtpOptions options);
/// Convenience: connect, send one message, then QUIT.
[[nodiscard]] static Void::Result::Result<void>
submit(SmtpOptions options, const SmtpMessage& message);
[[nodiscard]] bool valid() const noexcept;
[[nodiscard]] bool secure() const noexcept;
[[nodiscard]] Void::Result::Result<void>
send(const SmtpMessage& message);
/// Send QUIT (best effort) and close the connection.
[[nodiscard]] Void::Result::Result<void> quit();
void close() noexcept;
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
explicit SmtpClient(std::unique_ptr<Impl> impl) noexcept;
};
} // namespace Void::Net
+117
View File
@@ -0,0 +1,117 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <span>
#include <stop_token>
#include <string>
#include <string_view>
namespace Void::Net
{
/// Options for a verified TLS client stream.
///
/// Peer and hostname verification are always enabled; there is no
/// insecure mode and no fallback to plaintext when the handshake fails.
/// `server_name` is the identity checked against the peer certificate
/// (and sent as SNI when it is a DNS name); it defaults to `host`.
/// `ca_file` selects an explicit PEM trust store; when empty the system
/// default trust store is used.
struct TlsClientOptions {
std::string host{};
std::uint16_t port{443};
std::string server_name{};
std::string ca_file{};
std::chrono::milliseconds connect_timeout{
std::chrono::seconds{10}};
std::chrono::milliseconds handshake_timeout{
std::chrono::seconds{10}};
std::chrono::milliseconds io_timeout{std::chrono::seconds{30}};
std::stop_token stop{};
};
/// Synchronous TLS client stream over a TCP socket (POSIX, OpenSSL).
///
/// `connect()` establishes TCP and completes a verified TLS handshake.
/// `connect_plain()` establishes TCP only, for protocols that negotiate
/// TLS in-band (SMTP STARTTLS, IMAP STARTTLS, ...); call `start_tls()`
/// after the plaintext negotiation. A failed `start_tls()` closes the
/// stream, so a caller can never continue on an unauthenticated channel.
///
/// Reads and writes accept an optional per-operation timeout (zero uses
/// `TlsClientOptions::io_timeout`) and an optional stop token (empty uses
/// `TlsClientOptions::stop`). Timeouts and cancellation interrupt the
/// operation without closing the stream.
class TlsClientStream final
{
public:
TlsClientStream() noexcept;
~TlsClientStream() noexcept;
TlsClientStream(TlsClientStream&&) noexcept;
TlsClientStream& operator=(TlsClientStream&&) noexcept;
TlsClientStream(const TlsClientStream&) = delete;
TlsClientStream& operator=(const TlsClientStream&) = delete;
/// Resolve, connect, and complete a verified TLS handshake.
[[nodiscard]] static Void::Result::Result<TlsClientStream>
connect(TlsClientOptions options);
/// Connect TCP without starting TLS (STARTTLS plaintext phase).
[[nodiscard]] static Void::Result::Result<TlsClientStream>
connect_plain(TlsClientOptions options);
/// Take ownership of an already connected socket and start TLS
/// immediately. `native_socket` must be a connected TCP socket.
[[nodiscard]] static Void::Result::Result<TlsClientStream>
adopt(int native_socket, TlsClientOptions options);
/// Complete the verified TLS handshake on a stream created by
/// `connect_plain()` (or a plaintext `adopt()`). On failure the
/// stream is closed and `valid()` becomes false.
[[nodiscard]] Void::Result::Result<void> start_tls();
[[nodiscard]] bool valid() const noexcept;
[[nodiscard]] bool secure() const noexcept;
[[nodiscard]] int native_handle() const noexcept;
/// Read up to `destination.size()` bytes. Returns 0 on orderly EOF.
[[nodiscard]] Void::Result::Result<std::size_t>
read(std::span<std::byte> destination,
std::chrono::milliseconds timeout = {},
std::stop_token stop = {});
/// Write up to `source.size()` bytes (a positive result may be a
/// partial write).
[[nodiscard]] Void::Result::Result<std::size_t>
write(std::span<const std::byte> source,
std::chrono::milliseconds timeout = {},
std::stop_token stop = {});
/// Write every byte, retrying partial writes.
[[nodiscard]] Void::Result::Result<void>
write_all(std::span<const std::byte> source,
std::chrono::milliseconds timeout = {},
std::stop_token stop = {});
[[nodiscard]] Void::Result::Result<void>
write_all(std::string_view text,
std::chrono::milliseconds timeout = {},
std::stop_token stop = {});
/// Send TLS close_notify (best effort) and close the socket.
[[nodiscard]] Void::Result::Result<void> shutdown();
void close() noexcept;
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
explicit TlsClientStream(std::unique_ptr<Impl> impl) noexcept;
};
} // namespace Void::Net
+15 -5
View File
@@ -97,7 +97,16 @@ struct HookControl {
std::condition_variable drain_cv;
};
inline thread_local std::vector<const HookControl*> t_active_hook_controls;
// Per-thread stack of hook controls currently executing. A function-local
// thread_local keeps a single definition across TUs; a namespace-scope
// `inline thread_local` makes MinGW emit one TLS init function per TU and
// fails to link with duplicate symbols.
[[nodiscard]] inline std::vector<const HookControl*>&
active_hook_controls() noexcept
{
static thread_local std::vector<const HookControl*> controls;
return controls;
}
struct HookCallScope {
const HookControl* control{nullptr};
@@ -105,14 +114,15 @@ struct HookCallScope {
explicit HookCallScope(const HookControl* ctrl) : control(ctrl)
{
if (control != nullptr) {
t_active_hook_controls.push_back(control);
active_hook_controls().push_back(control);
}
}
~HookCallScope() noexcept
{
if (control != nullptr && !t_active_hook_controls.empty()) {
t_active_hook_controls.pop_back();
auto& controls = active_hook_controls();
if (control != nullptr && !controls.empty()) {
controls.pop_back();
}
}
@@ -121,7 +131,7 @@ struct HookCallScope {
[[nodiscard]] static bool is_active_on_thread(const HookControl* ctrl) noexcept
{
for (const auto* entry : t_active_hook_controls) {
for (const auto* entry : active_hook_controls()) {
if (entry == ctrl) {
return true;
}
+113
View File
@@ -0,0 +1,113 @@
#pragma once
#include <Void/Script/Types.hpp>
#include <expected>
#include <functional>
#include <span>
#include <string>
#include <vector>
namespace Void::Script
{
// The adapter's public interface is always declared so consumers can compile
// against it regardless of the build configuration. When Void is built without
// Lua (`VOID_SCRIPT_HAS_LUA` undefined), `LuaEvaluator::evaluate` returns a
// structured `Error` instead of running the chunk.
/// Host function: receives integer arguments, returns an integer or an error
/// message. It must not commit externally visible state itself; the evaluator
/// records each call in `Result::host_calls` so the caller can commit after a
/// successful evaluation.
using HostFunction = std::function<std::expected<Integer, std::string>(
std::span<const Integer>)>;
struct Host {
std::string name;
HostFunction function;
};
/// Standard Lua libraries the evaluator may open. Every library is opt-in
/// through this explicit allow-list; `os`, `io`, `package` and `debug` are
/// never opened, and even the base library has `load`, `loadfile`, `dofile`,
/// `collectgarbage` and `print` removed so a script cannot reach the ambient
/// filesystem, process, dynamic loader or host output.
struct Bindings {
bool base{true};
bool table{true};
bool string{true};
bool math{true};
bool coroutine{true};
[[nodiscard]] bool operator==(const Bindings&) const = default;
};
/// Returns true when evaluation must stop. It is polled from the instruction
/// hook and before every host call, so a long-running or host-heavy script is
/// interrupted cooperatively. An exception thrown by the callback is treated
/// as a cancellation request.
using CancelFunction = std::function<bool()>;
/// Complete evaluator policy. The defaults are a small, safe allow-list: no
/// host functions, no cancellation source, and only the hardened standard
/// libraries selected by `Bindings`.
struct Configuration {
Limits limits{};
Bindings bindings{};
std::vector<Host> hosts{};
CancelFunction cancelled{};
};
/// Bounded Lua text evaluator.
///
/// Each `evaluate` call creates a fresh, isolated Lua state, applies the
/// allocator, instruction, host-call and cancellation limits, exposes the
/// integer-keyed inputs as `input[key]`, registers the host functions as
/// globals, and runs the chunk with a protected call. Only integer return
/// values are accepted and collected into an owned result. On failure the
/// state is discarded, so inputs and the caller's host state are untouched; a
/// later valid evaluation starts clean.
///
/// The Lua state alone is not a security boundary: run untrusted scripts in a
/// separately isolated process. This evaluator only removes the obvious
/// ambient capabilities and enforces resource budgets.
class LuaEvaluator
{
public:
explicit LuaEvaluator(Limits limits = Limits{},
std::vector<Host> hosts = {})
: configuration_{
.limits = limits,
.bindings = Bindings{},
.hosts = std::move(hosts),
.cancelled = CancelFunction{}}
{
}
explicit LuaEvaluator(Configuration configuration)
: configuration_(std::move(configuration))
{
}
[[nodiscard]] const Limits& limits() const noexcept
{
return configuration_.limits;
}
[[nodiscard]] const Bindings& bindings() const noexcept
{
return configuration_.bindings;
}
[[nodiscard]] std::expected<Result, Error>
evaluate(std::string_view source,
std::span<const Input> inputs = {}) const;
private:
Configuration configuration_;
};
} // namespace Void::Script
+73
View File
@@ -0,0 +1,73 @@
#pragma once
#include <compare>
#include <cstddef>
#include <cstdint>
#include <string>
#include <vector>
namespace Void::Script
{
using Integer = std::int64_t;
enum class ErrorKind : std::uint8_t {
compile = 0,
runtime,
allocator_limit,
instruction_limit,
host_call_limit,
result_limit,
host_error,
invalid_input,
cancelled,
};
struct Error {
ErrorKind kind{ErrorKind::runtime};
std::string message;
[[nodiscard]] bool operator==(const Error&) const = default;
};
struct Limits {
/// Total bytes the VM may allocate (including the state and libraries).
std::size_t max_allocator_bytes{1ULL * 1024ULL * 1024ULL};
/// VM instructions before evaluation is aborted.
std::size_t max_instructions{100'000};
/// Host function invocations before evaluation is aborted.
std::size_t max_host_calls{1'000};
/// Maximum number of integer results collected.
std::size_t max_result_integers{1'024};
/// Maximum number of integer-keyed inputs.
std::size_t max_inputs{256};
};
/// Integer-keyed input exposed to the script as `input[key]`.
struct Input {
Integer key{0};
Integer value{0};
[[nodiscard]] bool operator==(const Input&) const = default;
};
/// One host function call observed during a successful evaluation. The caller
/// may commit these effects after `evaluate` returns; the evaluator itself
/// never commits host state.
struct HostInvocation {
std::string host;
std::vector<Integer> arguments;
Integer result{0};
[[nodiscard]] bool operator==(const HostInvocation&) const = default;
};
/// Owned result of a successful evaluation.
struct Result {
/// Integer values returned by the chunk, in order.
std::vector<Integer> integers;
/// Host calls made by the script, in order.
std::vector<HostInvocation> host_calls;
};
} // namespace Void::Script
+6
View File
@@ -140,6 +140,12 @@ namespace Void::Sqlite
}
return Void::Result::fail(std::move(c).error());
}
} else if (tx->state() != TransactionState::Committed) {
// SQLite may end the transaction on its own (FULL, interrupt,
// IO error). Never report the callback's success as durable.
return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::misuse,
"AsyncPool: transaction ended before commit (automatically rolled back)"));
}
return res;
},
+12 -8
View File
@@ -181,7 +181,8 @@ namespace Void::Sqlite
};
/// RAII transaction retaining shared ConnectionState. Never marks Committed
/// before COMMIT succeeds; inspects sqlite3_get_autocommit on error.
/// before COMMIT succeeds; inspects sqlite3_get_autocommit on error and after
/// statements so an automatic rollback is reported as RolledBack.
class Transaction
{
public:
@@ -192,11 +193,11 @@ namespace Void::Sqlite
Transaction(const Transaction&) = delete;
Transaction& operator=(const Transaction&) = delete;
[[nodiscard]] TransactionState state() const noexcept { return m_state; }
[[nodiscard]] bool is_active() const noexcept
{
return m_state == TransactionState::Active;
}
/// Observes the native autocommit state; returns RolledBack when SQLite
/// already ended this transaction (for example SQLITE_FULL or an
/// interrupt inside the transaction).
[[nodiscard]] TransactionState state() const noexcept;
[[nodiscard]] bool is_active() const noexcept;
Result<void> commit();
[[nodiscard]] Result<void> rollback_checked();
@@ -204,10 +205,13 @@ namespace Void::Sqlite
private:
friend class Database;
explicit Transaction(std::shared_ptr<detail::ConnectionState> conn) noexcept;
explicit Transaction(std::shared_ptr<detail::ConnectionState> conn,
std::uint64_t id) noexcept;
void refresh_state() const noexcept;
std::shared_ptr<detail::ConnectionState> m_conn{};
TransactionState m_state{TransactionState::RolledBack};
std::uint64_t m_id{0};
mutable TransactionState m_state{TransactionState::RolledBack};
};
/// Separately owned nested savepoint scope.
+12
View File
@@ -177,6 +177,8 @@ namespace Void::Sqlite
std::size_t max_cached_statements{64};
std::size_t max_cache_bytes{8ULL * 1024ULL * 1024ULL};
std::chrono::milliseconds busy_timeout{5000};
/// WAL thresholds are measured in un-checkpointed frames (converted to
/// bytes with the database page size), not the raw on-disk WAL size.
std::uint64_t wal_checkpoint_threshold_bytes{16ULL * 1024ULL * 1024ULL};
std::uint64_t wal_warn_threshold_bytes{64ULL * 1024ULL * 1024ULL};
std::uint64_t wal_stop_writes_threshold_bytes{256ULL * 1024ULL * 1024ULL};
@@ -335,6 +337,8 @@ namespace Void::Sqlite
struct CheckpointReport {
int log_frames{0};
int checkpointed_frames{0};
/// Frames written to the WAL but not yet copied back into the database.
int uncheckpointed_frames{0};
bool busy{false};
std::uint64_t wal_size_bytes{0};
};
@@ -364,6 +368,14 @@ namespace Void::Sqlite
bool active_transaction{false};
std::size_t open_savepoints{0};
std::uint64_t wal_size_bytes{0};
/// Whether the frame counts below were obtained from the WAL index. When
/// false, `wal_uncheckpointed_bytes` is a conservative upper bound (the
/// on-disk WAL size) and the frame counts are zero.
bool wal_frames_known{false};
int wal_log_frames{0};
int wal_checkpointed_frames{0};
int wal_uncheckpointed_frames{0};
std::uint64_t wal_uncheckpointed_bytes{0};
bool wal_checkpoint_recommended{false};
bool wal_warn_exceeded{false};
bool wal_write_admission_blocked{false};
+410
View File
@@ -0,0 +1,410 @@
#pragma once
#include <Void/System/Types.hpp>
#include <chrono>
#include <cstdint>
#include <expected>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <mmsystem.h>
#include <windows.h>
#endif
namespace Void::System
{
using PcmSample = std::int16_t;
struct PcmFormat {
std::uint32_t sample_rate{44100};
std::uint16_t channels{2};
[[nodiscard]] bool operator==(const PcmFormat&) const noexcept = default;
};
/// Owned PCM sample data. The device keeps it alive for as long as a voice
/// references it; callers may release their handle right after submission.
struct PcmBuffer {
PcmFormat format;
std::vector<PcmSample> samples;
[[nodiscard]] std::chrono::microseconds duration() const noexcept
{
const std::uint64_t frames =
format.channels == 0
? 0
: samples.size() / format.channels;
if (format.sample_rate == 0) {
return std::chrono::microseconds{0};
}
return std::chrono::microseconds{
static_cast<std::int64_t>(frames) * 1'000'000 /
format.sample_rate};
}
};
enum class AudioStatus : std::uint8_t {
ok = 0,
/// No output device is available; the caller can continue silently.
device_unavailable,
voice_limit,
invalid_buffer,
backend_error,
closed,
};
struct AudioError {
AudioStatus status{AudioStatus::backend_error};
std::string message;
[[nodiscard]] bool operator==(const AudioError&) const = default;
};
enum class VoiceState : std::uint8_t {
playing = 0,
stopped,
finished,
unknown,
};
using VoiceId = std::uint64_t;
struct AudioLimits {
std::size_t max_voices{8};
};
/// Bounded PCM playback with owned samples and explicit voice lifetimes.
///
/// `play` transfers a shared handle to the device; the caller may drop its
/// handle immediately and the samples stay alive until the voice is stopped,
/// finishes or the device closes. `stop` ends a voice (including a loop),
/// `state` reports and reaps finished voices, and the destructor tears every
/// voice down. A missing device is reported as `device_unavailable` so an
/// application can continue without audio; `open_silent` provides the same
/// lifetime semantics without a device (used for tests and headless runs).
///
/// Thread-safe.
class AudioDevice
{
public:
static std::expected<AudioDevice, AudioError>
open(AudioLimits limits = {})
{
auto impl = std::make_unique<Impl>();
impl->limits = limits;
#ifdef _WIN32
impl->silent = false;
#else
impl->silent = true;
#endif
return AudioDevice{std::move(impl)};
}
static std::expected<AudioDevice, AudioError>
open_silent(AudioLimits limits = {})
{
auto impl = std::make_unique<Impl>();
impl->limits = limits;
impl->silent = true;
return AudioDevice{std::move(impl)};
}
AudioDevice(AudioDevice&&) noexcept = default;
AudioDevice& operator=(AudioDevice&&) noexcept = default;
AudioDevice(const AudioDevice&) = delete;
AudioDevice& operator=(const AudioDevice&) = delete;
~AudioDevice() { close(); }
[[nodiscard]] bool available() const
{
std::lock_guard lock{impl_->mutex};
return !impl_->closed && impl_->available;
}
/// Submit owned samples. On success the device owns a reference; on
/// failure the caller's handle is untouched.
[[nodiscard]] std::expected<VoiceId, AudioError>
play(std::shared_ptr<const PcmBuffer> buffer, bool loop = false)
{
Impl& impl = *impl_;
std::lock_guard lock{impl.mutex};
reap(impl);
if (impl.closed) {
return std::unexpected{
AudioError{AudioStatus::closed, "audio device is closed"}};
}
if (!impl.available) {
return std::unexpected{AudioError{
AudioStatus::device_unavailable,
"no audio output device"}};
}
if (buffer == nullptr || buffer->format.channels == 0 ||
buffer->samples.empty()) {
return std::unexpected{AudioError{
AudioStatus::invalid_buffer, "empty PCM buffer"}};
}
if (impl.voices.size() >= impl.limits.max_voices) {
return std::unexpected{AudioError{
AudioStatus::voice_limit, "voice limit reached"}};
}
Voice voice;
voice.id = impl.next_id++;
voice.buffer = std::move(buffer);
voice.loop = loop;
voice.state = VoiceState::playing;
voice.started = std::chrono::steady_clock::now();
#ifdef _WIN32
if (!impl.silent) {
if (const auto error = start_win32(voice); !error.has_value()) {
return std::unexpected{error.error()};
}
}
#endif
const VoiceId id = voice.id;
impl.voices.emplace(id, std::move(voice));
return id;
}
/// Stop a voice (including a loop) and release its samples.
bool stop(VoiceId id)
{
Impl& impl = *impl_;
std::lock_guard lock{impl.mutex};
const auto found = impl.voices.find(id);
if (found == impl.voices.end()) {
return false;
}
found->second.state = VoiceState::stopped;
release(impl, found->second);
impl.voices.erase(found);
return true;
}
/// Current state; finished voices are reaped and their samples
/// released.
[[nodiscard]] VoiceState state(VoiceId id)
{
Impl& impl = *impl_;
std::lock_guard lock{impl.mutex};
const auto found = impl.voices.find(id);
if (found == impl.voices.end()) {
return VoiceState::unknown;
}
Voice& voice = found->second;
#ifdef _WIN32
if (!impl.silent) {
service_win32(voice);
}
#endif
if (voice.state == VoiceState::playing && !voice.loop &&
std::chrono::steady_clock::now() - voice.started >=
voice.buffer->duration()) {
voice.state = VoiceState::finished;
}
const VoiceState result = voice.state;
if (result == VoiceState::finished ||
result == VoiceState::stopped) {
release(impl, voice);
impl.voices.erase(found);
}
return result;
}
[[nodiscard]] std::size_t active_voices()
{
Impl& impl = *impl_;
std::lock_guard lock{impl.mutex};
reap(impl);
return impl.voices.size();
}
void close()
{
if (impl_ == nullptr) {
return;
}
Impl& impl = *impl_;
std::lock_guard lock{impl.mutex};
for (auto& [id, voice] : impl.voices) {
(void)id;
stop_backend(voice);
voice.buffer.reset();
}
impl.voices.clear();
impl.closed = true;
}
private:
struct Voice {
VoiceId id{0};
std::shared_ptr<const PcmBuffer> buffer;
bool loop{false};
VoiceState state{VoiceState::playing};
std::chrono::steady_clock::time_point started{};
#ifdef _WIN32
HWAVEOUT wave{};
WAVEHDR header{};
WAVEFORMATEX format{};
std::vector<PcmSample> playback;
bool prepared{false};
#endif
};
struct Impl {
mutable std::mutex mutex;
AudioLimits limits{};
std::unordered_map<VoiceId, Voice> voices;
VoiceId next_id{1};
bool silent{true};
bool available{true};
bool closed{false};
};
explicit AudioDevice(std::unique_ptr<Impl> impl)
: impl_(std::move(impl))
{
}
static void release(Impl& impl, Voice& voice)
{
(void)impl;
#ifdef _WIN32
stop_backend(voice);
#endif
voice.buffer.reset();
}
/// Reap voices that finished. Silent non-loop voices finish after
/// their duration; looping voices stay until stopped.
static void reap(Impl& impl)
{
const auto now = std::chrono::steady_clock::now();
for (auto iterator = impl.voices.begin();
iterator != impl.voices.end();) {
Voice& voice = iterator->second;
#ifdef _WIN32
if (!impl.silent) {
service_win32(voice);
}
#endif
if (voice.state == VoiceState::playing && !voice.loop &&
now - voice.started >= voice.buffer->duration()) {
voice.state = VoiceState::finished;
}
if (voice.state == VoiceState::finished ||
voice.state == VoiceState::stopped) {
release(impl, voice);
iterator = impl.voices.erase(iterator);
} else {
++iterator;
}
}
}
#ifdef _WIN32
static std::expected<void, AudioError> start_win32(Voice& voice)
{
voice.format.wFormatTag = WAVE_FORMAT_PCM;
voice.format.nChannels =
static_cast<WORD>(voice.buffer->format.channels);
voice.format.nSamplesPerSec =
static_cast<DWORD>(voice.buffer->format.sample_rate);
voice.format.wBitsPerSample = 16;
voice.format.nBlockAlign =
static_cast<WORD>(voice.format.nChannels * 2);
voice.format.nAvgBytesPerSec =
voice.format.nSamplesPerSec * voice.format.nBlockAlign;
voice.format.cbSize = 0;
const MMRESULT opened = ::waveOutOpen(
&voice.wave, WAVE_MAPPER, &voice.format, 0, 0,
CALLBACK_NULL);
if (opened != MMSYSERR_NOERROR) {
voice.wave = nullptr;
return std::unexpected{AudioError{
AudioStatus::device_unavailable,
"waveOutOpen failed"}};
}
voice.header = WAVEHDR{};
// waveOut only reads the samples, but WAVEHDR exposes a mutable
// buffer; keep an owned mutable copy instead of casting away
// constness of the shared buffer.
voice.playback = voice.buffer->samples;
voice.header.lpData =
reinterpret_cast<LPSTR>(voice.playback.data());
voice.header.dwBufferLength = static_cast<DWORD>(
voice.playback.size() * sizeof(PcmSample));
if (::waveOutPrepareHeader(voice.wave, &voice.header,
sizeof(WAVEHDR)) !=
MMSYSERR_NOERROR) {
::waveOutClose(voice.wave);
voice.wave = nullptr;
return std::unexpected{AudioError{
AudioStatus::backend_error,
"waveOutPrepareHeader failed"}};
}
voice.prepared = true;
if (::waveOutWrite(voice.wave, &voice.header, sizeof(WAVEHDR)) !=
MMSYSERR_NOERROR) {
stop_backend(voice);
return std::unexpected{AudioError{
AudioStatus::backend_error, "waveOutWrite failed"}};
}
return {};
}
static void service_win32(Voice& voice)
{
if (voice.wave == nullptr ||
(voice.header.dwFlags & WHDR_DONE) == 0) {
return;
}
if (voice.loop) {
// Re-queue the same prepared header for another pass.
voice.header.dwFlags &= ~WHDR_DONE;
(void)::waveOutWrite(voice.wave, &voice.header,
sizeof(WAVEHDR));
} else {
voice.state = VoiceState::finished;
}
}
static void stop_backend(Voice& voice)
{
if (voice.wave != nullptr) {
(void)::waveOutReset(voice.wave);
if (voice.prepared) {
(void)::waveOutUnprepareHeader(
voice.wave, &voice.header, sizeof(WAVEHDR));
voice.prepared = false;
}
(void)::waveOutClose(voice.wave);
voice.wave = nullptr;
}
}
#else
static void stop_backend(Voice&) {}
#endif
std::unique_ptr<Impl> impl_;
};
} // namespace Void::System
+6 -10
View File
@@ -209,22 +209,18 @@ private:
[[nodiscard]] inline std::string win32_message(DWORD error)
{
char* buffer = nullptr;
std::array<char, 512> buffer{};
const DWORD length = ::FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
error,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
reinterpret_cast<char*>(&buffer),
0,
buffer.data(),
static_cast<DWORD>(buffer.size()),
nullptr);
std::string message = (length != 0 && buffer != nullptr)
? std::string{buffer, length}
std::string message = length != 0
? std::string{buffer.data(), length}
: std::string{"unknown error"};
if (buffer != nullptr) {
::LocalFree(buffer);
}
while (!message.empty() &&
(message.back() == '\n' || message.back() == '\r' ||
message.back() == ' ' || message.back() == '.')) {
+177 -1
View File
@@ -4,20 +4,36 @@
#include <Void/Functional/Result.hpp>
#include <Void/System/Types.hpp>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <filesystem>
#include <functional>
#include <optional>
#include <span>
#include <stop_token>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#ifdef _WIN32
#include <memory>
#endif
namespace Void::Process
{
#ifdef _WIN32
namespace Detail
{
/// Opaque owner of the native Windows process, job and pipe state. Defined by
/// the System module implementation; it is never an integer descriptor.
struct WindowsProcess;
struct ChildAccess;
} // namespace Detail
#endif
inline constexpr std::size_t kMaxSpawnInputBytes = 256ULL * 1024ULL;
inline constexpr std::size_t kDefaultMaxStdoutBytes = 1024ULL * 1024ULL;
inline constexpr std::size_t kDefaultMaxStderrBytes = 1024ULL * 1024ULL;
@@ -98,7 +114,7 @@ struct CommunicateResult {
class Child
{
public:
Child() noexcept = default;
Child() noexcept;
Child(long long pid,
long long pgid,
bool owns_process_group,
@@ -155,12 +171,172 @@ private:
Void::System::OwnedFd stderr_{};
std::chrono::milliseconds kill_grace_{std::chrono::milliseconds{2000}};
#ifdef _WIN32
std::unique_ptr<Detail::WindowsProcess> windows_;
friend struct Detail::ChildAccess;
friend class BinarySession;
#endif
void reset_and_reap() noexcept;
};
[[nodiscard]] Void::Result::Result<Child, Void::Result::Error>
spawn(const SpawnOptions& options);
inline constexpr std::size_t kDefaultBinaryOutputBufferBytes = 1024ULL * 1024ULL;
/// Why a BinarySession operation stopped before completing.
enum class BinaryFailureCode : std::int32_t {
none = 0,
timeout = 1,
cancelled = 2,
truncated = 3,
closed = 4,
buffer_full = 5,
io_error = 6,
};
/// Successful (possibly partial) BinarySession operation.
struct BinaryTransfer {
std::size_t bytes{0};
bool eof{false}; ///< the stream reached end-of-file
bool exited{false}; ///< the child exit status is known (see status)
bool truncated{false}; ///< output was discarded because a buffer was full
ExitStatus status{};
};
/// Structured BinarySession failure. `bytes_transferred` lets callers resume
/// from the exact offset that was not transferred.
struct BinaryError {
std::size_t bytes_transferred{0};
bool eof{false};
BinaryFailureCode failure{BinaryFailureCode::io_error};
Void::Result::Error error{};
};
struct BinarySessionOptions {
std::size_t max_stdout_buffer{kDefaultBinaryOutputBufferBytes};
std::size_t max_stderr_buffer{kDefaultBinaryOutputBufferBytes};
/// When true, output beyond a buffer cap is drained and discarded (marked
/// truncated) instead of applying backpressure to the child.
bool truncate_output_on_overflow{false};
};
/// Incremental binary I/O session over a spawned child's pipes.
///
/// Each call drives both output directions: while stdout is being read,
/// stderr is drained into its bounded buffer (and vice versa), so a child
/// flooding one stream cannot block the other as long as buffering allows.
/// Pipes are non-blocking; operations are poll-driven and bounded by an
/// optional timeout and a stop token (or cancel()).
class BinarySession
{
public:
BinarySession() noexcept = default;
explicit BinarySession(Child child, BinarySessionOptions options = {});
~BinarySession() noexcept;
BinarySession(const BinarySession&) = delete;
BinarySession& operator=(const BinarySession&) = delete;
BinarySession(BinarySession&& other) noexcept;
BinarySession& operator=(BinarySession&& other) noexcept;
[[nodiscard]] static Void::Result::Result<BinarySession, Void::Result::Error>
spawn(const SpawnOptions& options, BinarySessionOptions session_options = {});
[[nodiscard]] bool valid() const noexcept;
[[nodiscard]] Child& child() noexcept { return child_; }
[[nodiscard]] const Child& child() const noexcept { return child_; }
[[nodiscard]] long long pid() const noexcept { return child_.pid(); }
/// Writes as much of `data` as the child accepts. Returns the transferred
/// count; on timeout/cancellation/closure the BinaryError reports it.
[[nodiscard]] Void::Result::Result<BinaryTransfer, BinaryError> write_stdin(
std::span<const std::byte> data,
std::chrono::milliseconds timeout = std::chrono::milliseconds{0},
std::stop_token stop = {});
[[nodiscard]] Void::Result::Result<BinaryTransfer, BinaryError> read_stdout(
std::span<std::byte> out,
std::chrono::milliseconds timeout = std::chrono::milliseconds{0},
std::stop_token stop = {});
[[nodiscard]] Void::Result::Result<BinaryTransfer, BinaryError> read_stderr(
std::span<std::byte> out,
std::chrono::milliseconds timeout = std::chrono::milliseconds{0},
std::stop_token stop = {});
/// Closes the child's stdin (flush-free half-close). Idempotent.
[[nodiscard]] Void::Result::Result<void, Void::Result::Error> close_stdin();
/// Waits for the child while continuing to drain both output streams.
[[nodiscard]] Void::Result::Result<ExitStatus, Void::Result::Error> wait(
std::chrono::milliseconds timeout = std::chrono::milliseconds{0},
std::stop_token stop = {});
/// Terminates the child (and its process group) with the configured grace.
[[nodiscard]] Void::Result::Result<ExitStatus, Void::Result::Error> terminate(
std::chrono::milliseconds grace = std::chrono::milliseconds{-1});
/// Requests cancellation of the next/current operation. Safe to call from
/// another thread.
void cancel() noexcept { cancelled_.store(true, std::memory_order_release); }
[[nodiscard]] bool cancelled() const noexcept
{
return cancelled_.load(std::memory_order_acquire);
}
[[nodiscard]] bool stdout_eof() const noexcept { return stdout_eof_; }
[[nodiscard]] bool stderr_eof() const noexcept { return stderr_eof_; }
[[nodiscard]] bool stdout_truncated() const noexcept { return stdout_truncated_; }
[[nodiscard]] bool stderr_truncated() const noexcept { return stderr_truncated_; }
[[nodiscard]] std::size_t buffered_stdout() const noexcept
{
return stdout_buffer_.size() - stdout_offset_;
}
[[nodiscard]] std::size_t buffered_stderr() const noexcept
{
return stderr_buffer_.size() - stderr_offset_;
}
private:
struct PollFill {
bool stdin_broken{false};
bool idle{false};
BinaryFailureCode failure{BinaryFailureCode::none};
Void::Result::Error error{};
};
[[nodiscard]] PollFill poll_fill(int timeout_ms,
std::span<const std::byte> stdin_data,
std::size_t& stdin_written,
bool discard_on_full);
[[nodiscard]] Void::Result::Result<BinaryTransfer, BinaryError> read_stream(
bool is_stdout,
std::span<std::byte> out,
std::chrono::milliseconds timeout,
std::stop_token stop);
void note_exit() noexcept;
Child child_{};
Void::System::OwnedFd stdin_{};
Void::System::OwnedFd stdout_{};
Void::System::OwnedFd stderr_{};
std::vector<std::byte> stdout_buffer_{};
std::size_t stdout_offset_{0};
std::vector<std::byte> stderr_buffer_{};
std::size_t stderr_offset_{0};
bool stdout_eof_{true};
bool stderr_eof_{true};
bool stdin_closed_{true};
bool stdout_truncated_{false};
bool stderr_truncated_{false};
BinarySessionOptions options_{};
std::atomic<bool> cancelled_{false};
ExitStatus status_{};
bool reaped_{false};
};
[[nodiscard]] Void::Result::Result<CommunicateResult, Void::Result::Error>
communicate_blocking(Child& child,
std::string_view stdin_data = {},
+140
View File
@@ -0,0 +1,140 @@
#pragma once
#include <chrono>
#include <concepts>
#include <condition_variable>
#include <cstddef>
#include <functional>
#include <mutex>
#include <type_traits>
#include <utility>
namespace Void::Testing
{
/// Small synchronization gate for deterministic completion-order tests.
///
/// Participants call `arrive()` after a computation returned and can then
/// block in `wait_release()`. The test thread can wait for a number of
/// arrivals (`wait_for`) and release blocked participants explicitly, on
/// failure, or after a timeout. All waits are bounded.
class CompletionGate
{
public:
using Clock = std::chrono::steady_clock;
CompletionGate() = default;
CompletionGate(const CompletionGate&) = delete;
CompletionGate& operator=(const CompletionGate&) = delete;
/// Record one completed invocation and wake `wait_for` waiters.
void arrive() noexcept
{
std::lock_guard lock{mutex_};
++arrivals_;
condition_.notify_all();
}
[[nodiscard]] std::size_t arrivals() const noexcept
{
std::lock_guard lock{mutex_};
return arrivals_;
}
/// Wait until at least `count` invocations arrived. Returns false on
/// timeout.
[[nodiscard]] bool wait_for(std::size_t count,
std::chrono::milliseconds timeout)
{
std::unique_lock lock{mutex_};
return condition_.wait_for(
lock, timeout, [&] { return arrivals_ >= count; });
}
/// Unblock every current and future `wait_release` caller.
void release() noexcept
{
std::lock_guard lock{mutex_};
released_ = true;
condition_.notify_all();
}
[[nodiscard]] bool released() const noexcept
{
std::lock_guard lock{mutex_};
return released_;
}
/// Block until `release()`; returns false on timeout so a failing test
/// can still finish.
[[nodiscard]] bool wait_release(std::chrono::milliseconds timeout)
{
std::unique_lock lock{mutex_};
return condition_.wait_for(lock, timeout,
[&] { return released_; });
}
private:
mutable std::mutex mutex_;
std::condition_variable condition_;
std::size_t arrivals_{0};
bool released_{false};
};
/// Callable adapter that runs an observer exactly once after a successful
/// invocation returns, and before the enclosing future is fulfilled.
///
/// The observer is *not* called when the callable throws; the exception is
/// forwarded unchanged. Void, value, reference and move-only results are
/// preserved. The observer itself must not throw; an exception from it
/// propagates instead of the result.
template <typename Fn, typename Observer> class ObservedCallable
{
public:
template <typename F, typename O>
ObservedCallable(F&& fn, O&& observer)
: fn_(std::forward<F>(fn))
, observer_(std::forward<O>(observer))
{
}
template <typename... Args>
requires std::invocable<Fn&, Args...>
decltype(auto) operator()(Args&&... args)
{
using Result = std::invoke_result_t<Fn&, Args...>;
if constexpr (std::is_void_v<Result>) {
std::invoke(fn_, std::forward<Args>(args)...);
std::invoke(observer_);
return;
} else if constexpr (std::is_reference_v<Result>) {
Result result =
std::invoke(fn_, std::forward<Args>(args)...);
std::invoke(observer_);
return std::forward<Result>(result);
} else {
Result result =
std::invoke(fn_, std::forward<Args>(args)...);
std::invoke(observer_);
return result;
}
}
private:
Fn fn_;
Observer observer_;
};
template <typename Fn, typename Observer>
[[nodiscard]] auto observe_completion(Fn&& fn, Observer&& observer)
{
return ObservedCallable<std::decay_t<Fn>, std::decay_t<Observer>>(
std::forward<Fn>(fn), std::forward<Observer>(observer));
}
} // namespace Void::Testing
+3
View File
@@ -60,6 +60,9 @@ namespace Void::Testing
std::vector<std::string> tags;
bool assertions_truncated{false};
std::size_t dropped_assertions{0};
// Counted at record time, so failures beyond the bounded assertion
// retention still determine the test outcome.
std::size_t failed_assertions{0};
std::size_t diagnostic_bytes{0};
std::string cleanup_error;
};
+17 -5
View File
@@ -1,7 +1,6 @@
#pragma once
#include <Void/Core/Meta.hpp>
#include <Void/Testing/Annotations.hpp>
#include <Void/Testing/Config.hpp>
#include <Void/Testing/Detail/Registry.hpp>
#include <Void/Testing/Test.hpp>
@@ -11,6 +10,7 @@
#if __has_include(<meta>)
#include <meta>
#include <Void/Testing/Annotations.hpp>
#define VOID_TESTING_HAS_REFLECTION 1
#endif
@@ -95,6 +95,13 @@ namespace Void::Testing
}
}
/// Non-capturing thunk: a template argument is a constant
/// expression, unlike a reflected member captured by a lambda.
template <meta::info M> static void run_method_thunk()
{
run_method<M>();
}
static std::string suite_label()
{
if constexpr (constexpr auto n =
@@ -138,12 +145,17 @@ namespace Void::Testing
skip_reason = std::string{s->reason.view()};
}
constexpr auto name = meta::identifier_of(m);
constexpr const char* file = loc.file_name();
constexpr int line =
static_cast<int>(loc.line());
constexpr auto run = &run_method_thunk<m>;
reg.add(TestCase{
.run = [] { run_method<m>(); },
.name = std::string{meta::identifier_of(m)},
.run = run,
.name = std::string{name},
.suite = suite,
.file = loc.file_name(),
.line = static_cast<int>(loc.line()),
.file = file,
.line = line,
.disabled = disabled,
.skip_reason = std::move(skip_reason),
.tags = std::move(tags),
+5
View File
@@ -1,6 +1,7 @@
#pragma once
#include <Void/TestingMock/Matcher.hpp>
#include <Void/TestingMock/MoveOnlyFunction.hpp>
#include <Void/TestingMock/Session.hpp>
#include <concepts>
@@ -30,7 +31,11 @@ namespace Void::TestingMock::Detail
std::tuple<MatcherHolder<std::decay_t<Args>>...>;
/// Move-only function — supports unique_ptr-capturing lambdas,
/// move-only arguments, and move-only return values.
#if defined(__cpp_lib_move_only_function)
using Action = std::move_only_function<R(Args...)>;
#else
using Action = MoveOnlyFunction<R(Args...)>;
#endif
Expectation(MatcherTuple matchers, std::source_location loc)
: m_matchers(std::move(matchers)), m_location(loc)
@@ -0,0 +1,73 @@
#pragma once
#include <concepts>
#include <cstddef>
#include <functional>
#include <memory>
#include <type_traits>
#include <utility>
namespace Void::TestingMock::Detail
{
/// Minimal move-only type-erased callable with the subset of
/// std::move_only_function used by TestingMock. Only needed on standard
/// libraries that do not implement std::move_only_function (older libc++,
/// e.g. Emscripten).
template <typename Signature> class MoveOnlyFunction;
template <typename R, typename... Args>
class MoveOnlyFunction<R(Args...)>
{
private:
struct Base {
virtual ~Base() = default;
virtual R invoke(Args&&... args) = 0;
};
template <typename F> struct Model final : Base {
explicit Model(F callable) : fn(std::move(callable)) {}
R invoke(Args&&... args) override
{
return std::invoke(fn, std::forward<Args>(args)...);
}
F fn;
};
public:
MoveOnlyFunction() noexcept = default;
MoveOnlyFunction(std::nullptr_t) noexcept {}
template <typename F>
requires std::invocable<F&, Args...> &&
(!std::same_as<std::remove_cvref_t<F>,
MoveOnlyFunction>)
MoveOnlyFunction(F&& callable)
: impl_(std::make_unique<Model<std::remove_cvref_t<F>>>(
std::forward<F>(callable)))
{
}
MoveOnlyFunction(MoveOnlyFunction&&) noexcept = default;
MoveOnlyFunction& operator=(MoveOnlyFunction&&) noexcept = default;
MoveOnlyFunction(const MoveOnlyFunction&) = delete;
MoveOnlyFunction& operator=(const MoveOnlyFunction&) = delete;
[[nodiscard]] explicit operator bool() const noexcept
{
return impl_ != nullptr;
}
R operator()(Args... args)
{
return impl_->invoke(std::forward<Args>(args)...);
}
private:
std::unique_ptr<Base> impl_;
};
} // namespace Void::TestingMock::Detail
+310
View File
@@ -0,0 +1,310 @@
#pragma once
#include <Void/Text/Bounded.hpp>
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Encoding::Base32
{
namespace Detail
{
/// RFC 4648 section 6 alphabet.
constexpr std::string_view alphabet =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
/// Crockford alphabet: no I, L, O or U.
constexpr std::string_view alphabet_crockford =
"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
constexpr char to_lower_ascii(char c) noexcept
{
return (c >= 'A' && c <= 'Z') ? static_cast<char>(c + ('a' - 'A')) : c;
}
[[nodiscard]] constexpr std::array<std::int8_t, 256>
make_rfc_table() noexcept
{
std::array<std::int8_t, 256> t{};
t.fill(-1);
for (std::size_t i = 0; i < 32; ++i) {
const char upper = alphabet[i];
t[static_cast<unsigned char>(upper)] =
static_cast<std::int8_t>(i);
t[static_cast<unsigned char>(to_lower_ascii(upper))] =
static_cast<std::int8_t>(i);
}
return t;
}
[[nodiscard]] constexpr std::array<std::int8_t, 256>
make_crockford_table() noexcept
{
std::array<std::int8_t, 256> t{};
t.fill(-1);
for (std::size_t i = 0; i < 32; ++i) {
const char upper = alphabet_crockford[i];
t[static_cast<unsigned char>(upper)] =
static_cast<std::int8_t>(i);
t[static_cast<unsigned char>(to_lower_ascii(upper))] =
static_cast<std::int8_t>(i);
}
// Crockford aliases: I and L are 1, O is 0.
for (const char c : {'I', 'i', 'L', 'l'}) {
t[static_cast<unsigned char>(c)] = 1;
}
for (const char c : {'O', 'o'}) {
t[static_cast<unsigned char>(c)] = 0;
}
// U is deliberately absent (rejected).
return t;
}
/// Overwrite partial output before discarding it so a failed decode
/// does not leave decoded plaintext behind in freed storage.
inline void wipe(std::string& out) noexcept
{
std::fill(out.begin(), out.end(), '\0');
out.clear();
}
inline std::string encode_with(std::span<const std::byte> data,
std::string_view alpha,
bool pad)
{
std::string out;
out.reserve(((data.size() + 4) / 5) * 8);
std::uint32_t buffer = 0;
int bits = 0;
for (const std::byte raw : data) {
buffer = (buffer << 8) |
static_cast<std::uint32_t>(
static_cast<std::uint8_t>(raw));
bits += 8;
while (bits >= 5) {
bits -= 5;
out += alpha[(buffer >> bits) & 0x1FU];
}
buffer &= bits == 0 ? 0U : ((1U << bits) - 1U);
}
if (bits != 0) {
out += alpha[(buffer << (5 - bits)) & 0x1FU];
}
if (pad) {
while (out.size() % 8 != 0) {
out += '=';
}
}
return out;
}
inline std::optional<std::string>
decode_with(std::string_view s,
const std::array<std::int8_t, 256>& table,
bool allow_padding,
bool skip_separators,
Void::Text::TextLimits limits)
{
if (s.size() > limits.max_input) {
return std::nullopt;
}
std::string out;
out.reserve((s.size() * 5) / 8);
std::uint32_t buffer = 0;
int bits = 0;
std::size_t symbols = 0;
std::size_t padding = 0;
bool saw_padding = false;
for (const char encoded : s) {
const auto character = static_cast<unsigned char>(encoded);
if (skip_separators && encoded == '-') {
continue;
}
if (allow_padding && encoded == '=') {
saw_padding = true;
++padding;
continue;
}
if (saw_padding) {
wipe(out);
return std::nullopt;
}
const std::int8_t value = table[character];
if (value < 0) {
wipe(out);
return std::nullopt;
}
buffer = (buffer << 5) | static_cast<std::uint32_t>(value);
bits += 5;
++symbols;
if (bits >= 8) {
bits -= 8;
out += static_cast<char>((buffer >> bits) & 0xFFU);
if (out.size() > limits.max_output) {
wipe(out);
return std::nullopt;
}
buffer &= bits == 0 ? 0U : ((1U << bits) - 1U);
}
}
const std::size_t remainder = symbols % 8;
if (remainder == 1 || remainder == 3 || remainder == 6) {
wipe(out);
return std::nullopt;
}
const std::size_t expected_padding =
remainder == 0 ? 0 : 8 - remainder;
if (padding != 0 && padding != expected_padding) {
wipe(out);
return std::nullopt;
}
// Non-zero trailing pad bits mean the text is not canonical.
if (bits != 0 && buffer != 0) {
wipe(out);
return std::nullopt;
}
return out;
}
} // namespace Detail
/// Encode bytes to RFC 4648 Base32 (uppercase, with padding).
[[nodiscard]] inline std::string encode(std::span<const std::byte> data)
{
return Detail::encode_with(data, Detail::alphabet, true);
}
/// Encode bytes to RFC 4648 Base32 with an explicit padding choice.
[[nodiscard]] inline std::string encode(std::span<const std::byte> data,
bool pad)
{
return Detail::encode_with(data, Detail::alphabet, pad);
}
/// Encode an unsigned-byte view without forcing callers to reinterpret
/// their binary buffers as text.
[[nodiscard]] inline std::string encode(std::span<const std::uint8_t> data)
{
return encode(std::as_bytes(data));
}
/// Encode a string_view to RFC 4648 Base32.
[[nodiscard]] inline std::string encode(std::string_view s)
{
return encode(std::as_bytes(std::span{s.data(), s.size()}));
}
/// Decode RFC 4648 Base32. Accepts padded or unpadded text and is
/// case-insensitive. Returns nullopt for invalid characters, impossible
/// lengths, malformed padding, non-zero trailing bits, or limits exceeded.
[[nodiscard]] inline std::optional<std::string>
decode(std::string_view s, Void::Text::TextLimits limits = {})
{
static constexpr auto table = Detail::make_rfc_table();
return Detail::decode_with(
s, table, /*allow_padding=*/true, /*skip_separators=*/false, limits);
}
/// Decode RFC 4648 Base32 into an explicitly binary buffer.
[[nodiscard]] inline std::optional<std::vector<std::byte>>
decode_bytes(std::string_view s, Void::Text::TextLimits limits = {})
{
const auto decoded = decode(s, limits);
if (!decoded) {
return std::nullopt;
}
const auto bytes =
std::as_bytes(std::span{decoded->data(), decoded->size()});
return std::vector<std::byte>{bytes.begin(), bytes.end()};
}
/// Encode bytes to Crockford Base32 (uppercase, no padding).
[[nodiscard]] inline std::string
encode_crockford(std::span<const std::byte> data)
{
return Detail::encode_with(data, Detail::alphabet_crockford, false);
}
[[nodiscard]] inline std::string
encode_crockford(std::span<const std::uint8_t> data)
{
return encode_crockford(std::as_bytes(data));
}
[[nodiscard]] inline std::string encode_crockford(std::string_view s)
{
return encode_crockford(std::as_bytes(std::span{s.data(), s.size()}));
}
/// Decode Crockford Base32. Case-insensitive; I/L map to 1, O maps to 0,
/// U is rejected, and '-' separators are skipped. Returns nullopt on
/// invalid input, impossible lengths, non-zero trailing bits, or limits
/// exceeded.
[[nodiscard]] inline std::optional<std::string>
decode_crockford(std::string_view s, Void::Text::TextLimits limits = {})
{
static constexpr auto table = Detail::make_crockford_table();
return Detail::decode_with(
s, table, /*allow_padding=*/false, /*skip_separators=*/true, limits);
}
/// Decode Crockford Base32 into an explicitly binary buffer.
[[nodiscard]] inline std::optional<std::vector<std::byte>>
decode_crockford_bytes(std::string_view s,
Void::Text::TextLimits limits = {})
{
const auto decoded = decode_crockford(s, limits);
if (!decoded) {
return std::nullopt;
}
const auto bytes =
std::as_bytes(std::span{decoded->data(), decoded->size()});
return std::vector<std::byte>{bytes.begin(), bytes.end()};
}
} // namespace Void::Encoding::Base32
namespace Void::Text
{
/// Encode bytes as uppercase RFC 4648 Base32. Padding is emitted by
/// default and can be disabled for unpadded forms.
[[nodiscard]] inline std::string
base32_encode(std::span<const std::byte> data, bool pad = true)
{
return Void::Encoding::Base32::encode(data, pad);
}
/// Decode RFC 4648 Base32 text. Case-insensitive, accepts padded or
/// unpadded input, and rejects invalid characters, impossible lengths,
/// malformed padding and non-zero trailing bits by returning nullopt.
[[nodiscard]] inline std::optional<std::string>
base32_decode(std::string_view text, TextLimits limits = {})
{
return Void::Encoding::Base32::decode(text, limits);
}
/// Decode a byte view as RFC 4648 Base32 text.
[[nodiscard]] inline std::optional<std::string>
base32_decode(std::span<const std::byte> text, TextLimits limits = {})
{
return base32_decode(
std::string_view{reinterpret_cast<const char*>(text.data()),
text.size()},
limits);
}
} // namespace Void::Text
+271 -69
View File
@@ -2,10 +2,15 @@
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <functional>
#include <limits>
#include <span>
#include <stdexcept>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace Void::Diff
@@ -21,73 +26,226 @@ struct Edit {
T value;
};
// ── Bounded diff controls ─────────────────────────────────────────────────────
struct DiffLimits
{
// Maximum number of elements across both inputs (a.size() + b.size()).
std::size_t max_input_elements = std::numeric_limits<std::size_t>::max();
// Maximum number of input bytes for line_diff_bounded.
std::size_t max_input_bytes = std::numeric_limits<std::size_t>::max();
// Maximum bytes retained by the Myers trace (backtracking snapshots).
std::size_t max_trace_memory = std::numeric_limits<std::size_t>::max();
// Maximum number of edits in the produced script.
std::size_t max_output = std::numeric_limits<std::size_t>::max();
// Maximum work units (diagonal steps plus snake comparisons).
std::size_t max_work = std::numeric_limits<std::size_t>::max();
};
enum class DiffFailure : std::uint8_t
{
InputTooLarge,
TraceMemoryExhausted,
OutputTooLarge,
WorkExhausted,
Cancelled,
};
namespace Detail
{
// A cancellation checkpoint is any callable returning bool. An empty
// std::function (the default) means "never cancelled".
template <typename Cancel>
[[nodiscard]] inline bool cancellation_requested(const Cancel& cancel)
{
if constexpr (requires { static_cast<bool>(cancel); }) {
if (!static_cast<bool>(cancel)) return false;
}
return static_cast<bool>(cancel());
}
} // namespace Detail
// ── Myers diff ────────────────────────────────────────────────────────────────
// Returns the shortest edit script (SES) to transform `a` into `b`.
// Uses Myers' O(ND) algorithm.
// Uses Myers' O(ND) algorithm, with checked size arithmetic and optional
// input/trace/output/work budgets plus cancellation checkpoints.
template <typename T, typename Eq = std::equal_to<T>,
typename Cancel = std::function<bool()>>
[[nodiscard]] std::expected<std::vector<Edit<T>>, DiffFailure>
diff_bounded(std::span<const T> a, std::span<const T> b,
DiffLimits limits = {}, Eq eq = {}, Cancel&& cancelled = {})
{
using Diff = std::ptrdiff_t;
constexpr Diff kMaxDiff = std::numeric_limits<Diff>::max();
const std::size_t n_size = a.size();
const std::size_t m_size = b.size();
if (n_size > limits.max_input_elements ||
m_size > limits.max_input_elements ||
n_size > limits.max_input_elements - m_size) {
return std::unexpected{DiffFailure::InputTooLarge};
}
const std::size_t max_diff_size = static_cast<std::size_t>(kMaxDiff);
if (n_size > max_diff_size || m_size > max_diff_size ||
n_size > max_diff_size - m_size) {
return std::unexpected{DiffFailure::InputTooLarge};
}
const Diff n = static_cast<Diff>(n_size);
const Diff m = static_cast<Diff>(m_size);
const Diff max_d = n + m;
if (max_d == 0) return std::vector<Edit<T>>{};
// Unsigned index math keeps max_d + k from overflowing signed ptrdiff_t.
const auto index = [max_d](Diff k) {
return static_cast<std::size_t>(max_d) + static_cast<std::size_t>(k);
};
const std::size_t v_size = static_cast<std::size_t>(max_d) * 2 + 1;
if (v_size > limits.max_trace_memory / sizeof(Diff)) {
return std::unexpected{DiffFailure::TraceMemoryExhausted};
}
const std::size_t snapshot_bytes = v_size * sizeof(Diff);
// v[k + max_d] = furthest-reaching x in diagonal k
std::vector<Diff> v(v_size, -1);
// trace[d] = snapshot of v at step d (for backtracking)
std::vector<std::vector<Diff>> trace;
std::size_t trace_bytes = 0;
std::size_t work = 0;
const auto spend = [&]() -> bool {
if (work >= limits.max_work) return false;
++work;
return true;
};
v[index(1)] = 0;
bool done = false;
Diff final_d = 0;
for (Diff d = 0; d <= max_d && !done; ++d) {
if (Detail::cancellation_requested(cancelled))
return std::unexpected{DiffFailure::Cancelled};
if (snapshot_bytes > limits.max_trace_memory - trace_bytes)
return std::unexpected{DiffFailure::TraceMemoryExhausted};
trace.push_back(v);
trace_bytes += snapshot_bytes;
for (Diff k = -d; k <= d; k += 2) {
if (!spend()) return std::unexpected{DiffFailure::WorkExhausted};
if (Detail::cancellation_requested(cancelled))
return std::unexpected{DiffFailure::Cancelled};
Diff x;
if (k == -d || (k != d && v[index(k - 1)] < v[index(k + 1)]))
x = v[index(k + 1)];
else
x = v[index(k - 1)] + 1;
Diff y = x - k;
while (x < n && y < m && eq(a[static_cast<std::size_t>(x)],
b[static_cast<std::size_t>(y)])) {
if (!spend()) return std::unexpected{DiffFailure::WorkExhausted};
if (Detail::cancellation_requested(cancelled))
return std::unexpected{DiffFailure::Cancelled};
++x;
++y;
}
v[index(k)] = x;
if (x == n && y == m) {
final_d = d;
done = true;
break;
}
}
}
if (!done) return std::unexpected{DiffFailure::WorkExhausted};
// Backtrack to reconstruct the edit script.
std::vector<Edit<T>> script;
const auto push = [&](Op op, const T& value) -> bool {
if (script.size() >= limits.max_output) return false;
script.push_back(Edit<T>{op, value});
return true;
};
Diff x = n;
Diff y = m;
for (Diff d = final_d; d > 0; --d) {
if (!spend()) return std::unexpected{DiffFailure::WorkExhausted};
if (Detail::cancellation_requested(cancelled))
return std::unexpected{DiffFailure::Cancelled};
const auto& pv = trace[static_cast<std::size_t>(d)];
const Diff k = x - y;
Diff prev_k;
if (k == -d || (k != d && pv[index(k - 1)] < pv[index(k + 1)]))
prev_k = k + 1;
else
prev_k = k - 1;
const Diff prev_x = pv[index(prev_k)];
const Diff prev_y = prev_x - prev_k;
// snake (equal)
while (x > prev_x && y > prev_y) {
if (!spend()) return std::unexpected{DiffFailure::WorkExhausted};
if (Detail::cancellation_requested(cancelled))
return std::unexpected{DiffFailure::Cancelled};
--x;
--y;
if (!push(Op::Equal, a[static_cast<std::size_t>(x)]))
return std::unexpected{DiffFailure::OutputTooLarge};
}
if (d > 0) {
if (x == prev_x) {
--y;
if (!push(Op::Insert, b[static_cast<std::size_t>(y)]))
return std::unexpected{DiffFailure::OutputTooLarge};
} else {
--x;
if (!push(Op::Delete, a[static_cast<std::size_t>(x)]))
return std::unexpected{DiffFailure::OutputTooLarge};
}
}
x = prev_x;
y = prev_y;
}
// Remaining snake at start
while (x > 0 && y > 0) {
if (!spend()) return std::unexpected{DiffFailure::WorkExhausted};
--x;
--y;
if (!push(Op::Equal, a[static_cast<std::size_t>(x)]))
return std::unexpected{DiffFailure::OutputTooLarge};
}
std::reverse(script.begin(), script.end());
return script;
}
// Convenience overload for vectors
template <typename T, typename Eq = std::equal_to<T>,
typename Cancel = std::function<bool()>>
[[nodiscard]] std::expected<std::vector<Edit<T>>, DiffFailure>
diff_bounded(const std::vector<T>& a, const std::vector<T>& b,
DiffLimits limits = {}, Eq eq = {}, Cancel&& cancelled = {})
{
return diff_bounded<T, Eq>(std::span<const T>{a}, std::span<const T>{b},
limits, eq, std::forward<Cancel>(cancelled));
}
// Unbounded compatibility API. Default limits are effectively unlimited, so
// existing callers keep their behaviour.
template <typename T, typename Eq = std::equal_to<T>>
[[nodiscard]] std::vector<Edit<T>>
diff(std::span<const T> a, std::span<const T> b, Eq eq = {})
{
const int n = static_cast<int>(a.size());
const int m = static_cast<int>(b.size());
const int max_d = n + m;
if (max_d == 0) return {};
// v[k + max_d] = furthest-reaching x in diagonal k
std::vector<int> v(2 * max_d + 1, -1);
// trace[d] = snapshot of v at step d (for backtracking)
std::vector<std::vector<int>> trace;
v[max_d + 1] = 0;
bool done = false;
int final_d = 0;
for (int d = 0; d <= max_d && !done; ++d) {
trace.push_back(v);
for (int k = -d; k <= d; k += 2) {
int x;
if (k == -d || (k != d && v[max_d + k - 1] < v[max_d + k + 1]))
x = v[max_d + k + 1];
else
x = v[max_d + k - 1] + 1;
int y = x - k;
while (x < n && y < m && eq(a[x], b[y])) { ++x; ++y; }
v[max_d + k] = x;
if (x == n && y == m) { final_d = d; done = true; break; }
}
}
// Backtrack to reconstruct the edit script
std::vector<Edit<T>> script;
int x = n, y = m;
for (int d = final_d; d > 0; --d) {
const auto& pv = trace[d];
const int k = x - y;
int prev_k;
if (k == -d || (k != d && pv[max_d + k - 1] < pv[max_d + k + 1]))
prev_k = k + 1;
else
prev_k = k - 1;
const int prev_x = pv[max_d + prev_k];
const int prev_y = prev_x - prev_k;
// snake (equal)
while (x > prev_x && y > prev_y) {
--x; --y;
script.push_back({Op::Equal, a[x]});
}
if (d > 0) {
if (x == prev_x) { --y; script.push_back({Op::Insert, b[y]}); }
else { --x; script.push_back({Op::Delete, a[x]}); }
}
x = prev_x; y = prev_y;
}
// Remaining snake at start
while (x > 0 && y > 0) { --x; --y; script.push_back({Op::Equal, a[x]}); }
std::reverse(script.begin(), script.end());
return script;
auto result = diff_bounded<T, Eq>(a, b, {}, eq);
if (!result) throw std::length_error("Void::Diff: diff input too large");
return *std::move(result);
}
// Convenience overload for vectors
@@ -104,22 +262,66 @@ diff(const std::vector<T>& a, const std::vector<T>& b, Eq eq = {})
using LineDiff = Edit<std::string>;
[[nodiscard]] inline std::vector<LineDiff>
line_diff(std::string_view a, std::string_view b)
namespace Detail
{
auto split = [](std::string_view s) {
std::vector<std::string> lines;
[[nodiscard]] inline std::expected<std::vector<std::string_view>, DiffFailure>
split_lines_bounded(std::string_view input, const DiffLimits& limits,
std::size_t& line_count)
{
std::vector<std::string_view> lines;
std::size_t pos = 0;
while (pos <= s.size()) {
const auto nl = s.find('\n', pos);
lines.emplace_back(s.substr(pos, nl == std::string_view::npos ? nl : nl - pos));
while (pos <= input.size()) {
if (line_count >= limits.max_input_elements) {
return std::unexpected{DiffFailure::InputTooLarge};
}
++line_count;
const std::size_t nl = input.find('\n', pos);
lines.emplace_back(
input.substr(pos, nl == std::string_view::npos ? nl : nl - pos));
if (nl == std::string_view::npos) break;
pos = nl + 1;
}
return lines;
};
}
} // namespace Detail
return diff(split(a), split(b));
template <typename Cancel = std::function<bool()>>
[[nodiscard]] inline std::expected<std::vector<LineDiff>, DiffFailure>
line_diff_bounded(std::string_view a, std::string_view b,
DiffLimits limits = {}, Cancel&& cancelled = {})
{
if (a.size() > limits.max_input_bytes ||
b.size() > limits.max_input_bytes ||
a.size() > limits.max_input_bytes - b.size()) {
return std::unexpected{DiffFailure::InputTooLarge};
}
std::size_t line_count = 0;
auto a_lines = Detail::split_lines_bounded(a, limits, line_count);
if (!a_lines) return std::unexpected{a_lines.error()};
auto b_lines = Detail::split_lines_bounded(b, limits, line_count);
if (!b_lines) return std::unexpected{b_lines.error()};
auto edits = diff_bounded(std::span<const std::string_view>{*a_lines},
std::span<const std::string_view>{*b_lines},
limits, std::equal_to<>{},
std::forward<Cancel>(cancelled));
if (!edits) return std::unexpected{edits.error()};
std::vector<LineDiff> lines;
lines.reserve(edits->size());
for (const auto& edit : *edits) {
lines.push_back(LineDiff{edit.op, std::string{edit.value}});
}
return lines;
}
[[nodiscard]] inline std::vector<LineDiff>
line_diff(std::string_view a, std::string_view b)
{
auto result = line_diff_bounded(a, b);
if (!result) throw std::length_error("Void::Diff: line diff input too large");
return *std::move(result);
}
// ── helpers ───────────────────────────────────────────────────────────────────
+482
View File
@@ -0,0 +1,482 @@
#pragma once
// Portable Ed25519 built on the module's own SHA-512 implementation.
//
// The field arithmetic follows the compact public-domain approach used by
// TweetNaCl: elements of GF(2^255-19) are 16 signed limbs of 16 bits and the
// group law is evaluated in extended coordinates. Secret scalars and the
// hash-derived key material are wiped before returning.
#include "BuiltinHash.hpp"
#include <Void/Crypto/Crypto.hpp>
#include <Void/Crypto/Types.hpp>
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <initializer_list>
#include <span>
namespace Void::Crypto::Detail::Ed25519
{
using U8 = std::uint8_t;
using I64 = std::int64_t;
using Gf = std::array<I64, 16>;
using Point = std::array<Gf, 4>;
using Sha512 = std::array<U8, 64>;
inline constexpr Gf gf0{};
inline constexpr Gf gf1{1};
// Curve constants in 16-bit limbs (GF(2^255-19)).
inline constexpr Gf D{
0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070,
0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203};
inline constexpr Gf D2{
0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0,
0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406};
inline constexpr Gf I{
0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43,
0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83};
inline constexpr Gf base_x{
0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c,
0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169};
inline constexpr Gf base_y{
0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666,
0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666};
// Group order L = 2^252 + 27742317777372353535851937790883648493.
inline constexpr std::array<I64, 32> L{
0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7,
0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0x10};
inline void wipe(std::span<U8> bytes) noexcept
{
builtin_secure_wipe(std::span<std::byte>{
reinterpret_cast<std::byte*>(bytes.data()), bytes.size()});
}
inline void hash_sha512(std::initializer_list<std::span<const U8>> parts,
Sha512& out)
{
BuiltinHasher hasher;
if (!hasher.init(HashAlgorithm::Sha512)) {
out.fill(0);
return;
}
for (const auto part : parts) {
hasher.update(std::span<const std::byte>{
reinterpret_cast<const std::byte*>(part.data()), part.size()});
}
const Digest digest = hasher.finalize();
const std::size_t count = std::min<std::size_t>(digest.size(), out.size());
std::memcpy(out.data(), digest.data(), count);
if (count < out.size()) {
std::fill(out.begin() + static_cast<std::ptrdiff_t>(count), out.end(), 0);
}
}
[[nodiscard]] inline int verify_32(const U8* a, const U8* b) noexcept
{
unsigned int diff = 0;
for (int i = 0; i < 32; ++i) {
diff |= static_cast<unsigned int>(a[i] ^ b[i]);
}
return static_cast<int>((1 & ((diff - 1) >> 8)) - 1);
}
inline void set25519(Gf& r, const Gf& a) noexcept
{
r = a;
}
inline void car25519(Gf& o) noexcept
{
for (int i = 0; i < 16; ++i) {
o[i] += I64{1} << 16;
const I64 c = o[i] >> 16;
o[(i + 1) * (i < 15)] += c - 1 + 37 * (c - 1) * (i == 15);
o[i] -= c << 16;
}
}
inline void sel25519(Gf& p, Gf& q, int b) noexcept
{
const I64 c = ~(static_cast<I64>(b) - 1);
for (int i = 0; i < 16; ++i) {
const I64 t = c & (p[i] ^ q[i]);
p[i] ^= t;
q[i] ^= t;
}
}
inline void pack25519(U8* o, const Gf& n) noexcept
{
Gf m{};
Gf t = n;
car25519(t);
car25519(t);
car25519(t);
for (int j = 0; j < 2; ++j) {
m[0] = t[0] - 0xffed;
for (int i = 1; i < 15; ++i) {
m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);
m[i - 1] &= 0xffff;
}
m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);
const int b = static_cast<int>((m[15] >> 16) & 1);
m[14] &= 0xffff;
sel25519(t, m, 1 - b);
}
for (int i = 0; i < 16; ++i) {
o[2 * i] = static_cast<U8>(t[i] & 0xff);
o[2 * i + 1] = static_cast<U8>(t[i] >> 8);
}
}
[[nodiscard]] inline int neq25519(const Gf& a, const Gf& b) noexcept
{
std::array<U8, 32> c{};
std::array<U8, 32> d{};
pack25519(c.data(), a);
pack25519(d.data(), b);
return verify_32(c.data(), d.data());
}
[[nodiscard]] inline U8 par25519(const Gf& a) noexcept
{
std::array<U8, 32> d{};
pack25519(d.data(), a);
return d[0] & 1;
}
inline void unpack25519(Gf& o, const U8* n) noexcept
{
for (int i = 0; i < 16; ++i) {
o[i] = n[2 * i] + (static_cast<I64>(n[2 * i + 1]) << 8);
}
o[15] &= 0x7fff;
}
inline void add(Gf& o, const Gf& a, const Gf& b) noexcept
{
for (int i = 0; i < 16; ++i) {
o[i] = a[i] + b[i];
}
}
inline void sub(Gf& o, const Gf& a, const Gf& b) noexcept
{
for (int i = 0; i < 16; ++i) {
o[i] = a[i] - b[i];
}
}
inline void mul(Gf& o, const Gf& a, const Gf& b) noexcept
{
std::array<I64, 31> t{};
for (int i = 0; i < 16; ++i) {
for (int j = 0; j < 16; ++j) {
t[i + j] += a[i] * b[j];
}
}
for (int i = 0; i < 15; ++i) {
t[i] += 38 * t[i + 16];
}
for (int i = 0; i < 16; ++i) {
o[i] = t[i];
}
car25519(o);
car25519(o);
}
inline void square(Gf& o, const Gf& a) noexcept
{
mul(o, a, a);
}
inline void invert(Gf& o, const Gf& in) noexcept
{
Gf c = in;
for (int a = 253; a >= 0; --a) {
square(c, c);
if (a != 2 && a != 4) {
mul(c, c, in);
}
}
o = c;
}
inline void pow2523(Gf& o, const Gf& in) noexcept
{
Gf c = in;
for (int a = 250; a >= 0; --a) {
square(c, c);
if (a != 1) {
mul(c, c, in);
}
}
o = c;
}
inline void point_add(Point& p, const Point& q) noexcept
{
Gf a{};
Gf b{};
Gf c{};
Gf d{};
Gf e{};
Gf f{};
Gf g{};
Gf h{};
Gf t{};
sub(a, p[1], p[0]);
sub(t, q[1], q[0]);
mul(a, a, t);
add(b, p[0], p[1]);
add(t, q[0], q[1]);
mul(b, b, t);
mul(c, p[3], q[3]);
mul(c, c, D2);
mul(d, p[2], q[2]);
add(d, d, d);
sub(e, b, a);
sub(f, d, c);
add(g, d, c);
add(h, b, a);
mul(p[0], e, f);
mul(p[1], h, g);
mul(p[2], g, f);
mul(p[3], e, h);
}
inline void point_cswap(Point& p, Point& q, int b) noexcept
{
for (int i = 0; i < 4; ++i) {
sel25519(p[i], q[i], b);
}
}
inline void point_pack(U8* r, const Point& p) noexcept
{
Gf tx{};
Gf ty{};
Gf zi{};
invert(zi, p[2]);
mul(tx, p[0], zi);
mul(ty, p[1], zi);
pack25519(r, ty);
r[31] ^= static_cast<U8>(par25519(tx) << 7);
}
inline void scalarmult(Point& p, Point& q, const U8* s) noexcept
{
p[0].fill(0);
p[1].fill(0);
p[2].fill(0);
p[3].fill(0);
p[1][0] = 1;
p[2][0] = 1;
for (int i = 255; i >= 0; --i) {
const int b = (s[i / 8] >> (i & 7)) & 1;
point_cswap(p, q, b);
point_add(q, p);
point_add(p, p);
point_cswap(p, q, b);
}
}
inline void scalarbase(Point& p, const U8* s) noexcept
{
Point q{};
set25519(q[0], base_x);
set25519(q[1], base_y);
set25519(q[2], gf1);
mul(q[3], base_x, base_y);
scalarmult(p, q, s);
}
inline int unpackneg(Point& r, const U8* p) noexcept
{
Gf t{};
Gf chk{};
Gf num{};
Gf den{};
Gf den2{};
Gf den4{};
Gf den6{};
set25519(r[2], gf1);
unpack25519(r[1], p);
square(num, r[1]);
mul(den, num, D);
sub(num, num, r[2]);
add(den, r[2], den);
square(den2, den);
square(den4, den2);
mul(den6, den4, den2);
mul(t, den6, num);
mul(t, t, den);
pow2523(t, t);
mul(t, t, num);
mul(t, t, den);
mul(t, t, den);
mul(r[0], t, den);
square(chk, r[0]);
mul(chk, chk, den);
if (neq25519(chk, num) != 0) {
mul(r[0], r[0], I);
}
square(chk, r[0]);
mul(chk, chk, den);
if (neq25519(chk, num) != 0) {
return -1;
}
if (par25519(r[0]) == (p[31] >> 7)) {
sub(r[0], gf0, r[0]);
}
mul(r[3], r[0], r[1]);
return 0;
}
inline void modL(U8* r, std::array<I64, 64>& x) noexcept
{
I64 carry = 0;
int i = 0;
int j = 0;
for (i = 63; i >= 32; --i) {
carry = 0;
for (j = i - 32; j < i - 12; ++j) {
x[j] += carry - 16 * x[i] * L[j - (i - 32)];
carry = (x[j] + 128) >> 8;
x[j] -= carry << 8;
}
x[j] += carry;
x[i] = 0;
}
carry = 0;
for (j = 0; j < 32; ++j) {
x[j] += carry - (x[31] >> 4) * L[j];
carry = x[j] >> 8;
x[j] &= 255;
}
for (j = 0; j < 32; ++j) {
x[j] -= carry * L[j];
}
for (i = 0; i < 32; ++i) {
x[i + 1] += x[i] >> 8;
r[i] = static_cast<U8>(x[i] & 255);
}
}
inline void reduce(U8* r) noexcept
{
std::array<I64, 64> x{};
for (int i = 0; i < 64; ++i) {
x[i] = r[i];
}
std::fill(r, r + 64, U8{0});
modL(r, x);
}
/// Derive the public key and the clamped secret scalar from a 32-byte seed.
inline void expand_seed(const U8* seed, Sha512& digest, U8* public_key) noexcept
{
hash_sha512({std::span<const U8>{seed, 32}}, digest);
digest[0] &= 248;
digest[31] &= 127;
digest[31] |= 64;
Point p{};
scalarbase(p, digest.data());
if (public_key != nullptr) {
point_pack(public_key, p);
}
}
inline void sign(const U8* seed, const U8* public_key,
std::span<const std::byte> message, U8* signature) noexcept
{
Sha512 digest{};
Sha512 nonce{};
Sha512 challenge{};
Point p{};
expand_seed(seed, digest, nullptr);
const auto message_bytes = std::span<const U8>{
reinterpret_cast<const U8*>(message.data()), message.size()};
hash_sha512({std::span<const U8>{digest.data() + 32, 32}, message_bytes},
nonce);
reduce(nonce.data());
scalarbase(p, nonce.data());
point_pack(signature, p);
hash_sha512({std::span<const U8>{signature, 32},
std::span<const U8>{public_key, 32}, message_bytes},
challenge);
reduce(challenge.data());
std::array<I64, 64> x{};
for (int i = 0; i < 32; ++i) {
x[i] = nonce[i];
}
for (int i = 0; i < 32; ++i) {
for (int j = 0; j < 32; ++j) {
x[i + j] += static_cast<I64>(challenge[i]) * digest[j];
}
}
modL(signature + 32, x);
wipe(digest);
wipe(nonce);
wipe(challenge);
}
[[nodiscard]] inline bool verify(const U8* public_key, const U8* signature,
std::span<const std::byte> message) noexcept
{
// Reject a non-canonical scalar S >= L (and the top three bits, which
// must be clear because L < 2^253).
if ((signature[63] & 224) != 0) {
return false;
}
std::array<U8, 64> s_wide{};
std::memcpy(s_wide.data(), signature + 32, 32);
reduce(s_wide.data());
if (verify_32(s_wide.data(), signature + 32) != 0) {
return false;
}
Point q{};
Point p{};
if (unpackneg(q, public_key) != 0) {
return false;
}
Sha512 challenge{};
hash_sha512({std::span<const U8>{signature, 32},
std::span<const U8>{public_key, 32},
std::span<const U8>{
reinterpret_cast<const U8*>(message.data()),
message.size()}},
challenge);
reduce(challenge.data());
scalarmult(p, q, challenge.data());
scalarbase(q, signature + 32);
point_add(p, q);
std::array<U8, 32> check{};
point_pack(check.data(), p);
const bool ok = verify_32(signature, check.data()) == 0;
wipe(challenge);
return ok;
}
} // namespace Void::Crypto::Detail::Ed25519
+131
View File
@@ -789,6 +789,46 @@ namespace Void::Crypto::Detail
return out;
}
void builtin_hmac_sha1(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
std::span<std::byte> output_20) noexcept
{
std::array<std::byte, 64> key_block{};
if (secret_key.size() > 64) {
Sha1State kh;
kh.update(secret_key);
kh.finalize_into(std::span{key_block}.subspan(0, 20));
} else if (!secret_key.empty()) {
std::memcpy(key_block.data(), secret_key.data(), secret_key.size());
}
std::array<std::byte, 64> ipad{};
std::array<std::byte, 64> opad{};
for (std::size_t i = 0; i < 64; ++i) {
ipad[i] = key_block[i] ^ std::byte{0x36};
opad[i] = key_block[i] ^ std::byte{0x5C};
}
std::array<std::byte, 20> inner_hash{};
{
Sha1State inner;
inner.update(ipad);
inner.update(message);
inner.finalize_into(inner_hash);
}
{
Sha1State outer;
outer.update(opad);
outer.update(inner_hash);
outer.finalize_into(output_20);
}
builtin_secure_wipe(key_block);
builtin_secure_wipe(ipad);
builtin_secure_wipe(opad);
builtin_secure_wipe(inner_hash);
}
void builtin_hmac_sha256(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
std::span<std::byte> output_32) noexcept
@@ -892,4 +932,95 @@ namespace Void::Crypto::Detail
builtin_secure_wipe(t);
}
void builtin_pbkdf2_hmac_sha256(std::span<const std::byte> password,
std::span<const std::byte> salt,
std::uint32_t iterations,
std::span<std::byte> secret_output) noexcept
{
std::array<std::byte, 64> key_block{};
if (password.size() > 64) {
Sha256State kh;
kh.update(password);
kh.finalize_into(std::span{key_block}.subspan(0, 32));
} else if (!password.empty()) {
std::memcpy(key_block.data(), password.data(), password.size());
}
std::array<std::byte, 64> ipad{};
std::array<std::byte, 64> opad{};
for (std::size_t i = 0; i < 64; ++i) {
ipad[i] = key_block[i] ^ std::byte{0x36};
opad[i] = key_block[i] ^ std::byte{0x5C};
}
auto hmac = [&ipad, &opad](std::span<const std::byte> data,
std::span<std::byte> out) noexcept {
std::array<std::byte, 32> inner_hash{};
{
Sha256State inner;
inner.update(ipad);
inner.update(data);
inner.finalize_into(inner_hash);
}
{
Sha256State outer;
outer.update(opad);
outer.update(inner_hash);
outer.finalize_into(out);
}
builtin_secure_wipe(inner_hash);
};
// Callers cap the output length, so this cannot overflow.
const std::size_t blocks = (secret_output.size() + 31) / 32;
std::size_t written = 0;
for (std::size_t block = 1; block <= blocks; ++block) {
std::array<std::byte, 4> counter{};
store_be32(counter.data(), static_cast<std::uint32_t>(block));
std::array<std::byte, 32> u{};
{
std::array<std::byte, 32> inner_hash{};
{
Sha256State inner;
inner.update(ipad);
inner.update(salt);
inner.update(counter);
inner.finalize_into(inner_hash);
}
{
Sha256State outer;
outer.update(opad);
outer.update(inner_hash);
outer.finalize_into(u);
}
builtin_secure_wipe(inner_hash);
}
std::array<std::byte, 32> t = u;
for (std::uint32_t iteration = 1; iteration < iterations;
++iteration) {
std::array<std::byte, 32> next{};
hmac(u, next);
u = next;
for (std::size_t i = 0; i < t.size(); ++i) {
t[i] ^= u[i];
}
builtin_secure_wipe(next);
}
const std::size_t copy_n =
std::min<std::size_t>(32, secret_output.size() - written);
std::memcpy(secret_output.data() + written, t.data(), copy_n);
written += copy_n;
builtin_secure_wipe(u);
builtin_secure_wipe(t);
}
builtin_secure_wipe(key_block);
builtin_secure_wipe(ipad);
builtin_secure_wipe(opad);
}
} // namespace Void::Crypto::Detail
+10
View File
@@ -4,6 +4,7 @@
#include <Void/Crypto/Types.hpp>
#include <cstddef>
#include <cstdint>
#include <span>
namespace Void::Crypto::Detail
@@ -37,10 +38,19 @@ namespace Void::Crypto::Detail
void destroy() noexcept;
};
void builtin_hmac_sha1(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
std::span<std::byte> output_20) noexcept;
void builtin_hmac_sha256(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
std::span<std::byte> output_32) noexcept;
void builtin_pbkdf2_hmac_sha256(std::span<const std::byte> password,
std::span<const std::byte> salt,
std::uint32_t iterations,
std::span<std::byte> secret_output) noexcept;
void builtin_hkdf_sha256(std::span<const std::byte> secret_input,
std::span<const std::byte> salt,
std::span<const std::byte> context,
+353 -68
View File
@@ -1,7 +1,9 @@
#include <Void/Crypto/Crypto.hpp>
#include "BuiltinEd25519.hpp"
#include "BuiltinHash.hpp"
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstring>
@@ -9,6 +11,7 @@
#include <fstream>
#include <limits>
#include <optional>
#include <random>
#include <utility>
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
@@ -217,9 +220,138 @@ namespace Void::Crypto
return result == 1;
#else
(void)provider;
return Detail::Ed25519::verify(
reinterpret_cast<const std::uint8_t*>(public_key.data()),
reinterpret_cast<const std::uint8_t*>(signature.data()), message);
#endif
}
[[maybe_unused]] [[nodiscard]] const char*
hmac_digest_name(HashAlgorithm algorithm) noexcept
{
switch (algorithm) {
case HashAlgorithm::Sha1:
return "SHA1";
case HashAlgorithm::Sha256:
return "SHA256";
default:
return nullptr;
}
}
[[nodiscard]] Void::Result::Result<void>
hmac_into_impl(HashAlgorithm algorithm,
std::span<const std::byte> secret_key,
std::span<const std::byte> message,
std::span<std::byte> output,
const ProviderOptions& provider,
std::string_view operation)
{
const std::size_t expected_size = algorithm == HashAlgorithm::Sha1
? HmacSha1Size
: HmacSha256Size;
if (output.size() != expected_size) {
return std::unexpected{
make_crypto_error(CryptoErrorCode::invalid_argument,
std::format("{}: output must be {} bytes",
operation, expected_size))};
}
if (spans_overlap(secret_key, output) ||
spans_overlap(message, output)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::overlapping_buffers,
std::format("{}: output buffer overlaps input",
operation))};
}
if (auto fault =
maybe_inject_fault(FaultOperation::hmac, operation);
fault.has_value()) {
secure_wipe(output);
return std::unexpected{std::move(*fault)};
}
if (use_builtin_hash(algorithm, provider)) {
if (!provider.property_query.empty()) {
secure_wipe(output);
return std::unexpected{make_crypto_error(
CryptoErrorCode::provider_error,
std::format("{}: property_query unavailable on "
"built-in backend",
operation))};
}
if (algorithm == HashAlgorithm::Sha1) {
Detail::builtin_hmac_sha1(secret_key, message, output);
} else {
Detail::builtin_hmac_sha256(secret_key, message, output);
}
return {};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
const char* name = hmac_digest_name(algorithm);
if (name == nullptr) {
secure_wipe(output);
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
std::format("{}: unsupported HMAC algorithm", operation))};
}
ERR_clear_error();
EvpMacPtr mac{
EVP_MAC_fetch(nullptr, "HMAC", propq_or_null(provider)),
&EVP_MAC_free};
if (!mac) {
secure_wipe(output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
std::format("{}: EVP_MAC_fetch failed", operation))};
}
EvpMacCtxPtr ctx{EVP_MAC_CTX_new(mac.get()), &EVP_MAC_CTX_free};
if (!ctx) {
secure_wipe(output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
std::format("{}: EVP_MAC_CTX_new failed", operation))};
}
std::array<char, 8> digest_name{};
std::strncpy(digest_name.data(), name, digest_name.size() - 1);
std::array<OSSL_PARAM, 2> params = {
OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
digest_name.data(), 0),
OSSL_PARAM_construct_end(),
};
if (EVP_MAC_init(ctx.get(), non_null_bytes(secret_key),
secret_key.size(), params.data()) != 1) {
secure_wipe(output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
std::format("{}: EVP_MAC_init failed", operation))};
}
if (!message.empty() &&
EVP_MAC_update(ctx.get(), non_null_bytes(message),
message.size()) != 1) {
secure_wipe(output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
std::format("{}: EVP_MAC_update failed", operation))};
}
std::size_t out_len = 0;
if (EVP_MAC_final(ctx.get(),
reinterpret_cast<unsigned char*>(output.data()),
&out_len, output.size()) != 1 ||
out_len != expected_size) {
secure_wipe(output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
std::format("{}: EVP_MAC_final failed", operation))};
}
return {};
#else
secure_wipe(output);
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::verifyEd25519: built without OpenSSL backend")};
CryptoErrorCode::backend_error,
std::format("{}: OpenSSL backend unavailable", operation))};
#endif
}
} // namespace
@@ -642,10 +774,27 @@ namespace Void::Crypto
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
EvpPkeyPtr pkey{nullptr, &EVP_PKEY_free};
#else
std::uint8_t unused{0};
std::array<std::byte, Ed25519SeedSize> seed{};
std::array<std::byte, Ed25519PublicKeySize> public_key{};
#endif
};
#if !defined(VOID_CRYPTO_HAS_OPENSSL) || !VOID_CRYPTO_HAS_OPENSSL
namespace
{
void derive_ed25519_public_key(
const std::array<std::byte, Ed25519SeedSize>& seed,
std::array<std::byte, Ed25519PublicKeySize>& public_key)
{
Detail::Ed25519::Sha512 digest{};
Detail::Ed25519::expand_seed(
reinterpret_cast<const std::uint8_t*>(seed.data()), digest,
reinterpret_cast<std::uint8_t*>(public_key.data()));
Detail::Ed25519::wipe(digest);
}
} // namespace
#endif
Ed25519PrivateKey::Ed25519PrivateKey(std::unique_ptr<Impl> impl) noexcept
: m_impl(std::move(impl))
{
@@ -661,7 +810,7 @@ namespace Void::Crypto
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
return m_impl != nullptr && m_impl->pkey != nullptr;
#else
return false;
return m_impl != nullptr;
#endif
}
@@ -693,10 +842,20 @@ namespace Void::Crypto
return Ed25519PrivateKey{std::move(impl)};
#else
(void)provider;
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Ed25519PrivateKey::generate: built without OpenSSL "
"backend")};
std::random_device random;
std::array<std::byte, Ed25519SeedSize> seed{};
for (std::size_t offset = 0; offset < seed.size();) {
const std::uint32_t word = random();
const std::size_t count =
std::min<std::size_t>(sizeof(word), seed.size() - offset);
std::memcpy(seed.data() + offset, &word, count);
offset += count;
}
auto impl = std::make_unique<Impl>();
impl->seed = seed;
derive_ed25519_public_key(impl->seed, impl->public_key);
secure_wipe(seed);
return Ed25519PrivateKey{std::move(impl)};
#endif
}
@@ -739,10 +898,10 @@ namespace Void::Crypto
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")};
auto impl = std::make_unique<Impl>();
std::memcpy(impl->seed.data(), seed.data(), Ed25519SeedSize);
derive_ed25519_public_key(impl->seed, impl->public_key);
return Ed25519PrivateKey{std::move(impl)};
#endif
}
@@ -768,10 +927,10 @@ namespace Void::Crypto
}
return pub;
#else
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Ed25519PrivateKey::public_key: built without OpenSSL "
"backend")};
Ed25519PublicKey pub;
std::memcpy(pub.bytes.data(), m_impl->public_key.data(),
Ed25519PublicKeySize);
return pub;
#endif
}
@@ -799,10 +958,7 @@ namespace Void::Crypto
secure_wipe(raw);
return result;
#else
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Ed25519PrivateKey::export_raw_seed: built without OpenSSL "
"backend")};
return Ed25519Seed::from_bytes(m_impl->seed);
#endif
}
@@ -865,9 +1021,13 @@ namespace Void::Crypto
return signature;
#else
(void)provider;
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::sign_ed25519: built without OpenSSL backend")};
Ed25519Signature signature;
Detail::Ed25519::sign(
reinterpret_cast<const std::uint8_t*>(private_key.m_impl->seed.data()),
reinterpret_cast<const std::uint8_t*>(
private_key.m_impl->public_key.data()),
message, reinterpret_cast<std::uint8_t*>(signature.bytes.data()));
return signature;
#endif
}
@@ -891,26 +1051,146 @@ namespace Void::Crypto
provider);
}
Void::Result::Result<Ed25519KeyPair>
ed25519_keypair(const ProviderOptions& provider)
{
auto private_key = Ed25519PrivateKey::generate(provider);
if (!private_key) {
return std::unexpected{std::move(private_key).error()};
}
auto public_key = private_key->public_key();
if (!public_key) {
return std::unexpected{std::move(public_key).error()};
}
auto secret_key = private_key->export_raw_seed();
if (!secret_key) {
return std::unexpected{std::move(secret_key).error()};
}
return Ed25519KeyPair{std::move(*secret_key), std::move(*public_key)};
}
Void::Result::Result<Ed25519Signature>
ed25519_sign(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
const ProviderOptions& provider)
{
auto private_key = Ed25519PrivateKey::from_raw_seed(secret_key, provider);
if (!private_key) {
return std::unexpected{std::move(private_key).error()};
}
return sign_ed25519(message, *private_key, provider);
}
Void::Result::Result<bool>
ed25519_verify(std::span<const std::byte> public_key,
std::span<const std::byte> message,
std::span<const std::byte> signature,
const ProviderOptions& provider)
{
auto parsed_public_key = Ed25519PublicKey::from_bytes(public_key);
if (!parsed_public_key) {
return std::unexpected{std::move(parsed_public_key).error()};
}
auto parsed_signature = Ed25519Signature::from_bytes(signature);
if (!parsed_signature) {
return std::unexpected{std::move(parsed_signature).error()};
}
return verify_ed25519(message, *parsed_signature, *parsed_public_key,
provider);
}
Void::Result::Result<void>
hmac_sha1_into(std::span<const std::byte> secret_key,
std::span<const std::byte>
message,
std::span<std::byte>
output,
const ProviderOptions& provider)
{
return hmac_into_impl(HashAlgorithm::Sha1, secret_key, message, output,
provider, "Crypto::hmac_sha1_into");
}
Void::Result::Result<Digest>
hmac_sha1(std::span<const std::byte> secret_key,
std::span<const std::byte>
message,
const ProviderOptions& provider)
{
Digest out(HmacSha1Size);
if (auto res = hmac_sha1_into(secret_key, message, out, provider);
!res.has_value()) {
secure_wipe(out);
return std::unexpected{std::move(res.error())};
}
return out;
}
Void::Result::Result<void>
hmac_sha256_into(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
std::span<std::byte> output,
const ProviderOptions& provider)
{
if (output.size() != HmacSha256Size) {
return hmac_into_impl(HashAlgorithm::Sha256, secret_key, message,
output, provider, "Crypto::hmac_sha256_into");
}
Void::Result::Result<Digest> hmac_sha256(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
const ProviderOptions& provider)
{
Digest out(HmacSha256Size);
if (auto res = hmac_sha256_into(secret_key, message, out, provider);
!res.has_value()) {
secure_wipe(out);
return std::unexpected{std::move(res.error())};
}
return out;
}
Void::Result::Result<void>
pbkdf2_hmac_sha256_into(std::span<const std::byte> password,
std::span<const std::byte> salt,
std::uint32_t iterations,
std::span<std::byte> output,
const ProviderOptions& provider)
{
if (iterations == 0 ||
iterations > CryptoLimits::kMaxPbkdf2Iterations) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_argument,
std::format("Crypto::hmac_sha256_into: output must be {} bytes",
HmacSha256Size))};
std::format("Crypto::pbkdf2_hmac_sha256: iterations must be "
"1..{}",
CryptoLimits::kMaxPbkdf2Iterations))};
}
if (spans_overlap(secret_key, output) ||
spans_overlap(message, output)) {
if (salt.size() > CryptoLimits::kMaxPbkdf2SaltBytes) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::message_too_large,
std::format("Crypto::pbkdf2_hmac_sha256: salt exceeds {} byte "
"cap",
CryptoLimits::kMaxPbkdf2SaltBytes))};
}
if (output.empty()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_argument,
"Crypto::pbkdf2_hmac_sha256: output buffer must be non-empty")};
}
if (output.size() > CryptoLimits::kMaxPbkdf2OutputBytes) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::output_too_large,
std::format(
"Crypto::pbkdf2_hmac_sha256: output size exceeds {} byte "
"cap",
CryptoLimits::kMaxPbkdf2OutputBytes))};
}
if (spans_overlap(password, output) || spans_overlap(salt, output)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::overlapping_buffers,
"Crypto::hmac_sha256_into: output buffer overlaps input")};
"Crypto::pbkdf2_hmac_sha256: output buffer overlaps input")};
}
if (auto fault = maybe_inject_fault(FaultOperation::hmac,
"Crypto::hmac_sha256_into");
if (auto fault = maybe_inject_fault(FaultOperation::pbkdf2,
"Crypto::pbkdf2_hmac_sha256");
fault.has_value()) {
secure_wipe(output);
return std::unexpected{std::move(*fault)};
@@ -921,78 +1201,83 @@ namespace Void::Crypto
secure_wipe(output);
return std::unexpected{make_crypto_error(
CryptoErrorCode::provider_error,
"Crypto::hmac_sha256_into: property_query unavailable on "
"Crypto::pbkdf2_hmac_sha256: property_query unavailable on "
"built-in backend")};
}
Detail::builtin_hmac_sha256(secret_key, message, output);
Detail::builtin_pbkdf2_hmac_sha256(password, salt, iterations,
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};
if (!mac) {
EvpKdfPtr kdf{EVP_KDF_fetch(nullptr, "PBKDF2", propq_or_null(provider)),
&EVP_KDF_free};
if (!kdf) {
secure_wipe(output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::hmac_sha256_into: EVP_MAC_fetch failed")};
"Crypto::pbkdf2_hmac_sha256: EVP_KDF_fetch failed")};
}
EvpMacCtxPtr ctx{EVP_MAC_CTX_new(mac.get()), &EVP_MAC_CTX_free};
EvpKdfCtxPtr ctx{EVP_KDF_CTX_new(kdf.get()), &EVP_KDF_CTX_free};
if (!ctx) {
secure_wipe(output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::hmac_sha256_into: EVP_MAC_CTX_new failed")};
"Crypto::pbkdf2_hmac_sha256: EVP_KDF_CTX_new failed")};
}
char digest_name[] = "SHA256";
std::array<OSSL_PARAM, 2> params = {
OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, digest_name,
int iteration_count = static_cast<int>(iterations);
std::array<OSSL_PARAM, 5> params = {
OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST, digest_name,
0),
OSSL_PARAM_construct_octet_string(
OSSL_KDF_PARAM_PASSWORD,
const_cast<unsigned char*>(non_null_bytes(password)),
password.size()),
OSSL_PARAM_construct_octet_string(
OSSL_KDF_PARAM_SALT,
const_cast<unsigned char*>(non_null_bytes(salt)), salt.size()),
OSSL_PARAM_construct_int(OSSL_KDF_PARAM_ITER, &iteration_count),
OSSL_PARAM_construct_end(),
};
if (EVP_MAC_init(ctx.get(), non_null_bytes(secret_key),
secret_key.size(), params.data()) != 1) {
secure_wipe(output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::hmac_sha256_into: EVP_MAC_init failed")};
}
if (!message.empty() &&
EVP_MAC_update(ctx.get(), non_null_bytes(message),
message.size()) != 1) {
if (EVP_KDF_derive(ctx.get(),
reinterpret_cast<unsigned char*>(output.data()),
output.size(), params.data()) != 1) {
secure_wipe(output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::hmac_sha256_into: EVP_MAC_update failed")};
}
std::size_t out_len = 0;
if (EVP_MAC_final(ctx.get(),
reinterpret_cast<unsigned char*>(output.data()),
&out_len, output.size()) != 1 ||
out_len != HmacSha256Size) {
secure_wipe(output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::hmac_sha256_into: EVP_MAC_final failed")};
"Crypto::pbkdf2_hmac_sha256: EVP_KDF_derive failed")};
}
return {};
#else
secure_wipe(output);
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::hmac_sha256_into: OpenSSL backend unavailable")};
"Crypto::pbkdf2_hmac_sha256: OpenSSL backend unavailable")};
#endif
}
Void::Result::Result<Digest> hmac_sha256(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
const ProviderOptions& provider)
Void::Result::Result<Digest>
pbkdf2_hmac_sha256(std::span<const std::byte> password,
std::span<const std::byte> salt,
std::uint32_t iterations,
std::size_t output_length,
const ProviderOptions& provider)
{
Digest out(HmacSha256Size);
if (auto res = hmac_sha256_into(secret_key, message, out, provider);
if (output_length > CryptoLimits::kMaxPbkdf2OutputBytes) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::output_too_large,
std::format(
"Crypto::pbkdf2_hmac_sha256: output size exceeds {} byte "
"cap",
CryptoLimits::kMaxPbkdf2OutputBytes))};
}
Digest out(output_length);
if (auto res = pbkdf2_hmac_sha256_into(password, salt, iterations, out,
provider);
!res.has_value()) {
secure_wipe(out);
return std::unexpected{std::move(res.error())};
+877 -2
View File
@@ -33,6 +33,19 @@
#include <sys/socket.h>
#endif
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef FD_SETSIZE
#define FD_SETSIZE 1024
#endif
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <io.h>
#endif
namespace Void::IO::detail
{
@@ -2814,7 +2827,861 @@ private:
int wake_fd_{-1};
std::atomic<bool> wake_closed_{false};
};
#endif // __linux__
#elif defined(_WIN32)
// ── Windows portable poll (select) backend ─────────────────────────────
//
// IOCP would require a full overlapped-operation rewrite of the driver.
// Instead this backend keeps the shared BaseBackend operation machinery and
// uses Winsock select() for readiness. Streams must be sockets (or CRT fds
// for blocking _read/_write); positional files use the shared worker pool.
namespace
{
[[nodiscard]] std::error_code win_error_code(int err) noexcept
{
return std::error_code{err, std::system_category()};
}
[[nodiscard]] bool ensure_winsock() noexcept
{
static const bool ready = [] {
WSADATA data{};
return ::WSAStartup(MAKEWORD(2, 2), &data) == 0;
}();
return ready;
}
[[nodiscard]] SOCKET socket_from_fd(int fd) noexcept
{
return static_cast<SOCKET>(static_cast<std::uintptr_t>(
static_cast<std::uint32_t>(fd)));
}
[[nodiscard]] int fd_from_socket(SOCKET socket) noexcept
{
return static_cast<int>(static_cast<std::uint32_t>(socket));
}
[[nodiscard]] bool is_socket_fd(SOCKET socket) noexcept
{
int type = 0;
int length = sizeof(type);
return ::getsockopt(socket, SOL_SOCKET, SO_TYPE,
reinterpret_cast<char*>(&type), &length) == 0;
}
[[nodiscard]] bool set_nonblocking(SOCKET socket) noexcept
{
u_long mode = 1;
return ::ioctlsocket(socket, FIONBIO, &mode) == 0;
}
} // namespace
class SelectBackend final : public BaseBackend
{
public:
static Void::Result::Result<std::shared_ptr<SelectBackend>> create_select(
Async::Executor& executor,
IoLimits limits,
const Void::Time::MonotonicClock& clock,
std::shared_ptr<OwnedBufferTracker> buffer_tracker,
FileSyscalls* file_syscalls,
std::function<Void::Result::Result<void>(std::size_t)> worker_hook)
{
if (!ensure_winsock()) {
return std::unexpected{make_io_error(
IoErrorCode::os_error, "WSAStartup failed",
win_error_code(::WSAGetLastError()))};
}
const SOCKET wake_recv = ::socket(AF_INET, SOCK_DGRAM, 0);
if (wake_recv == INVALID_SOCKET) {
return std::unexpected{make_io_error(
IoErrorCode::os_error, "wake socket failed",
win_error_code(::WSAGetLastError()))};
}
sockaddr_in address{};
address.sin_family = AF_INET;
address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
address.sin_port = 0;
if (::bind(wake_recv, reinterpret_cast<sockaddr*>(&address),
sizeof(address)) == SOCKET_ERROR) {
const int err = ::WSAGetLastError();
::closesocket(wake_recv);
return std::unexpected{make_io_error(
IoErrorCode::os_error, "wake bind failed",
win_error_code(err))};
}
int length = sizeof(address);
if (::getsockname(wake_recv, reinterpret_cast<sockaddr*>(&address),
&length) == SOCKET_ERROR) {
const int err = ::WSAGetLastError();
::closesocket(wake_recv);
return std::unexpected{make_io_error(
IoErrorCode::os_error, "wake getsockname failed",
win_error_code(err))};
}
const SOCKET wake_send = ::socket(AF_INET, SOCK_DGRAM, 0);
if (wake_send == INVALID_SOCKET ||
::connect(wake_send, reinterpret_cast<sockaddr*>(&address),
sizeof(address)) == SOCKET_ERROR ||
!set_nonblocking(wake_recv) || !set_nonblocking(wake_send)) {
const int err = ::WSAGetLastError();
if (wake_send != INVALID_SOCKET) {
::closesocket(wake_send);
}
::closesocket(wake_recv);
return std::unexpected{make_io_error(
IoErrorCode::os_error, "wake socket setup failed",
win_error_code(err))};
}
try {
return std::shared_ptr<SelectBackend>(new SelectBackend(
executor, limits, clock, std::move(buffer_tracker),
file_syscalls, std::move(worker_hook), wake_recv, wake_send));
} catch (...) {
::closesocket(wake_send);
::closesocket(wake_recv);
throw;
}
}
~SelectBackend() override
{
for (auto& slot : slots_) {
if (slot.in_use && !slot.is_file && slot.fd >= 0) {
::closesocket(socket_from_fd(slot.fd));
slot.fd = -1;
}
}
if (wake_send_ != INVALID_SOCKET) {
::closesocket(wake_send_);
wake_send_ = INVALID_SOCKET;
}
if (wake_recv_ != INVALID_SOCKET) {
::closesocket(wake_recv_);
wake_recv_ = INVALID_SOCKET;
}
}
[[nodiscard]] BackendPreference kind() const noexcept override
{
return BackendPreference::epoll;
}
[[nodiscard]] Void::Result::Result<std::shared_ptr<StreamState>>
create_mock_stream() override
{
return std::unexpected{make_io_error(
IoErrorCode::unsupported,
"SelectBackend does not create mock streams")};
}
[[nodiscard]] Void::Result::Result<std::shared_ptr<StreamState>>
adopt_fd(int fd) override
{
if (fd < 0) {
return std::unexpected{make_io_error(
IoErrorCode::invalid_argument,
"Invalid negative fd in adopt_fd")};
}
const SOCKET socket = socket_from_fd(fd);
if (!is_socket_fd(socket)) {
return std::unexpected{make_io_error(
IoErrorCode::unsupported,
"Windows poll backend adopts sockets only")};
}
(void)set_nonblocking(socket);
DescriptorId id;
{
std::lock_guard lk{mu_};
if (control_queue_.size() >= limits_.max_control_submissions) {
return std::unexpected{make_io_error(
IoErrorCode::overloaded, "IO Driver control queue full")};
}
auto res = allocate_slot_locked(fd);
if (!res.has_value()) {
return std::unexpected{std::move(res.error())};
}
id = *res;
control_queue_.push_back(
ControlAction{ControlAction::Type::register_fd, id});
}
wake();
return std::make_shared<StreamState>(this->shared_from_this(), id);
}
[[nodiscard]] Void::Result::Result<
std::pair<std::shared_ptr<StreamState>, std::shared_ptr<StreamState>>>
create_socket_pair() override
{
const SOCKET listener = ::socket(AF_INET, SOCK_STREAM, 0);
if (listener == INVALID_SOCKET) {
return std::unexpected{make_io_error(
IoErrorCode::os_error, "socketpair listener failed",
win_error_code(::WSAGetLastError()))};
}
sockaddr_in address{};
address.sin_family = AF_INET;
address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
address.sin_port = 0;
if (::bind(listener, reinterpret_cast<sockaddr*>(&address),
sizeof(address)) == SOCKET_ERROR ||
::listen(listener, 1) == SOCKET_ERROR) {
const int err = ::WSAGetLastError();
::closesocket(listener);
return std::unexpected{make_io_error(
IoErrorCode::os_error, "socketpair bind/listen failed",
win_error_code(err))};
}
int length = sizeof(address);
(void)::getsockname(listener, reinterpret_cast<sockaddr*>(&address),
&length);
const SOCKET client = ::socket(AF_INET, SOCK_STREAM, 0);
if (client == INVALID_SOCKET ||
::connect(client, reinterpret_cast<sockaddr*>(&address),
sizeof(address)) == SOCKET_ERROR) {
const int err = ::WSAGetLastError();
if (client != INVALID_SOCKET) {
::closesocket(client);
}
::closesocket(listener);
return std::unexpected{make_io_error(
IoErrorCode::os_error, "socketpair connect failed",
win_error_code(err))};
}
const SOCKET server = ::accept(listener, nullptr, nullptr);
::closesocket(listener);
if (server == INVALID_SOCKET) {
const int err = ::WSAGetLastError();
::closesocket(client);
return std::unexpected{make_io_error(
IoErrorCode::os_error, "socketpair accept failed",
win_error_code(err))};
}
(void)set_nonblocking(client);
(void)set_nonblocking(server);
auto first = adopt_fd(fd_from_socket(client));
if (!first.has_value()) {
::closesocket(client);
::closesocket(server);
return std::unexpected{std::move(first.error())};
}
auto second = adopt_fd(fd_from_socket(server));
if (!second.has_value()) {
on_stream_destroyed((*first)->id());
::closesocket(server);
return std::unexpected{std::move(second.error())};
}
return std::make_pair(std::move(*first), std::move(*second));
}
void wake() noexcept override
{
if (wake_closed_.load(std::memory_order_acquire)) {
return;
}
wakeups_.fetch_add(1, std::memory_order_acq_rel);
const char byte = 1;
(void)::send(wake_send_, &byte, 1, 0);
}
protected:
[[nodiscard]] Void::Result::Result<std::size_t>
run_turn(std::optional<std::chrono::nanoseconds> max_wait) override
{
std::size_t work_done = 0;
std::vector<Async::ResumeTicket> tickets;
work_done += process_cancels_and_controls(tickets);
work_done += drain_file_completions(tickets);
work_done += scan_close_waiters(std::nullopt, tickets);
if (shutdown_begun_.load(std::memory_order_acquire)) {
work_done += abort_pending_socket_ops(tickets);
}
if (file_deadlines_pending()) {
const auto now = clock_.now();
work_done += expire_file_work_at(now, tickets);
work_done += drain_file_completions(tickets);
}
dispatch_tickets(tickets);
int timeout_ms = 0;
{
std::optional<Void::Time::MonotonicClock::time_point> earliest;
{
std::lock_guard lk{mu_};
for (const auto& slot : slots_) {
if (!slot.in_use) {
continue;
}
for (const auto* op : {&slot.active_read, &slot.active_write}) {
if (*op && (*op)->deadline.has_value()) {
if (!earliest.has_value() || *(*op)->deadline < *earliest) {
earliest = *(*op)->deadline;
}
}
}
}
}
if (const auto fdl = earliest_file_deadline(); fdl.has_value()) {
if (!earliest.has_value() || *fdl < *earliest) {
earliest = fdl;
}
}
if (max_wait.has_value()) {
auto wait_ns = *max_wait;
if (earliest.has_value()) {
const auto rem = Void::Time::remaining_until(clock_, *earliest);
if (rem < wait_ns) {
wait_ns = rem;
}
}
if (wait_ns.count() <= 0) {
timeout_ms = 0;
} else {
const auto ms =
std::chrono::duration_cast<std::chrono::milliseconds>(wait_ns).count();
timeout_ms = static_cast<int>(
std::clamp<long long>(ms == 0 ? 1 : ms, 0, 5000));
}
} else {
if (earliest.has_value()) {
const auto rem = Void::Time::remaining_until(clock_, *earliest);
const auto ms =
std::chrono::duration_cast<std::chrono::milliseconds>(rem).count();
timeout_ms = static_cast<int>(
std::clamp<long long>((rem.count() > 0 && ms == 0) ? 1 : ms, 0, 5000));
} else {
timeout_ms = -1;
}
}
}
struct PollEntry {
std::uint32_t slot{};
std::uint32_t generation{};
int fd{-1};
bool want_read{false};
bool want_write{false};
};
std::vector<PollEntry> entries;
fd_set read_set;
fd_set write_set;
fd_set error_set;
FD_ZERO(&read_set);
FD_ZERO(&write_set);
FD_ZERO(&error_set);
FD_SET(wake_recv_, &read_set);
{
std::lock_guard lk{mu_};
for (std::uint32_t index = 0; index < slots_.size(); ++index) {
auto& slot = slots_[index];
if (!slot.in_use || slot.is_file || slot.fd < 0 || slot.closing) {
continue;
}
const bool want_read =
slot.active_read != nullptr && !slot.active_read->retired;
const bool want_write =
slot.active_write != nullptr && !slot.active_write->retired;
if (!want_read && !want_write) {
continue;
}
if (entries.size() + 1 >= static_cast<std::size_t>(FD_SETSIZE)) {
break;
}
const SOCKET socket = socket_from_fd(slot.fd);
if (want_read) {
FD_SET(socket, &read_set);
}
if (want_write) {
FD_SET(socket, &write_set);
}
FD_SET(socket, &error_set);
entries.push_back(PollEntry{index, slot.id.generation, slot.fd,
want_read, want_write});
}
}
timeval wait{};
timeval* wait_ptr = nullptr;
if (timeout_ms >= 0) {
wait.tv_sec = timeout_ms / 1000;
wait.tv_usec = (timeout_ms % 1000) * 1000;
wait_ptr = &wait;
} else if (shutdown_begun_.load(std::memory_order_acquire)) {
// Never block an unbounded shutdown slice on a lost wake.
wait.tv_sec = 0;
wait.tv_usec = 10000;
wait_ptr = &wait;
}
const int ready = ::select(0, &read_set, &write_set, &error_set, wait_ptr);
if (ready == SOCKET_ERROR) {
const int err = ::WSAGetLastError();
if (err == WSAEINTR) {
return work_done;
}
return std::unexpected{make_io_error(
IoErrorCode::os_error, "select failed", win_error_code(err))};
}
if (FD_ISSET(wake_recv_, &read_set)) {
drain_wake();
}
for (const auto& entry : entries) {
const SOCKET socket = socket_from_fd(entry.fd);
std::uint32_t mask = 0;
if (entry.want_read && FD_ISSET(socket, &read_set)) {
mask |= kIn | kHup;
}
if (entry.want_write && FD_ISSET(socket, &write_set)) {
mask |= kOut;
}
if (FD_ISSET(socket, &error_set)) {
mask |= kErr | kHup;
}
if (mask == 0) {
continue;
}
std::shared_ptr<PendingOp> read_op;
std::shared_ptr<PendingOp> write_op;
{
std::lock_guard lk{mu_};
if (entry.slot >= slots_.size() || !slots_[entry.slot].in_use ||
slots_[entry.slot].is_file ||
slots_[entry.slot].id.generation != entry.generation ||
slots_[entry.slot].fd < 0 || slots_[entry.slot].closing) {
stale_events_ignored_.fetch_add(1, std::memory_order_acq_rel);
continue;
}
if ((mask & (kIn | kHup | kErr)) != 0 &&
slots_[entry.slot].active_read &&
!slots_[entry.slot].active_read->retired) {
read_op = slots_[entry.slot].active_read;
}
if ((mask & (kOut | kHup | kErr)) != 0 &&
slots_[entry.slot].active_write &&
!slots_[entry.slot].active_write->retired) {
write_op = slots_[entry.slot].active_write;
}
}
if (read_op) {
work_done += drive_read(entry.slot, entry.generation, entry.fd,
mask, read_op, tickets);
}
if (write_op) {
work_done += drive_write(entry.slot, entry.generation, entry.fd,
mask, write_op, tickets);
}
}
work_done += process_cancels_and_controls(tickets);
work_done += drain_file_completions(tickets);
work_done += scan_close_waiters(std::nullopt, tickets);
work_done += expire_deadlines(tickets);
if (file_deadlines_pending()) {
const auto now = clock_.now();
work_done += expire_file_work_at(now, tickets);
work_done += drain_file_completions(tickets);
}
dispatch_tickets(tickets);
return work_done;
}
std::size_t drain_socket_queues(std::vector<Async::ResumeTicket>& tickets) override
{
drain_wake();
return process_cancels_and_controls(tickets);
}
void on_slot_abort_locked(DescriptorSlot& slot) noexcept override
{
slot.epoll_registered = false;
slot.epoll_in_armed = false;
slot.epoll_out_armed = false;
}
void on_op_retired_locked(DescriptorSlot&) noexcept override {}
[[nodiscard]] bool closes_native_fds() const noexcept override { return true; }
void on_slot_final_close_locked(DescriptorSlot& slot) noexcept override
{
if (slot.fd >= 0) {
::closesocket(socket_from_fd(slot.fd));
slot.fd = -1;
}
on_slot_abort_locked(slot);
}
void on_shutdown_complete() noexcept override
{
wake_closed_.store(true, std::memory_order_release);
}
[[nodiscard]] Void::Result::Result<void>
on_op_submitted_locked(DescriptorSlot&, Direction,
const std::shared_ptr<PendingOp>&) override
{
return {};
}
private:
static constexpr std::uint32_t kIn = 0x0001;
static constexpr std::uint32_t kOut = 0x0004;
static constexpr std::uint32_t kErr = 0x0008;
static constexpr std::uint32_t kHup = 0x0010;
SelectBackend(Async::Executor& executor,
IoLimits limits,
const Void::Time::MonotonicClock& clock,
std::shared_ptr<OwnedBufferTracker> buffer_tracker,
FileSyscalls* file_syscalls,
std::function<Void::Result::Result<void>(std::size_t)> worker_hook,
SOCKET wake_recv,
SOCKET wake_send)
: BaseBackend(executor, limits, clock, std::move(buffer_tracker),
file_syscalls, std::move(worker_hook))
, wake_recv_(wake_recv)
, wake_send_(wake_send)
{
}
void drain_wake() noexcept
{
char buffer[64];
while (::recv(wake_recv_, buffer, sizeof(buffer), 0) > 0) {
}
}
std::size_t process_cancels_and_controls(
std::vector<Async::ResumeTicket>& tickets)
{
std::size_t done = 0;
std::vector<std::shared_ptr<PendingOp>> cancels;
std::vector<ControlAction> controls;
std::vector<CloseWaiter> close_waiters;
{
std::lock_guard lk{mu_};
cancels.swap(cancel_queue_);
controls.swap(control_queue_);
}
for (const auto& op : cancels) {
if (complete_op_and_collect_tickets(
op,
std::unexpected{make_io_error(
IoErrorCode::cancelled, "IO operation cancelled")},
tickets, close_waiters,
/*skip_if_executing=*/true)) {
++done;
}
}
{
std::lock_guard lk{mu_};
for (const auto& action : controls) {
if (!action.id.valid() || action.id.slot >= slots_.size()) {
continue;
}
auto& slot = slots_[action.id.slot];
if (!slot.in_use || slot.is_file ||
slot.id.generation != action.id.generation) {
continue;
}
if (action.type == ControlAction::Type::close_fd) {
if (!slot.active_read && !slot.active_write) {
close_waiters.insert(
close_waiters.end(),
std::make_move_iterator(slot.close_waiters.begin()),
std::make_move_iterator(slot.close_waiters.end()));
slot.close_waiters.clear();
release_slot_locked(action.id.slot, true);
++done;
}
}
}
}
commit_close_waiters(close_waiters, tickets);
return done;
}
std::size_t expire_deadlines(std::vector<Async::ResumeTicket>& tickets)
{
std::vector<std::shared_ptr<PendingOp>> expired;
const auto now = clock_.now();
{
std::lock_guard lk{mu_};
for (auto& slot : slots_) {
if (!slot.in_use || slot.is_file) {
continue;
}
if (slot.active_read && !slot.active_read->retired &&
!slot.active_read->in_execution &&
slot.active_read->deadline.has_value() &&
now >= *slot.active_read->deadline) {
expired.push_back(slot.active_read);
}
if (slot.active_write && !slot.active_write->retired &&
!slot.active_write->in_execution &&
slot.active_write->deadline.has_value() &&
now >= *slot.active_write->deadline) {
expired.push_back(slot.active_write);
}
}
}
std::size_t done = 0;
std::vector<CloseWaiter> close_waiters;
for (const auto& op : expired) {
if (complete_op_and_collect_tickets(
op,
std::unexpected{make_io_error(
IoErrorCode::timeout, "IO operation timed out")},
tickets, close_waiters,
/*skip_if_executing=*/true)) {
++done;
}
}
return done;
}
[[nodiscard]] bool begin_execution(const std::shared_ptr<PendingOp>& op) noexcept
{
std::lock_guard lk{mu_};
if (op->retired) {
return false;
}
op->in_execution = true;
return true;
}
void end_execution(const std::shared_ptr<PendingOp>& op) noexcept
{
std::lock_guard lk{mu_};
op->in_execution = false;
}
std::size_t drive_read(std::uint32_t slot_idx,
std::uint32_t gen,
int fd,
std::uint32_t ev_mask,
const std::shared_ptr<PendingOp>& op,
std::vector<Async::ResumeTicket>& tickets)
{
(void)slot_idx;
(void)gen;
if (op->op_state->stop_requested()) {
std::vector<CloseWaiter> close_waiters;
return complete_op_and_collect_tickets(
op,
std::unexpected{make_io_error(
IoErrorCode::cancelled,
"Read cancelled before syscall")},
tickets, close_waiters)
? 1
: 0;
}
if (!begin_execution(op)) {
return 0;
}
const std::size_t to_read = std::min(op->len, limits_.max_bytes_per_turn);
const SOCKET socket = socket_from_fd(fd);
const bool is_socket = is_socket_fd(socket);
int n = -1;
int saved_error = 0;
for (;;) {
if (is_socket) {
n = ::recv(socket, reinterpret_cast<char*>(op->read_ptr),
static_cast<int>(to_read), 0);
saved_error = n < 0 ? ::WSAGetLastError() : 0;
if (n < 0 && saved_error == WSAEINTR) {
continue;
}
} else {
n = ::_read(fd, op->read_ptr,
static_cast<unsigned int>(to_read));
saved_error = n < 0 ? errno : 0;
if (n < 0 && saved_error == EINTR) {
continue;
}
}
break;
}
int so_err = 0;
if (n < 0 && is_socket && saved_error == WSAEWOULDBLOCK &&
(ev_mask & kErr) != 0) {
int length = sizeof(so_err);
if (::getsockopt(socket, SOL_SOCKET, SO_ERROR,
reinterpret_cast<char*>(&so_err), &length) != 0) {
so_err = 0;
}
}
end_execution(op);
std::vector<CloseWaiter> close_waiters;
if (n > 0) {
return complete_op_and_collect_tickets(
op, Transfer{static_cast<std::size_t>(n), false},
tickets, close_waiters)
? 1
: 0;
}
if (n == 0) {
return complete_op_and_collect_tickets(
op, Transfer{0, true}, tickets, close_waiters)
? 1
: 0;
}
const bool would_block =
is_socket ? saved_error == WSAEWOULDBLOCK : saved_error == EAGAIN;
if (would_block) {
if (so_err != 0) {
return complete_op_and_collect_tickets(
op,
std::unexpected{make_io_error(
IoErrorCode::os_error, "Socket error on read",
win_error_code(so_err))},
tickets, close_waiters)
? 1
: 0;
}
return 0;
}
return complete_op_and_collect_tickets(
op,
std::unexpected{make_io_error(
IoErrorCode::os_error, "read failed",
win_error_code(saved_error))},
tickets, close_waiters)
? 1
: 0;
}
void disarm_write_locked(std::uint32_t slot_idx,
std::uint32_t gen,
const std::shared_ptr<PendingOp>& op) noexcept
{
if (slot_idx < slots_.size() && slots_[slot_idx].in_use &&
slots_[slot_idx].id.generation == gen) {
slots_[slot_idx].active_write.reset();
slots_[slot_idx].active_write = op;
}
}
std::size_t drive_write(std::uint32_t slot_idx,
std::uint32_t gen,
int fd,
std::uint32_t ev_mask,
const std::shared_ptr<PendingOp>& op,
std::vector<Async::ResumeTicket>& tickets)
{
if (op->op_state->stop_requested()) {
{
std::lock_guard lk{mu_};
if (!op->retired) {
disarm_write_locked(slot_idx, gen, op);
}
}
std::vector<CloseWaiter> close_waiters;
return complete_op_and_collect_tickets(
op,
std::unexpected{make_io_error(
IoErrorCode::cancelled,
"Write cancelled before syscall")},
tickets, close_waiters)
? 1
: 0;
}
if (!begin_execution(op)) {
return 0;
}
const std::size_t to_write =
std::min(op->len, limits_.max_bytes_per_turn);
const SOCKET socket = socket_from_fd(fd);
const bool is_socket = is_socket_fd(socket);
int n = -1;
int saved_error = 0;
for (;;) {
if (is_socket) {
n = ::send(socket, reinterpret_cast<const char*>(op->write_ptr),
static_cast<int>(to_write), 0);
saved_error = n < 0 ? ::WSAGetLastError() : 0;
if (n < 0 && saved_error == WSAEINTR) {
continue;
}
} else {
n = ::_write(fd, op->write_ptr,
static_cast<unsigned int>(to_write));
saved_error = n < 0 ? errno : 0;
if (n < 0 && saved_error == EINTR) {
continue;
}
}
break;
}
int so_err = 0;
if (n < 0 && is_socket && saved_error == WSAEWOULDBLOCK &&
(ev_mask & kErr) != 0) {
int length = sizeof(so_err);
if (::getsockopt(socket, SOL_SOCKET, SO_ERROR,
reinterpret_cast<char*>(&so_err), &length) != 0) {
so_err = 0;
}
}
end_execution(op);
std::vector<CloseWaiter> close_waiters;
if (n >= 0) {
{
std::lock_guard lk{mu_};
if (!op->retired) {
disarm_write_locked(slot_idx, gen, op);
}
}
return complete_op_and_collect_tickets(
op, Transfer{static_cast<std::size_t>(n), false},
tickets, close_waiters)
? 1
: 0;
}
const bool would_block =
is_socket ? saved_error == WSAEWOULDBLOCK : saved_error == EAGAIN;
if (would_block) {
if (so_err != 0) {
{
std::lock_guard lk{mu_};
if (!op->retired) {
disarm_write_locked(slot_idx, gen, op);
}
}
return complete_op_and_collect_tickets(
op,
std::unexpected{make_io_error(
IoErrorCode::os_error,
"Socket error on write",
win_error_code(so_err))},
tickets, close_waiters)
? 1
: 0;
}
return 0;
}
{
std::lock_guard lk{mu_};
if (!op->retired) {
disarm_write_locked(slot_idx, gen, op);
}
}
return complete_op_and_collect_tickets(
op,
std::unexpected{make_io_error(
IoErrorCode::os_error, "write failed",
win_error_code(saved_error))},
tickets, close_waiters)
? 1
: 0;
}
SOCKET wake_recv_{INVALID_SOCKET};
SOCKET wake_send_{INVALID_SOCKET};
std::atomic<bool> wake_closed_{false};
};
#endif // __linux__ / _WIN32
} // namespace Void::IO::detail
@@ -2949,10 +3816,18 @@ Void::Result::Result<std::unique_ptr<Driver>> Driver::create(
return std::unexpected{std::move(ep.error())};
}
backend = std::move(*ep);
#elif defined(_WIN32)
auto poll = detail::SelectBackend::create_select(
executor, options.limits, clock, tracker, options.file_syscalls,
std::move(options.before_file_worker_start));
if (!poll.has_value()) {
return std::unexpected{std::move(poll.error())};
}
backend = std::move(*poll);
#else
return std::unexpected{make_io_error(
IoErrorCode::unsupported,
"Epoll backend is only supported on Linux; use BackendPreference::mock")};
"No native IO backend for this platform; use BackendPreference::mock")};
#endif
}
+6 -1
View File
@@ -1,3 +1,8 @@
void_add_module(IO
INTERNAL_DEPS Core Functional Time Memory Async
)
# The native epoll driver only builds on Linux/Unix; Windows uses the
# select-based backend and needs winsock.
EXCLUDE_SOURCES_WIN32
EpollDriver.cpp
DEPS_WIN32 ws2_32
)
+208
View File
@@ -0,0 +1,208 @@
#include <Void/MCP/Codec.hpp>
#include <format>
#include <string>
#include <utility>
namespace Void::MCP
{
LineFramer::LineFramer(McpLimits limits) : m_limits(std::move(limits))
{
}
std::size_t LineFramer::buffered() const noexcept
{
return m_buffer.size();
}
void LineFramer::reset() noexcept
{
m_buffer.clear();
}
Void::Result::Result<void>
LineFramer::append(std::string_view bytes)
{
m_buffer.append(bytes);
const std::size_t last_newline = m_buffer.rfind('\n');
const std::size_t tail =
last_newline == std::string::npos
? m_buffer.size()
: m_buffer.size() - last_newline - 1U;
if (tail > m_limits.max_line_bytes) {
return std::unexpected{make_mcp_error(
McpErrorCode::payload_too_large,
std::format("MCP: stdio frame exceeds {} bytes",
m_limits.max_line_bytes))};
}
return {};
}
Void::Result::Result<std::optional<std::string>>
LineFramer::next()
{
for (;;) {
const std::size_t newline = m_buffer.find('\n');
if (newline == std::string::npos) {
return std::optional<std::string>{};
}
std::string line = m_buffer.substr(0, newline);
m_buffer.erase(0, newline + 1U);
if (!line.empty() && line.back() == '\r') {
line.pop_back();
}
if (line.empty()) {
continue;
}
if (line.size() > m_limits.max_line_bytes) {
return std::unexpected{make_mcp_error(
McpErrorCode::payload_too_large,
std::format("MCP: stdio frame exceeds {} bytes",
m_limits.max_line_bytes))};
}
return std::optional<std::string>{std::move(line)};
}
}
Void::Result::Result<std::string>
frame_line(std::string_view json, const McpLimits& limits)
{
if (json.size() > limits.max_line_bytes) {
return std::unexpected{make_mcp_error(
McpErrorCode::payload_too_large,
std::format("MCP: stdio frame {} bytes exceeds {}",
json.size(), limits.max_line_bytes))};
}
std::string frame{json};
frame.push_back('\n');
return frame;
}
Void::Result::Result<std::string>
encode_sse_event(const SseEvent& event, const McpLimits& limits)
{
std::string out;
if (!event.event.empty()) {
out += "event: ";
out += event.event;
out.push_back('\n');
}
if (!event.id.empty()) {
out += "id: ";
out += event.id;
out.push_back('\n');
}
std::size_t begin = 0;
for (;;) {
const std::size_t newline = event.data.find('\n', begin);
out += "data: ";
if (newline == std::string::npos) {
out.append(event.data, begin, std::string::npos);
out.push_back('\n');
break;
}
out.append(event.data, begin, newline - begin);
out.push_back('\n');
begin = newline + 1U;
}
out.push_back('\n');
if (out.size() > limits.max_sse_event_bytes) {
return std::unexpected{make_mcp_error(
McpErrorCode::payload_too_large,
std::format("MCP: SSE event {} bytes exceeds {}",
out.size(), limits.max_sse_event_bytes))};
}
return out;
}
SseParser::SseParser(McpLimits limits) : m_limits(std::move(limits))
{
}
std::size_t SseParser::buffered() const noexcept
{
return m_buffer.size();
}
void SseParser::reset() noexcept
{
m_buffer.clear();
}
Void::Result::Result<void>
SseParser::append(std::string_view bytes)
{
m_buffer.append(bytes);
if (m_buffer.size() > m_limits.max_sse_event_bytes &&
m_buffer.find("\n\n") == std::string::npos) {
return std::unexpected{make_mcp_error(
McpErrorCode::payload_too_large,
std::format("MCP: SSE buffer exceeds {} bytes",
m_limits.max_sse_event_bytes))};
}
return {};
}
Void::Result::Result<std::optional<SseEvent>>
SseParser::next()
{
for (;;) {
const std::size_t separator = m_buffer.find("\n\n");
if (separator == std::string::npos) {
return std::optional<SseEvent>{};
}
const std::string block = m_buffer.substr(0, separator);
m_buffer.erase(0, separator + 2U);
SseEvent event;
bool has_data = false;
std::size_t begin = 0;
while (begin <= block.size()) {
const std::size_t newline = block.find('\n', begin);
const std::string_view line =
newline == std::string::npos
? std::string_view{block}.substr(begin)
: std::string_view{block}.substr(
begin, newline - begin);
begin = newline == std::string::npos ? block.size() + 1U
: newline + 1U;
if (line.empty() || line.front() == ':') {
continue;
}
const std::size_t colon = line.find(':');
const std::string_view field =
colon == std::string_view::npos
? line
: line.substr(0, colon);
std::string_view value =
colon == std::string_view::npos
? std::string_view{}
: line.substr(colon + 1U);
if (!value.empty() && value.front() == ' ') {
value.remove_prefix(1U);
}
if (field == "event") {
event.event = value;
} else if (field == "id") {
event.id = value;
} else if (field == "data") {
if (has_data) {
event.data.push_back('\n');
}
event.data += value;
has_data = true;
}
}
if (!has_data) {
continue;
}
if (event.data.size() > m_limits.max_sse_event_bytes) {
return std::unexpected{make_mcp_error(
McpErrorCode::payload_too_large,
"MCP: SSE event data exceeds limit")};
}
return std::optional<SseEvent>{std::move(event)};
}
}
} // namespace Void::MCP
+493
View File
@@ -0,0 +1,493 @@
#include <Void/MCP/Envelope.hpp>
#include <algorithm>
#include <cstdint>
#include <format>
#include <string>
#include <utility>
#include <variant>
namespace Void::MCP
{
namespace
{
using Object = JsonValue::Object;
using Array = JsonValue::Array;
[[nodiscard]] const Object* as_object(const JsonValue& value) noexcept
{
return std::get_if<Object>(&value.value);
}
[[nodiscard]] const std::string*
as_string(const JsonValue& value) noexcept
{
return std::get_if<std::string>(&value.value);
}
[[nodiscard]] const std::int64_t*
as_integer(const JsonValue& value) noexcept
{
return std::get_if<std::int64_t>(&value.value);
}
[[nodiscard]] Void::Result::Error
invalid(std::string message)
{
return make_mcp_error(McpErrorCode::invalid_request,
std::move(message));
}
[[nodiscard]] Void::Result::Result<std::string>
serialize_value(const JsonValue& value, const McpLimits& limits)
{
auto text = Void::Json::Strict::serialize(value,
limits.max_json_depth);
if (!text.has_value()) {
return std::unexpected{make_mcp_error(
McpErrorCode::invalid_params,
std::format("MCP: JSON serialize failed: {}",
text.error().message))};
}
if (text->size() > limits.max_message_bytes) {
return std::unexpected{make_mcp_error(
McpErrorCode::payload_too_large,
std::format("MCP: encoded message {} bytes exceeds {}",
text->size(), limits.max_message_bytes))};
}
return std::move(*text);
}
[[nodiscard]] JsonValue encode_id(const JsonRpcId& id)
{
return std::visit(
[](const auto& value) -> JsonValue {
using T = std::decay_t<decltype(value)>;
if constexpr (std::same_as<T, std::monostate>) {
return JsonValue{nullptr};
} else if constexpr (std::same_as<T, std::int64_t>) {
return JsonValue{value};
} else {
return JsonValue{value};
}
},
id.value);
}
[[nodiscard]] Void::Result::Result<JsonRpcId>
decode_id(const JsonValue& value)
{
if (std::holds_alternative<std::nullptr_t>(value.value)) {
return JsonRpcId{};
}
if (const auto* number = as_integer(value); number != nullptr) {
return JsonRpcId{*number};
}
if (const auto* text = as_string(value); text != nullptr) {
return JsonRpcId{*text};
}
return std::unexpected{invalid(
"MCP: JSON-RPC id must be null, an integer, or a string")};
}
[[nodiscard]] Void::Result::Result<JsonValue>
merge_metadata(std::optional<JsonValue> params,
const RequestMetadata& metadata,
const McpLimits& limits)
{
auto meta = metadata_to_json(metadata, limits);
if (!meta.has_value()) {
return std::unexpected{std::move(meta.error())};
}
Object object;
if (params.has_value()) {
if (const auto* existing = as_object(*params);
existing != nullptr) {
object = *existing;
} else if (!std::holds_alternative<std::nullptr_t>(
params->value)) {
return std::unexpected{invalid(
"MCP: params must be an object when present")};
}
}
object[std::string{"_meta"}] = std::move(*meta);
return JsonValue{std::move(object)};
}
[[nodiscard]] JsonValue encode_error(const ErrorObject& error)
{
Object object;
object["code"] = JsonValue{static_cast<std::int64_t>(error.code)};
object["message"] = JsonValue{error.message};
if (error.data.has_value()) {
object["data"] = *error.data;
}
return JsonValue{std::move(object)};
}
[[nodiscard]] Void::Result::Result<ErrorObject>
decode_error(const JsonValue& value)
{
const auto* object = as_object(value);
if (object == nullptr) {
return std::unexpected{invalid(
"MCP: JSON-RPC error must be an object")};
}
const auto code_it = object->find("code");
const auto message_it = object->find("message");
if (code_it == object->end() || message_it == object->end()) {
return std::unexpected{invalid(
"MCP: JSON-RPC error requires code and message")};
}
const auto* code = as_integer(code_it->second);
const auto* message = as_string(message_it->second);
if (code == nullptr || message == nullptr ||
*code < INT32_MIN || *code > INT32_MAX) {
return std::unexpected{invalid(
"MCP: malformed JSON-RPC error code or message")};
}
ErrorObject error;
error.code = static_cast<std::int32_t>(*code);
error.message = *message;
if (const auto data_it = object->find("data");
data_it != object->end()) {
error.data = data_it->second;
}
return error;
}
[[nodiscard]] Void::Result::Result<RequestMetadata>
parse_meta_object(const JsonValue& meta, const McpLimits& limits)
{
const auto* object = as_object(meta);
if (object == nullptr) {
return std::unexpected{make_mcp_error(
McpErrorCode::invalid_params,
"MCP: _meta must be an object")};
}
RequestMetadata metadata;
std::size_t entries = 0;
for (const auto& [key, value] : *object) {
++entries;
if (entries > limits.max_metadata_entries) {
return std::unexpected{make_mcp_error(
McpErrorCode::payload_too_large,
std::format("MCP: _meta exceeds {} entries",
limits.max_metadata_entries))};
}
if (key == kMetaProtocolVersion) {
const auto* text = as_string(value);
if (text == nullptr ||
text->size() >
limits.max_metadata_value_bytes) {
return std::unexpected{make_mcp_error(
McpErrorCode::invalid_params,
"MCP: protocolVersion must be a bounded string")};
}
metadata.protocol_version = *text;
} else if (key == kMetaClientInfo) {
const auto* info = as_object(value);
if (info == nullptr) {
return std::unexpected{make_mcp_error(
McpErrorCode::invalid_params,
"MCP: clientInfo must be an object")};
}
if (const auto name = info->find("name");
name != info->end()) {
if (const auto* text = as_string(name->second);
text != nullptr) {
metadata.client_info.name = *text;
}
}
if (const auto version = info->find("version");
version != info->end()) {
if (const auto* text = as_string(version->second);
text != nullptr) {
metadata.client_info.version = *text;
}
}
} else if (key == kMetaClientCapabilities) {
auto text = serialize_value(value, limits);
if (!text.has_value()) {
return std::unexpected{
std::move(text.error())};
}
metadata.client_capabilities_json = std::move(*text);
} else if (key == kMetaProgressToken) {
if (const auto* text = as_string(value);
text != nullptr) {
metadata.progress_token = *text;
}
} else if (key == kMetaSubscriptionId) {
if (const auto* text = as_string(value);
text != nullptr) {
metadata.subscription_id = *text;
}
} else if (const auto* text = as_string(value);
text != nullptr) {
if (key.size() > limits.max_metadata_value_bytes ||
text->size() > limits.max_metadata_value_bytes) {
return std::unexpected{make_mcp_error(
McpErrorCode::payload_too_large,
"MCP: _meta entry exceeds size limit")};
}
metadata.extra.push_back({key, *text});
}
}
return metadata;
}
} // namespace
Void::Result::Result<std::string>
encode_json(const JsonValue& value, const McpLimits& limits)
{
return serialize_value(value, limits);
}
Void::Result::Result<JsonValue>
decode_json(std::string_view text, const McpLimits& limits)
{
if (text.size() > limits.max_message_bytes) {
return std::unexpected{make_mcp_error(
McpErrorCode::payload_too_large,
std::format("MCP: message {} bytes exceeds {}",
text.size(), limits.max_message_bytes))};
}
auto value = Void::Json::Strict::parse(
text, Void::Json::Strict::ParseOptions{
.maximumDepth = limits.max_json_depth,
.allowDecimals = true});
if (!value.has_value()) {
return std::unexpected{make_mcp_error(
McpErrorCode::parse_error,
std::format("MCP: invalid JSON at {}: {}",
value.error().offset, value.error().message))};
}
return std::move(*value);
}
Void::Result::Result<RequestMetadata>
parse_metadata(const JsonValue& params, const McpLimits& limits)
{
const auto* object = as_object(params);
if (object == nullptr) {
return RequestMetadata{};
}
const auto meta = object->find("_meta");
if (meta == object->end()) {
return RequestMetadata{};
}
return parse_meta_object(meta->second, limits);
}
Void::Result::Result<JsonValue>
metadata_to_json(const RequestMetadata& metadata,
const McpLimits& limits)
{
if (metadata.protocol_version.size() >
limits.max_metadata_value_bytes) {
return std::unexpected{make_mcp_error(
McpErrorCode::payload_too_large,
"MCP: protocol version exceeds metadata limit")};
}
Object meta;
meta[std::string{kMetaProtocolVersion}] =
JsonValue{metadata.protocol_version};
if (!metadata.client_info.name.empty() ||
!metadata.client_info.version.empty()) {
Object info;
info["name"] = JsonValue{metadata.client_info.name};
info["version"] = JsonValue{metadata.client_info.version};
meta[std::string{kMetaClientInfo}] =
JsonValue{std::move(info)};
}
if (!metadata.client_capabilities_json.empty()) {
auto capabilities =
decode_json(metadata.client_capabilities_json, limits);
if (!capabilities.has_value()) {
return std::unexpected{std::move(capabilities.error())};
}
if (as_object(*capabilities) == nullptr) {
return std::unexpected{make_mcp_error(
McpErrorCode::invalid_params,
"MCP: clientCapabilities must be a JSON object")};
}
meta[std::string{kMetaClientCapabilities}] =
std::move(*capabilities);
}
if (metadata.progress_token.has_value()) {
meta[std::string{kMetaProgressToken}] =
JsonValue{*metadata.progress_token};
}
if (metadata.subscription_id.has_value()) {
meta[std::string{kMetaSubscriptionId}] =
JsonValue{*metadata.subscription_id};
}
if (metadata.extra.size() > limits.max_metadata_entries) {
return std::unexpected{make_mcp_error(
McpErrorCode::payload_too_large,
"MCP: too many metadata entries")};
}
for (const auto& entry : metadata.extra) {
if (entry.key.size() > limits.max_metadata_value_bytes ||
entry.value.size() > limits.max_metadata_value_bytes) {
return std::unexpected{make_mcp_error(
McpErrorCode::payload_too_large,
"MCP: metadata entry exceeds size limit")};
}
meta[entry.key] = JsonValue{entry.value};
}
return JsonValue{std::move(meta)};
}
Void::Result::Result<std::string>
encode_message(const Message& message, const McpLimits& limits)
{
Object object;
object["jsonrpc"] = JsonValue{std::string{kJsonRpcVersion}};
if (const auto* request = std::get_if<Request>(&message);
request != nullptr) {
object["id"] = encode_id(request->id);
object["method"] = JsonValue{request->method};
auto params = merge_metadata(request->params,
request->metadata, limits);
if (!params.has_value()) {
return std::unexpected{std::move(params.error())};
}
object["params"] = std::move(*params);
} else if (const auto* notification =
std::get_if<Notification>(&message);
notification != nullptr) {
object["method"] = JsonValue{notification->method};
auto params = merge_metadata(notification->params,
notification->metadata, limits);
if (!params.has_value()) {
return std::unexpected{std::move(params.error())};
}
object["params"] = std::move(*params);
} else {
const auto& response = std::get<Response>(message);
object["id"] = encode_id(response.id);
if (response.error.has_value() &&
response.result.has_value()) {
return std::unexpected{invalid(
"MCP: response cannot carry both result and error")};
}
if (response.error.has_value()) {
object["error"] = encode_error(*response.error);
} else if (response.result.has_value()) {
object["result"] = *response.result;
} else {
return std::unexpected{invalid(
"MCP: response requires result or error")};
}
}
return serialize_value(JsonValue{std::move(object)}, limits);
}
Void::Result::Result<Message>
decode_message(std::string_view text, const McpLimits& limits)
{
auto value = decode_json(text, limits);
if (!value.has_value()) {
return std::unexpected{std::move(value.error())};
}
const auto* object = as_object(*value);
if (object == nullptr) {
return std::unexpected{invalid(
"MCP: JSON-RPC message must be an object")};
}
const auto version = object->find("jsonrpc");
if (version == object->end() ||
as_string(version->second) == nullptr ||
*as_string(version->second) != kJsonRpcVersion) {
return std::unexpected{invalid(
"MCP: jsonrpc must be \"2.0\"")};
}
const auto method = object->find("method");
const auto id = object->find("id");
if (method != object->end()) {
if (object->contains("result") || object->contains("error")) {
return std::unexpected{invalid(
"MCP: message cannot mix method with result/error")};
}
const auto* method_text = as_string(method->second);
if (method_text == nullptr || method_text->empty() ||
method_text->size() > limits.max_metadata_value_bytes) {
return std::unexpected{invalid(
"MCP: method must be a bounded non-empty string")};
}
std::optional<JsonValue> params;
if (const auto params_it = object->find("params");
params_it != object->end()) {
if (as_object(params_it->second) == nullptr) {
return std::unexpected{invalid(
"MCP: params must be an object when present")};
}
params = params_it->second;
}
RequestMetadata metadata;
if (params.has_value()) {
auto parsed = parse_metadata(*params, limits);
if (!parsed.has_value()) {
return std::unexpected{std::move(parsed.error())};
}
metadata = std::move(*parsed);
}
if (id != object->end()) {
auto decoded_id = decode_id(id->second);
if (!decoded_id.has_value()) {
return std::unexpected{
std::move(decoded_id.error())};
}
return Request{std::move(*decoded_id),
std::move(*method_text),
std::move(params), std::move(metadata)};
}
return Notification{std::move(*method_text),
std::move(params), std::move(metadata)};
}
if (id == object->end()) {
return std::unexpected{invalid(
"MCP: response requires an id")};
}
auto decoded_id = decode_id(id->second);
if (!decoded_id.has_value()) {
return std::unexpected{std::move(decoded_id.error())};
}
const auto result = object->find("result");
const auto error = object->find("error");
if (result != object->end() && error != object->end()) {
return std::unexpected{invalid(
"MCP: response cannot carry both result and error")};
}
if (result != object->end()) {
return Response{std::move(*decoded_id), result->second,
std::nullopt};
}
if (error != object->end()) {
auto decoded_error = decode_error(error->second);
if (!decoded_error.has_value()) {
return std::unexpected{
std::move(decoded_error.error())};
}
return Response{std::move(*decoded_id), std::nullopt,
std::move(*decoded_error)};
}
return std::unexpected{invalid(
"MCP: response requires result or error")};
}
Response make_error_response(const JsonRpcId& id, std::int32_t code,
std::string message,
std::optional<JsonValue> data)
{
Response response;
response.id = id;
response.error =
ErrorObject{code, std::move(message), std::move(data)};
return response;
}
} // namespace Void::MCP
+170
View File
@@ -0,0 +1,170 @@
#include <Void/MCP/Transport.hpp>
#include <Void/MCP/Envelope.hpp>
#include <algorithm>
#include <atomic>
#include <format>
#include <map>
#include <string>
#include <utility>
#include <variant>
namespace Void::MCP
{
namespace
{
[[nodiscard]] std::string default_session_id()
{
static std::atomic<std::uint64_t> counter{1};
return std::format("mcp-session-{}",
counter.fetch_add(1,
std::memory_order_relaxed));
}
[[nodiscard]] const JsonValue::Object*
as_object(const JsonValue& value) noexcept
{
return std::get_if<JsonValue::Object>(&value.value);
}
[[nodiscard]] std::string
param_string(const Request& request, std::string_view key)
{
if (!request.params.has_value()) {
return {};
}
const auto* object = as_object(*request.params);
if (object == nullptr) {
return {};
}
const auto field = object->find(key);
if (field == object->end()) {
return {};
}
if (const auto* text = std::get_if<std::string>(&field->second.value);
text != nullptr) {
return *text;
}
return {};
}
[[nodiscard]] bool contains(const std::vector<std::string>& values,
std::string_view wanted) noexcept
{
return std::ranges::any_of(values, [&](const std::string& value) {
return value == wanted;
});
}
} // namespace
struct LegacySessionAdapter::Impl {
LegacySessionOptions options;
std::map<std::string, LegacySession, std::less<>> sessions;
Impl() = default;
};
LegacySessionAdapter::LegacySessionAdapter(LegacySessionOptions options)
: m_impl(std::make_unique<Impl>())
{
m_impl->options = std::move(options);
if (m_impl->options.supported_versions.empty()) {
m_impl->options.supported_versions.push_back("2025-11-25");
}
if (!m_impl->options.session_id_factory) {
m_impl->options.session_id_factory = default_session_id;
}
}
LegacySessionAdapter::~LegacySessionAdapter() = default;
Void::Result::Result<std::optional<Message>>
LegacySessionAdapter::handle(const Message& inbound,
std::string_view session_id)
{
auto& impl = *m_impl;
if (const auto* request = std::get_if<Request>(&inbound);
request != nullptr) {
if (request->method == "initialize") {
if (!session_id.empty() &&
impl.sessions.contains(session_id)) {
return std::unexpected{make_mcp_error(
McpErrorCode::invalid_request,
"MCP: session is already initialized")};
}
const std::string requested =
param_string(*request, "protocolVersion");
const std::string negotiated =
contains(impl.options.supported_versions, requested)
? requested
: impl.options.supported_versions.front();
LegacySession session;
session.id = impl.options.session_id_factory();
session.protocol_version = negotiated;
impl.sessions.emplace(session.id, session);
JsonValue::Object capabilities;
JsonValue::Object server_info;
server_info["name"] =
JsonValue{impl.options.server_name};
server_info["version"] =
JsonValue{impl.options.server_version};
JsonValue::Object result;
result["protocolVersion"] = JsonValue{negotiated};
result["capabilities"] =
JsonValue{std::move(capabilities)};
result["serverInfo"] = JsonValue{std::move(server_info)};
return std::optional<Message>{Response{
request->id, JsonValue{std::move(result)},
std::nullopt}};
}
const auto session = impl.sessions.find(session_id);
if (session == impl.sessions.end() ||
!session->second.initialized) {
return std::unexpected{make_mcp_error(
McpErrorCode::session_not_found,
"MCP: no initialized legacy session")};
}
return std::optional<Message>{inbound};
}
if (const auto* notification = std::get_if<Notification>(&inbound);
notification != nullptr) {
if (notification->method == "initialized") {
const auto session = impl.sessions.find(session_id);
if (session == impl.sessions.end()) {
return std::unexpected{make_mcp_error(
McpErrorCode::session_not_found,
"MCP: initialized without a legacy session")};
}
session->second.initialized = true;
}
return std::optional<Message>{};
}
return std::optional<Message>{};
}
const LegacySession*
LegacySessionAdapter::find(std::string_view session_id) const
{
const auto session =
m_impl->sessions.find(std::string{session_id});
if (session == m_impl->sessions.end()) {
return nullptr;
}
return &session->second;
}
bool LegacySessionAdapter::terminate(std::string_view session_id)
{
return m_impl->sessions.erase(std::string{session_id}) > 0;
}
std::size_t LegacySessionAdapter::session_count() const
{
return m_impl->sessions.size();
}
} // namespace Void::MCP
+729
View File
@@ -0,0 +1,729 @@
#include <Void/MCP/Transport.hpp>
#include <Void/MCP/Codec.hpp>
#include <Void/MCP/Envelope.hpp>
#include <algorithm>
#include <array>
#include <cerrno>
#include <chrono>
#include <cstring>
#include <format>
#include <limits>
#include <string>
#include <utility>
#include <variant>
#if defined(_WIN32)
#include <io.h>
#else
#include <fcntl.h>
#include <poll.h>
#include <unistd.h>
#endif
namespace Void::MCP
{
namespace
{
[[nodiscard]] bool ascii_iequals(std::string_view left,
std::string_view right) noexcept
{
if (left.size() != right.size()) {
return false;
}
for (std::size_t index = 0; index < left.size(); ++index) {
const auto a = static_cast<unsigned char>(left[index]);
const auto b = static_cast<unsigned char>(right[index]);
if (std::tolower(a) != std::tolower(b)) {
return false;
}
}
return true;
}
[[nodiscard]] std::string_view trim(std::string_view text) noexcept
{
constexpr std::string_view whitespace = " \t";
const auto begin = text.find_first_not_of(whitespace);
if (begin == std::string_view::npos) {
return {};
}
const auto end = text.find_last_not_of(whitespace);
return text.substr(begin, end - begin + 1U);
}
/// Whether a comma-separated header list contains `token` (media
/// type parameters are ignored).
[[nodiscard]] bool
contains_token(std::string_view list, std::string_view token)
{
std::size_t begin = 0;
while (begin <= list.size()) {
const std::size_t comma = list.find(',', begin);
std::string_view item =
comma == std::string_view::npos
? list.substr(begin)
: list.substr(begin, comma - begin);
const std::size_t semicolon = item.find(';');
if (semicolon != std::string_view::npos) {
item = item.substr(0, semicolon);
}
if (ascii_iequals(trim(item), token)) {
return true;
}
if (comma == std::string_view::npos) {
break;
}
begin = comma + 1U;
}
return false;
}
[[nodiscard]] const JsonValue::Object*
as_object(const JsonValue& value) noexcept
{
return std::get_if<JsonValue::Object>(&value.value);
}
[[nodiscard]] const std::string*
as_string(const JsonValue& value) noexcept
{
return std::get_if<std::string>(&value.value);
}
[[nodiscard]] HttpResponse json_response(int status,
const Message& message,
const McpLimits& limits)
{
HttpResponse response;
response.status = status;
response.headers.push_back(
{"Content-Type", std::string{kJsonContentType}});
auto encoded = encode_message(message, limits);
if (encoded.has_value()) {
response.body = std::move(*encoded);
} else {
response.status = 500;
response.body = "{\"jsonrpc\":\"2.0\",\"id\":null,"
"\"error\":{\"code\":-32603,\"message\":"
"\"failed to encode error response\"}}";
}
return response;
}
[[nodiscard]] HttpResponse
error_response(int status, const JsonRpcId& id,
McpErrorCode code, std::string message,
const McpLimits& limits,
std::optional<JsonValue> data = {})
{
return json_response(
status,
make_error_response(id, json_rpc_error_code(code),
std::move(message), std::move(data)),
limits);
}
[[nodiscard]] std::optional<std::string>
request_name(const Request& request)
{
if (!request.params.has_value()) {
return std::nullopt;
}
const auto* object = as_object(*request.params);
if (object == nullptr) {
return std::nullopt;
}
const auto field =
request.method == "resources/read"
? object->find("uri")
: object->find("name");
if (field == object->end()) {
return std::nullopt;
}
if (const auto* text = as_string(field->second);
text != nullptr) {
return *text;
}
return std::nullopt;
}
[[nodiscard]] bool method_requires_name(std::string_view method) noexcept
{
return method == "tools/call" || method == "resources/read" ||
method == "prompts/get";
}
[[nodiscard]] RequestMetadata message_metadata(const Message& message)
{
if (const auto* request = std::get_if<Request>(&message);
request != nullptr) {
return request->metadata;
}
if (const auto* notification = std::get_if<Notification>(&message);
notification != nullptr) {
return notification->metadata;
}
return {};
}
[[nodiscard]] JsonRpcId message_id(const Message& message)
{
if (const auto* request = std::get_if<Request>(&message);
request != nullptr) {
return request->id;
}
return {};
}
[[nodiscard]] JsonRpcId
parse_id_from_body(std::string_view body) noexcept
{
// Best-effort id extraction for transport-level errors; the full
// message is parsed by the caller when it is valid.
const auto position = body.find("\"id\"");
if (position == std::string_view::npos) {
return {};
}
std::size_t index = position + 4U;
while (index < body.size() &&
(body[index] == ' ' || body[index] == '\t' ||
body[index] == ':')) {
++index;
}
if (index >= body.size()) {
return {};
}
if (body[index] == '"') {
const auto end = body.find('"', index + 1U);
if (end == std::string_view::npos) {
return {};
}
return JsonRpcId{
std::string{body.substr(index + 1U, end - index - 1U)}};
}
std::int64_t number = 0;
const char* begin = body.data() + index;
const auto parsed = std::from_chars(begin, body.data() + body.size(),
number);
if (parsed.ec != std::errc{}) {
return {};
}
return JsonRpcId{number};
}
#if !defined(_WIN32)
[[nodiscard]] std::chrono::milliseconds
remaining(std::chrono::steady_clock::time_point deadline) noexcept
{
const auto left = deadline - std::chrono::steady_clock::now();
if (left <= std::chrono::steady_clock::duration::zero()) {
return std::chrono::milliseconds{0};
}
return std::chrono::duration_cast<std::chrono::milliseconds>(
left);
}
[[nodiscard]] Void::Result::Result<void>
wait_fd(int fd, short events,
std::chrono::milliseconds timeout, std::stop_token stop,
std::string_view operation)
{
const auto deadline =
std::chrono::steady_clock::now() + timeout;
for (;;) {
if (stop.stop_requested()) {
return std::unexpected{make_mcp_error(
McpErrorCode::cancelled,
std::format("MCP: stdio {} cancelled",
operation))};
}
auto wait = remaining(deadline);
if (timeout.count() > 0 && wait.count() == 0) {
return std::unexpected{make_mcp_error(
McpErrorCode::timeout,
std::format("MCP: stdio {} timed out",
operation))};
}
if (stop.stop_possible() &&
(wait.count() == 0 || wait.count() > 50)) {
wait = std::chrono::milliseconds{50};
}
pollfd descriptor{
.fd = fd, .events = events, .revents = 0};
const int rc = ::poll(&descriptor, 1,
timeout.count() > 0
? static_cast<int>(wait.count())
: -1);
if (rc < 0) {
if (errno == EINTR) {
continue;
}
return std::unexpected{make_mcp_error(
McpErrorCode::protocol_error,
std::format("MCP: stdio poll failed: {}",
std::strerror(errno)))};
}
if (rc > 0) {
return {};
}
}
}
#endif
[[nodiscard]] Void::Result::Result<std::size_t>
fd_read(int fd, std::span<std::byte> destination)
{
#if defined(_WIN32)
const int rc = ::_read(fd, destination.data(),
static_cast<unsigned int>(
std::min<std::size_t>(
destination.size(), INT_MAX)));
#else
const ssize_t rc = ::read(fd, destination.data(),
destination.size());
#endif
if (rc < 0) {
return std::unexpected{make_mcp_error(
McpErrorCode::protocol_error,
std::format("MCP: stdio read failed: {}",
std::strerror(errno)))};
}
return static_cast<std::size_t>(rc);
}
[[nodiscard]] Void::Result::Result<void>
write_all_fd(int fd, std::string_view data,
std::chrono::milliseconds timeout,
std::stop_token stop)
{
bool nonblocking = false;
#if !defined(_WIN32)
const int flags = ::fcntl(fd, F_GETFL, 0);
nonblocking = flags >= 0 && (flags & O_NONBLOCK) != 0;
#endif
while (!data.empty()) {
if (stop.stop_requested()) {
return std::unexpected{make_mcp_error(
McpErrorCode::cancelled,
"MCP: stdio write cancelled")};
}
#if !defined(_WIN32)
if (nonblocking) {
auto waited =
wait_fd(fd, POLLOUT, timeout, stop, "write");
if (!waited.has_value()) {
return std::unexpected{
std::move(waited.error())};
}
}
#endif
const std::size_t chunk =
std::min<std::size_t>(data.size(), 4096U);
#if defined(_WIN32)
const int rc = ::_write(
fd, data.data(), static_cast<unsigned int>(chunk));
#else
const ssize_t rc = ::write(fd, data.data(), chunk);
#endif
if (rc < 0) {
if (errno == EINTR) {
continue;
}
if (errno == EAGAIN || errno == EWOULDBLOCK) {
continue;
}
return std::unexpected{make_mcp_error(
McpErrorCode::transport_closed,
std::format("MCP: stdio write failed: {}",
std::strerror(errno)))};
}
data.remove_prefix(static_cast<std::size_t>(rc));
}
return {};
}
} // namespace
std::optional<std::string_view>
header_value(const HttpRequest& request, std::string_view name)
{
for (const auto& header : request.headers) {
if (ascii_iequals(header.name, name)) {
return header.value;
}
}
return std::nullopt;
}
struct StreamableHttpEndpoint::Impl {
RequestHandler requests;
NotificationHandler notifications;
StreamableHttpOptions options;
Impl(RequestHandler request_handler,
NotificationHandler notification_handler,
StreamableHttpOptions opts)
: requests(std::move(request_handler)),
notifications(std::move(notification_handler)),
options(std::move(opts))
{
}
};
StreamableHttpEndpoint::StreamableHttpEndpoint(
RequestHandler requests, NotificationHandler notifications,
StreamableHttpOptions options)
: m_impl(std::make_unique<Impl>(std::move(requests),
std::move(notifications),
std::move(options)))
{
}
StreamableHttpEndpoint::~StreamableHttpEndpoint() = default;
HttpResponse StreamableHttpEndpoint::handle(
const HttpRequest& request) const
{
const auto& options = m_impl->options;
const auto& limits = options.limits;
if (request.method != "POST") {
return error_response(
405, JsonRpcId{}, McpErrorCode::method_not_allowed,
"MCP: 2026-07-28 Streamable HTTP accepts POST only", limits);
}
const auto content_type = header_value(request, "Content-Type");
if (!content_type.has_value() ||
!contains_token(*content_type, kJsonContentType)) {
return error_response(
415, JsonRpcId{}, McpErrorCode::unsupported_media_type,
"MCP: Content-Type must be application/json", limits);
}
const auto accept = header_value(request, "Accept");
if (!accept.has_value() ||
!contains_token(*accept, kJsonContentType) ||
!contains_token(*accept, kSseContentType)) {
return error_response(
406, JsonRpcId{}, McpErrorCode::not_acceptable,
"MCP: Accept must list application/json and "
"text/event-stream",
limits);
}
if (options.authorize) {
auto authorized = options.authorize(request);
if (!authorized.has_value()) {
return error_response(
401, JsonRpcId{}, McpErrorCode::unauthorized,
"MCP: authorization failed", limits);
}
} else if (options.require_authorization) {
return error_response(
401, JsonRpcId{}, McpErrorCode::unauthorized,
"MCP: authorization is required", limits);
}
if (request.body.size() > limits.max_message_bytes) {
return error_response(
413, JsonRpcId{}, McpErrorCode::payload_too_large,
"MCP: request body exceeds message limit", limits);
}
auto message = decode_message(request.body, limits);
if (!message.has_value()) {
return error_response(
400, parse_id_from_body(request.body),
McpErrorCode::parse_error, message.error().message(),
limits);
}
if (std::holds_alternative<Response>(*message)) {
return error_response(
400, message_id(*message), McpErrorCode::invalid_request,
"MCP: clients must not POST JSON-RPC responses", limits);
}
const RequestMetadata metadata = message_metadata(*message);
const auto protocol_header =
header_value(request, kProtocolHeader);
if (!protocol_header.has_value() ||
*protocol_header != metadata.protocol_version) {
return error_response(
400, message_id(*message), McpErrorCode::header_mismatch,
"MCP: MCP-Protocol-Version header missing or does not "
"match _meta",
limits);
}
const bool version_supported = std::ranges::any_of(
options.supported_versions,
[&](const std::string& version) {
return version == metadata.protocol_version;
});
if (!version_supported) {
JsonValue::Object data;
JsonValue::Array supported;
for (const auto& version : options.supported_versions) {
supported.push_back(JsonValue{version});
}
data["supported"] = JsonValue{std::move(supported)};
data["requested"] = JsonValue{metadata.protocol_version};
return error_response(
400, message_id(*message),
McpErrorCode::unsupported_protocol_version,
"MCP: unsupported protocol version", limits,
JsonValue{std::move(data)});
}
const std::string method =
std::holds_alternative<Request>(*message)
? std::get<Request>(*message).method
: std::get<Notification>(*message).method;
const auto method_header = header_value(request, kMethodHeader);
if (!method_header.has_value() || *method_header != method) {
return error_response(
400, message_id(*message), McpErrorCode::header_mismatch,
"MCP: Mcp-Method header missing or does not match the "
"body method",
limits);
}
if (method_requires_name(method)) {
const auto& request_message = std::get<Request>(*message);
const auto name = request_name(request_message);
const auto name_header = header_value(request, kNameHeader);
if (!name.has_value() || !name_header.has_value() ||
*name_header != *name) {
return error_response(
400, message_id(*message),
McpErrorCode::header_mismatch,
"MCP: Mcp-Name header missing or does not match the "
"body",
limits);
}
}
if (const auto* notification = std::get_if<Notification>(&*message)) {
auto accepted =
m_impl->notifications
? m_impl->notifications(*notification)
: Void::Result::Result<void>{};
if (!accepted.has_value()) {
return error_response(
400, JsonRpcId{}, McpErrorCode::invalid_request,
accepted.error().message(), limits);
}
HttpResponse response;
response.status = 202;
return response;
}
const auto& request_message = std::get<Request>(*message);
auto handled =
m_impl->requests
? m_impl->requests(request_message)
: Void::Result::Result<Message>{std::unexpected{
make_mcp_error(McpErrorCode::method_not_found,
"MCP: no request handler")}};
if (!handled.has_value()) {
const auto& error = handled.error();
const auto code =
error.code().domain == kMcpErrorDomain
? static_cast<McpErrorCode>(error.code().value)
: McpErrorCode::internal_error;
return json_response(
200,
make_error_response(request_message.id,
json_rpc_error_code(code),
error.message()),
limits);
}
auto encoded = encode_message(*handled, limits);
if (!encoded.has_value()) {
return error_response(
500, request_message.id, McpErrorCode::internal_error,
encoded.error().message(), limits);
}
HttpResponse response;
response.status = 200;
if (options.prefer_sse) {
response.headers.push_back(
{"Content-Type", std::string{kSseContentType}});
auto event = encode_sse_event(
SseEvent{.event = "message", .data = std::move(*encoded)},
limits);
if (!event.has_value()) {
return error_response(
500, request_message.id,
McpErrorCode::payload_too_large,
event.error().message(), limits);
}
response.body = std::move(*event);
} else {
response.headers.push_back(
{"Content-Type", std::string{kJsonContentType}});
response.body = std::move(*encoded);
}
return response;
}
struct StdioTransport::Impl {
int read_fd{-1};
int write_fd{-1};
RequestHandler requests;
NotificationHandler notifications;
McpLimits limits;
std::chrono::milliseconds io_timeout;
LineFramer framer;
Impl(int reader, int writer, RequestHandler request_handler,
NotificationHandler notification_handler, McpLimits
transport_limits,
std::chrono::milliseconds timeout)
: read_fd(reader), write_fd(writer),
requests(std::move(request_handler)),
notifications(std::move(notification_handler)),
limits(std::move(transport_limits)), io_timeout(timeout),
framer(limits)
{
}
};
StdioTransport::StdioTransport(int read_fd, int write_fd,
RequestHandler requests,
NotificationHandler notifications,
McpLimits limits,
std::chrono::milliseconds io_timeout)
: m_impl(std::make_unique<Impl>(
read_fd, write_fd, std::move(requests),
std::move(notifications), std::move(limits), io_timeout))
{
}
StdioTransport::~StdioTransport() = default;
Void::Result::Result<std::optional<Message>>
StdioTransport::read_message(std::stop_token stop)
{
auto& impl = *m_impl;
for (;;) {
if (stop.stop_requested()) {
return std::unexpected{make_mcp_error(
McpErrorCode::cancelled, "MCP: stdio read cancelled")};
}
auto line = impl.framer.next();
if (!line.has_value()) {
return std::unexpected{std::move(line.error())};
}
if (line->has_value()) {
auto message =
decode_message(**line, impl.limits);
if (!message.has_value()) {
return std::unexpected{
std::move(message.error())};
}
return std::optional<Message>{std::move(*message)};
}
std::array<std::byte, 8192> buffer{};
auto count = fd_read(impl.read_fd, buffer);
if (!count.has_value()) {
#if !defined(_WIN32)
if (errno == EAGAIN || errno == EWOULDBLOCK) {
auto waited = wait_fd(impl.read_fd, POLLIN,
impl.io_timeout, stop, "read");
if (!waited.has_value()) {
return std::unexpected{
std::move(waited.error())};
}
continue;
}
#endif
return std::unexpected{std::move(count.error())};
}
if (*count == 0) {
if (impl.framer.buffered() > 0) {
return std::unexpected{make_mcp_error(
McpErrorCode::protocol_error,
"MCP: stdio stream ended mid-frame")};
}
return std::optional<Message>{};
}
auto appended = impl.framer.append(std::string_view{
reinterpret_cast<const char*>(buffer.data()), *count});
if (!appended.has_value()) {
return std::unexpected{std::move(appended.error())};
}
}
}
Void::Result::Result<void>
StdioTransport::write_message(const Message& message,
std::stop_token stop)
{
auto& impl = *m_impl;
auto encoded = encode_message(message, impl.limits);
if (!encoded.has_value()) {
return std::unexpected{std::move(encoded.error())};
}
auto frame = frame_line(*encoded, impl.limits);
if (!frame.has_value()) {
return std::unexpected{std::move(frame.error())};
}
return write_all_fd(impl.write_fd, *frame, impl.io_timeout, stop);
}
Void::Result::Result<void> StdioTransport::run(std::stop_token stop)
{
for (;;) {
auto message = read_message(stop);
if (!message.has_value()) {
if (message.error().kind() ==
Void::Result::ErrorKind::cancelled) {
return {};
}
// Malformed frame: answer and keep reading.
auto error_response = make_error_response(
JsonRpcId{}, json_rpc_error_code(
McpErrorCode::parse_error),
message.error().message());
auto written = write_message(error_response, stop);
if (!written.has_value()) {
return std::unexpected{
std::move(written.error())};
}
continue;
}
if (!message->has_value()) {
return {};
}
Message inbound = std::move(**message);
if (const auto* request = std::get_if<Request>(&inbound)) {
auto handled =
m_impl->requests
? m_impl->requests(*request)
: Void::Result::Result<Message>{
std::unexpected{make_mcp_error(
McpErrorCode::method_not_found,
"MCP: no request handler")}};
if (!handled.has_value()) {
handled = make_error_response(
request->id,
json_rpc_error_code(McpErrorCode::internal_error),
handled.error().message());
}
auto written = write_message(*handled, stop);
if (!written.has_value()) {
return std::unexpected{
std::move(written.error())};
}
} else if (const auto* notification =
std::get_if<Notification>(&inbound)) {
if (m_impl->notifications) {
auto accepted =
m_impl->notifications(*notification);
if (!accepted.has_value()) {
return std::unexpected{
std::move(accepted.error())};
}
}
}
}
}
} // namespace Void::MCP
+3
View File
@@ -0,0 +1,3 @@
void_add_module(MCP
INTERNAL_DEPS Functional Data
)
+103 -1
View File
@@ -24,6 +24,19 @@
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#else
#ifndef NOMINMAX
#define NOMINMAX
#endif
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <fcntl.h>
#include <io.h>
#include <process.h>
#include <sys/stat.h>
#endif
#include <algorithm>
@@ -56,6 +69,26 @@ namespace Void::Net
std::atomic<std::uint64_t> g_dl_temp_seq{0};
#if defined(_WIN32)
// Win32 paths above MAX_PATH must use the extended-length prefix, and
// forward slashes are not accepted by the wide file APIs.
[[nodiscard]] std::filesystem::path
extended_path(const std::filesystem::path& path)
{
std::error_code ec;
const auto absolute = std::filesystem::absolute(path, ec);
std::wstring text = (ec ? path : absolute).wstring();
std::replace(text.begin(), text.end(), L'/', L'\\');
if (text.rfind(L"\\\\?\\", 0) == 0 || text.size() < MAX_PATH) {
return std::filesystem::path{text};
}
if (text.rfind(L"\\\\", 0) == 0) {
return std::filesystem::path{L"\\\\?\\UNC\\" + text.substr(2)};
}
return std::filesystem::path{L"\\\\?\\" + text};
}
#endif
[[nodiscard]] bool
equal_ascii_ci(std::string_view a, std::string_view b) noexcept
{
@@ -557,13 +590,26 @@ namespace Void::Net
}
const std::filesystem::path tmp_path =
parent / std::format(".void-dl-{}-{}",
#if defined(_WIN32)
static_cast<long long>(::_getpid()),
#else
static_cast<long long>(::getpid()),
#endif
g_dl_temp_seq.fetch_add(
1, std::memory_order_relaxed));
#if defined(_WIN32)
// Create exclusively next to the destination: an existing entry
// (including a reparse point) is never followed or truncated.
const int fd = ::_wopen(
extended_path(tmp_path).c_str(),
_O_WRONLY | _O_CREAT | _O_EXCL | _O_BINARY | _O_NOINHERIT,
_S_IREAD | _S_IWRITE);
#else
const int fd = ::open(
tmp_path.c_str(),
O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW,
0644);
#endif
if (fd < 0) {
return std::unexpected{make_net_error(
NetErrorCode::io_error,
@@ -593,10 +639,17 @@ namespace Void::Net
{
std::size_t off = 0;
while (off < data.size()) {
#if defined(_WIN32)
const int w = ::_write(
m_fd,
reinterpret_cast<const char*>(data.data()) + off,
static_cast<unsigned int>(data.size() - off));
#else
const ssize_t w = ::write(
m_fd,
reinterpret_cast<const char*>(data.data()) + off,
data.size() - off);
#endif
if (w < 0 && errno == EINTR) {
continue;
}
@@ -616,6 +669,50 @@ namespace Void::Net
[[nodiscard]] Void::Result::Result<void> commit()
{
#if defined(_WIN32)
if (::_commit(m_fd) != 0) {
return std::unexpected{make_net_error(
NetErrorCode::io_error,
std::format("Net: flush 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()})};
}
// Never replace a reparse point: a hostile workspace entry
// could redirect the completed download outside the target.
const DWORD attributes =
::GetFileAttributesW(extended_path(m_dest).c_str());
if (attributes != INVALID_FILE_ATTRIBUTES &&
(attributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0) {
discard();
return std::unexpected{make_net_error(
NetErrorCode::io_error,
"Net: refusing to replace a reparse-point "
"download destination")};
}
if (::MoveFileExW(extended_path(m_tmp).c_str(),
extended_path(m_dest).c_str(),
MOVEFILE_REPLACE_EXISTING |
MOVEFILE_WRITE_THROUGH) == 0) {
const DWORD error = ::GetLastError();
discard();
return std::unexpected{make_net_error(
NetErrorCode::io_error,
std::format("Net: replace download file failed: "
"win32={}",
error),
std::error_code{static_cast<int>(error),
std::system_category()})};
}
#else
if (::fsync(m_fd) != 0) {
return std::unexpected{make_net_error(
NetErrorCode::io_error,
@@ -639,9 +736,10 @@ namespace Void::Net
return std::unexpected{make_net_error(
NetErrorCode::io_error,
std::format("Net: rename download file failed: {}",
ec.message()),
ec.message()),
ec)};
}
#endif
m_committed = true;
return {};
}
@@ -649,7 +747,11 @@ namespace Void::Net
void discard() noexcept
{
if (m_fd >= 0) {
#if defined(_WIN32)
(void)::_close(m_fd);
#else
(void)::close(m_fd);
#endif
m_fd = -1;
}
if (!m_committed && !m_tmp.empty()) {
+770 -7
View File
@@ -867,6 +867,588 @@ namespace Void::Net
return written_total;
}
struct ResponseWriter::State {
int fd{-1};
const std::atomic<bool>* stopping{nullptr};
std::atomic<bool> cancel_requested{false};
std::atomic<bool> head_attempted{false};
std::atomic<bool> begun{false};
std::atomic<bool> finished{false};
std::atomic<bool> invalid{false};
std::atomic<bool> chunked{false};
std::atomic<bool> bodyless{false};
std::atomic<bool> fixed_length{false};
std::atomic<bool> close_delimited{false};
std::atomic<bool> has_content_length{false};
std::atomic<bool> keep_alive{true};
std::atomic<std::uint64_t> content_length{0};
std::atomic<std::uint64_t> accepted{0};
std::atomic<std::uint64_t> sent{0};
std::atomic<std::size_t> pending_bytes{0};
std::atomic<std::chrono::milliseconds::rep> write_timeout_ms{
std::chrono::seconds{30}.count()};
std::mutex io_mutex{};
std::string pending{};
std::size_t max_pending{64ULL * 1024};
bool head_request{false};
bool http10{false};
std::stop_source stop_source{};
[[nodiscard]] bool stopped() const noexcept
{
return cancel_requested.load(std::memory_order_acquire) ||
(stopping != nullptr &&
stopping->load(std::memory_order_acquire));
}
void request_stop() noexcept
{
(void)stop_source.request_stop();
}
};
namespace
{
[[nodiscard]] Void::Result::Result<void>
writer_send_all(ResponseWriter::State& state,
std::span<const std::byte> data)
{
const auto timeout = std::chrono::milliseconds{
state.write_timeout_ms.load(std::memory_order_acquire)};
const auto deadline = std::chrono::steady_clock::now() + timeout;
std::size_t off = 0;
while (off < data.size()) {
if (state.stopped()) {
state.request_stop();
return std::unexpected{make_net_error(
NetErrorCode::cancelled,
"Net::ResponseWriter: exchange cancelled")};
}
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::ResponseWriter: 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<int>(std::clamp<long long>(rem, 1, 100));
}
struct pollfd pfd{};
pfd.fd = state.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::ResponseWriter: poll failed")};
}
if (pr == 0) {
continue;
}
const ssize_t n = ::send(
state.fd,
reinterpret_cast<const char*>(data.data()) + off,
data.size() - off, MSG_NOSIGNAL);
if (n < 0) {
if (errno == EINTR || errno == EAGAIN ||
errno == EWOULDBLOCK) {
continue;
}
state.request_stop();
return std::unexpected{make_net_error(
NetErrorCode::io_error,
std::format("Net::ResponseWriter: send failed: {}",
std::strerror(errno)),
std::error_code{errno, std::generic_category()})};
}
if (n == 0) {
state.request_stop();
return std::unexpected{make_net_error(
NetErrorCode::io_error,
"Net::ResponseWriter: peer closed connection")};
}
off += static_cast<std::size_t>(n);
}
return {};
}
[[nodiscard]] Void::Result::Result<void>
writer_flush(ResponseWriter::State& state)
{
if (state.pending.empty()) {
return {};
}
auto res = writer_send_all(
state, std::as_bytes(std::span{state.pending.data(),
state.pending.size()}));
if (!res.has_value()) {
return std::unexpected{std::move(res.error())};
}
state.pending.clear();
state.pending_bytes.store(0, std::memory_order_release);
state.sent.store(state.accepted.load(std::memory_order_acquire),
std::memory_order_release);
return {};
}
[[nodiscard]] Void::Result::Result<void>
writer_require_active(const std::shared_ptr<ResponseWriter::State>& s)
{
if (!s || s->invalid.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: exchange is no longer active")};
}
return {};
}
} // namespace
bool ResponseWriter::valid() const noexcept
{
return m_state != nullptr &&
!m_state->invalid.load(std::memory_order_acquire);
}
bool ResponseWriter::begun() const noexcept
{
return m_state != nullptr &&
m_state->begun.load(std::memory_order_acquire);
}
bool ResponseWriter::finished() const noexcept
{
return m_state != nullptr &&
m_state->finished.load(std::memory_order_acquire);
}
bool ResponseWriter::cancelled() const noexcept
{
return m_state == nullptr ||
m_state->cancel_requested.load(std::memory_order_acquire) ||
(m_state->stopping != nullptr &&
m_state->stopping->load(std::memory_order_acquire));
}
bool ResponseWriter::chunked() const noexcept
{
return m_state != nullptr &&
m_state->chunked.load(std::memory_order_acquire);
}
std::optional<std::uint64_t> ResponseWriter::content_length() const noexcept
{
if (m_state == nullptr ||
!m_state->has_content_length.load(std::memory_order_acquire)) {
return std::nullopt;
}
return m_state->content_length.load(std::memory_order_acquire);
}
std::uint64_t ResponseWriter::bytes_accepted() const noexcept
{
return m_state != nullptr
? m_state->accepted.load(std::memory_order_acquire)
: 0;
}
std::uint64_t ResponseWriter::bytes_sent() const noexcept
{
return m_state != nullptr
? m_state->sent.load(std::memory_order_acquire)
: 0;
}
std::size_t ResponseWriter::buffered_bytes() const noexcept
{
return m_state != nullptr
? m_state->pending_bytes.load(std::memory_order_acquire)
: 0;
}
std::stop_token ResponseWriter::stop_token() const noexcept
{
return m_state != nullptr ? m_state->stop_source.get_token()
: std::stop_token{};
}
void ResponseWriter::cancel() noexcept
{
if (m_state) {
m_state->cancel_requested.store(true, std::memory_order_release);
m_state->request_stop();
}
}
void ResponseWriter::set_write_timeout(
std::chrono::milliseconds timeout) noexcept
{
if (m_state) {
m_state->write_timeout_ms.store(timeout.count(),
std::memory_order_release);
}
}
std::chrono::milliseconds ResponseWriter::write_timeout() const noexcept
{
return std::chrono::milliseconds{
m_state != nullptr
? m_state->write_timeout_ms.load(std::memory_order_acquire)
: std::chrono::seconds{30}.count()};
}
Void::Result::Result<void>
ResponseWriter::begin(std::uint16_t status, std::vector<Header> headers)
{
auto active = writer_require_active(m_state);
if (!active.has_value()) {
return active;
}
State& state = *m_state;
std::unique_lock lock{state.io_mutex, std::try_to_lock};
if (!lock.owns_lock()) {
return Void::Result::fail(
Void::Result::ErrorKind::overloaded,
"Net::ResponseWriter: concurrent writer");
}
if (state.invalid.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: exchange is no longer active")};
}
if (state.begun.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: response already started")};
}
if (state.stopped()) {
state.request_stop();
return std::unexpected{make_net_error(
NetErrorCode::cancelled,
"Net::ResponseWriter: exchange cancelled")};
}
if (status < 100 || status > 599) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: invalid status code")};
}
const bool bodyless = state.head_request ||
(status >= 100 && status < 200) || status == 204 ||
status == 304;
std::optional<std::uint64_t> content_length;
std::optional<std::string> transfer_encoding;
bool connection_close = false;
std::string extra_headers;
for (const auto& header : headers) {
if (!is_valid_token(header.name) ||
has_crlf_or_nul(header.name) ||
has_crlf_or_nul(header.value)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: invalid response header")};
}
if (equal_ascii_ci(header.name, "Content-Length")) {
std::uint64_t parsed = 0;
if (!parse_u64_decimal(trim_ows(header.value), parsed)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: invalid Content-Length")};
}
if (content_length.has_value() &&
*content_length != parsed) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: conflicting Content-Length")};
}
content_length = parsed;
continue;
}
if (equal_ascii_ci(header.name, "Transfer-Encoding")) {
if (transfer_encoding.has_value()) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: duplicate Transfer-Encoding")};
}
transfer_encoding = header.value;
continue;
}
if (equal_ascii_ci(header.name, "Connection")) {
if (contains_ascii_ci(header.value, "close")) {
connection_close = true;
}
continue;
}
extra_headers += header.name;
extra_headers += ": ";
extra_headers += header.value;
extra_headers += "\r\n";
}
if (transfer_encoding.has_value() &&
!equal_ascii_ci(trim_ows(*transfer_encoding), "chunked")) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: unsupported Transfer-Encoding")};
}
if (transfer_encoding.has_value() && content_length.has_value()) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: ambiguous response framing")};
}
if (bodyless && transfer_encoding.has_value()) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: bodyless response with "
"Transfer-Encoding")};
}
if (bodyless && content_length.has_value() && !state.head_request &&
status != 304) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: bodyless response with "
"Content-Length")};
}
bool chunked = false;
bool fixed = false;
bool close_delimited = false;
if (!bodyless) {
if (transfer_encoding.has_value()) {
chunked = true;
} else if (content_length.has_value()) {
fixed = true;
} else if (state.http10) {
close_delimited = true;
} else {
chunked = true;
}
}
bool keep = state.keep_alive.load(std::memory_order_acquire) &&
!close_delimited;
if (connection_close) {
keep = false;
}
std::string head =
std::format("HTTP/1.1 {} {}\r\n", status, reason_phrase(status));
head += extra_headers;
if (bodyless) {
if (content_length.has_value()) {
head += std::format("Content-Length: {}\r\n",
*content_length);
}
} else if (fixed) {
head += std::format("Content-Length: {}\r\n", *content_length);
} else if (chunked) {
head += "Transfer-Encoding: chunked\r\n";
}
head += std::format("Connection: {}\r\n\r\n",
keep ? "keep-alive" : "close");
state.head_attempted.store(true, std::memory_order_release);
auto sent_head = writer_send_all(
state, std::as_bytes(std::span{head.data(), head.size()}));
if (!sent_head.has_value()) {
return std::unexpected{std::move(sent_head.error())};
}
state.bodyless.store(bodyless, std::memory_order_release);
state.chunked.store(chunked, std::memory_order_release);
state.fixed_length.store(fixed, std::memory_order_release);
state.close_delimited.store(close_delimited,
std::memory_order_release);
state.keep_alive.store(keep, std::memory_order_release);
if (content_length.has_value()) {
state.content_length.store(*content_length,
std::memory_order_release);
state.has_content_length.store(true,
std::memory_order_release);
}
state.begun.store(true, std::memory_order_release);
return {};
}
Void::Result::Result<std::size_t>
ResponseWriter::write_some(std::span<const std::byte> bytes)
{
auto active = writer_require_active(m_state);
if (!active.has_value()) {
return std::unexpected{std::move(active.error())};
}
State& state = *m_state;
std::unique_lock lock{state.io_mutex, std::try_to_lock};
if (!lock.owns_lock()) {
return Void::Result::fail(
Void::Result::ErrorKind::overloaded,
"Net::ResponseWriter: concurrent writer");
}
if (state.invalid.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: exchange is no longer active")};
}
if (!state.begun.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: response not started")};
}
if (state.finished.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: response already finished")};
}
if (state.stopped()) {
state.request_stop();
return std::unexpected{make_net_error(
NetErrorCode::cancelled,
"Net::ResponseWriter: exchange cancelled")};
}
if (bytes.empty()) {
return std::size_t{0};
}
if (state.bodyless.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: bodyless response cannot carry a body")};
}
auto flushed = writer_flush(state);
if (!flushed.has_value()) {
return std::unexpected{std::move(flushed.error())};
}
const std::size_t max_pending = state.max_pending;
std::size_t capacity = max_pending;
if (state.chunked.load(std::memory_order_acquire)) {
// Leave room for the chunk size line and trailing CRLF.
capacity = max_pending > 32 ? max_pending - 32 : 1;
}
std::size_t accepted = std::min(bytes.size(), capacity);
if (accepted == 0) {
return std::size_t{0};
}
if (state.fixed_length.load(std::memory_order_acquire)) {
const std::uint64_t total =
state.content_length.load(std::memory_order_acquire);
const std::uint64_t written =
state.accepted.load(std::memory_order_acquire);
const std::uint64_t remaining =
total > written ? total - written : 0;
if (accepted > remaining) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: fixed-length body overflow")};
}
}
if (state.chunked.load(std::memory_order_acquire)) {
state.pending += std::format("{:x}\r\n", accepted);
state.pending.append(
reinterpret_cast<const char*>(bytes.data()), accepted);
state.pending += "\r\n";
} else {
state.pending.append(
reinterpret_cast<const char*>(bytes.data()), accepted);
}
state.pending_bytes.store(state.pending.size(),
std::memory_order_release);
state.accepted.fetch_add(accepted, std::memory_order_acq_rel);
auto after = writer_flush(state);
if (!after.has_value()) {
return std::unexpected{std::move(after.error())};
}
return accepted;
}
Void::Result::Result<void> ResponseWriter::finish()
{
auto active = writer_require_active(m_state);
if (!active.has_value()) {
return active;
}
State& state = *m_state;
std::unique_lock lock{state.io_mutex, std::try_to_lock};
if (!lock.owns_lock()) {
return Void::Result::fail(
Void::Result::ErrorKind::overloaded,
"Net::ResponseWriter: concurrent writer");
}
if (state.invalid.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: exchange is no longer active")};
}
if (!state.begun.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: response not started")};
}
if (state.finished.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: response already finished")};
}
if (state.stopped()) {
state.request_stop();
return std::unexpected{make_net_error(
NetErrorCode::cancelled,
"Net::ResponseWriter: exchange cancelled")};
}
auto flushed = writer_flush(state);
if (!flushed.has_value()) {
return std::unexpected{std::move(flushed.error())};
}
if (state.chunked.load(std::memory_order_acquire)) {
const std::string_view terminal = "0\r\n\r\n";
auto res = writer_send_all(
state, std::as_bytes(std::span{terminal.data(),
terminal.size()}));
if (!res.has_value()) {
return std::unexpected{std::move(res.error())};
}
} else if (state.fixed_length.load(std::memory_order_acquire)) {
const std::uint64_t total =
state.content_length.load(std::memory_order_acquire);
const std::uint64_t written =
state.accepted.load(std::memory_order_acquire);
if (written != total) {
return std::unexpected{make_net_error(
NetErrorCode::protocol_error,
"Net::ResponseWriter: fixed-length body incomplete")};
}
}
state.finished.store(true, std::memory_order_release);
state.request_stop();
return {};
}
struct ResponseWriterAccess {
static ResponseWriter
make(std::shared_ptr<ResponseWriter::State> state)
{
return ResponseWriter{std::move(state)};
}
};
namespace
{
struct StreamingRoute {
@@ -876,6 +1458,13 @@ namespace Void::Net
StreamingRouteHandler handler;
};
struct DuplexRoute {
Method method;
std::string pattern;
std::vector<std::string> segments;
DuplexRouteHandler handler;
};
struct WorkerEntry {
std::uint64_t id{0};
std::atomic<int> client_fd{-1};
@@ -1023,6 +1612,7 @@ namespace Void::Net
mutable std::shared_mutex stream_mutex{};
std::vector<StreamingRoute> streaming_routes{};
std::vector<DuplexRoute> duplex_routes{};
std::vector<WebSocketRoute> ws_routes{};
std::atomic<std::uint64_t> next_ws_id{1};
@@ -1092,6 +1682,35 @@ namespace Void::Net
best->handler, std::move(best_params)};
}
[[nodiscard]] std::optional<
std::pair<DuplexRouteHandler, RouteParameters>>
match_duplex(Method m, std::string_view path_view) const
{
const auto segments = split_path(path_view);
std::shared_lock lock{stream_mutex};
const DuplexRoute* best = nullptr;
RouteParameters best_params;
for (const auto& r : duplex_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<DuplexRouteHandler, RouteParameters>{
best->handler, std::move(best_params)};
}
[[nodiscard]] std::optional<WebSocketRoute>
match_websocket(std::string_view path_view) const
{
@@ -1257,6 +1876,13 @@ namespace Void::Net
methods.push_back(r.method);
}
}
for (const auto& r : duplex_routes) {
if (match_segments(r.segments, segments).has_value() &&
std::ranges::find(methods, r.method) ==
methods.end()) {
methods.push_back(r.method);
}
}
}
return methods;
}
@@ -1594,10 +2220,13 @@ namespace Void::Net
break;
}
// 4. Check streaming route vs buffered Router.
// 4. Check duplex/streaming routes vs buffered Router.
auto duplex_match = match_duplex(*method_opt, raw_path);
auto streaming_match =
match_streaming(*method_opt, raw_path);
if (!streaming_match.has_value()) {
const bool live_route = duplex_match.has_value() ||
streaming_match.has_value();
if (!live_route) {
// Enforce buffered max_body_bytes before reading body.
if (!chunked && content_length.has_value() &&
*content_length > options.max_body_bytes) {
@@ -1644,6 +2273,99 @@ namespace Void::Net
}
}
if (duplex_match.has_value()) {
ServerRequest req;
req.method = *method_opt;
req.path = std::string{raw_path};
req.headers = std::move(headers);
req.parameters = std::move(duplex_match->second);
req.query = std::string{raw_query};
auto writer_state =
std::make_shared<ResponseWriter::State>();
writer_state->fd = fd_guard.get();
writer_state->stopping = &stopping;
writer_state->write_timeout_ms.store(
options.write_timeout.count(),
std::memory_order_release);
writer_state->max_pending =
options.duplex_write_buffer_bytes;
writer_state->head_request =
(*method_opt == Method::Head);
writer_state->http10 = (version == "HTTP/1.0");
writer_state->keep_alive.store(
keep_alive, std::memory_order_release);
ResponseWriter writer =
ResponseWriterAccess::make(writer_state);
auto route_res = duplex_match->first(
req, body_reader, writer);
const bool committed = writer_state->begun.load(
std::memory_order_acquire);
const bool head_attempted =
writer_state->head_attempted.load(
std::memory_order_acquire);
if (!route_res.has_value()) {
if (!committed && !head_attempted &&
!stopping.load(std::memory_order_acquire)) {
if (route_res.error().kind() ==
Void::Result::ErrorKind::exhausted) {
send_error_close(fd_guard.get(), 413,
"Payload Too Large");
} else if (
route_res.error().kind() ==
Void::Result::ErrorKind::timeout ||
route_res.error().kind() ==
Void::Result::ErrorKind::cancelled) {
send_error_close(fd_guard.get(), 408,
"Request Timeout");
} else {
send_error_close(
fd_guard.get(), 500,
"Internal Server Error");
}
}
// After headers the stream is simply terminated
// without a successful terminal chunk.
} else if (!committed) {
if (!head_attempted) {
send_error_close(fd_guard.get(), 500,
"Internal Server Error");
}
} else if (!writer_state->finished.load(
std::memory_order_acquire)) {
auto fin = writer.finish();
if (!fin.has_value()) {
// Framing could not be completed; close.
}
}
const bool completed = writer_state->finished.load(
std::memory_order_acquire);
const bool exchange_keep_alive =
keep_alive &&
writer_state->keep_alive.load(
std::memory_order_acquire) &&
reader_state.eof;
{
// Wait for any writer still inside an
// operation, then permanently invalidate the
// shared state. Retained writers stay memory-safe
// but can no longer touch this connection.
std::lock_guard lock{writer_state->io_mutex};
writer_state->invalid.store(
true, std::memory_order_release);
writer_state->fd = -1;
writer_state->stopping = nullptr;
}
writer_state->request_stop();
if (!exchange_keep_alive || !completed) {
break;
}
continue;
}
if (streaming_match.has_value()) {
ServerRequest req;
req.method = *method_opt;
@@ -1794,7 +2516,11 @@ namespace Void::Net
}
if ((pfds[1].revents & POLLIN) != 0) {
std::uint64_t val = 0;
(void)::read(wake_fd, &val, sizeof(val));
// Best effort: the eventfd is only a wakeup hint and the
// stopping flag is authoritative, but consume the result so
// fortified headers do not raise -Wunused-result.
[[maybe_unused]] const ssize_t drained =
::read(wake_fd, &val, sizeof(val));
}
if (stopping.load(std::memory_order_acquire)) {
break;
@@ -1833,8 +2559,11 @@ namespace Void::Net
"Content-Length: 19\r\n"
"Connection: close\r\n\r\n"
"Service Unavailable";
(void)::send(client_fd, busy.data(), busy.size(),
MSG_NOSIGNAL);
// The connection is closed regardless of whether the
// 503 could be delivered; consume the result explicitly.
[[maybe_unused]] const ssize_t sent =
::send(client_fd, busy.data(), busy.size(),
MSG_NOSIGNAL);
(void)::close(client_fd);
continue;
}
@@ -1868,7 +2597,10 @@ namespace Void::Net
stopping.store(true, std::memory_order_release);
if (wake_fd >= 0) {
const std::uint64_t one = 1;
(void)::write(wake_fd, &one, sizeof(one));
// Best effort wakeup: the accept loop also polls with a
// timeout, so a full eventfd cannot delay shutdown.
[[maybe_unused]] const ssize_t signalled =
::write(wake_fd, &one, sizeof(one));
}
if (accept_thread.joinable()) {
accept_thread.join();
@@ -1986,6 +2718,36 @@ namespace Void::Net
return {};
}
Void::Result::Result<void>
HttpServer::add_duplex_route(Method method, std::string pattern,
DuplexRouteHandler handler)
{
if (!handler) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::HttpServer: duplex 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->duplex_routes, [&](const DuplexRoute& r) {
return r.method == method &&
same_route_shape(r.segments, *compiled);
});
if (dup != m_impl->duplex_routes.end()) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::HttpServer: duplicate duplex route")};
}
m_impl->duplex_routes.push_back(DuplexRoute{
method, std::move(pattern), std::move(*compiled),
std::move(handler)});
return {};
}
Void::Result::Result<void>
HttpServer::add_websocket_route(std::string pattern,
WebSocketSessions& sessions,
@@ -2020,7 +2782,8 @@ namespace Void::Net
}
if (m_impl->options.max_concurrent_connections == 0 ||
m_impl->options.max_header_bytes == 0 ||
m_impl->options.max_headers == 0) {
m_impl->options.max_headers == 0 ||
m_impl->options.duplex_write_buffer_bytes == 0) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::HttpServer::start: limits must be positive")};
+635
View File
@@ -0,0 +1,635 @@
#include <Void/Net/Smtp.hpp>
#include <Void/Net/Http.hpp>
#include <Void/Net/Tls.hpp>
#include <Void/Text/Base64.hpp>
#include <algorithm>
#include <array>
#include <charconv>
#include <chrono>
#include <cstdint>
#include <format>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace Void::Net
{
namespace
{
[[nodiscard]] std::string upper_ascii(std::string_view text)
{
std::string out{text};
for (char& c : out) {
c = static_cast<char>(
std::toupper(static_cast<unsigned char>(c)));
}
return out;
}
[[nodiscard]] std::string_view trimmed(std::string_view text) noexcept
{
constexpr std::string_view whitespace = " \t\r\n";
const std::size_t begin = text.find_first_not_of(whitespace);
if (begin == std::string_view::npos) {
return {};
}
const std::size_t end = text.find_last_not_of(whitespace);
return text.substr(begin, end - begin + 1);
}
[[nodiscard]] bool has_control(std::string_view text) noexcept
{
return std::ranges::any_of(text, [](char c) {
const auto value = static_cast<unsigned char>(c);
return value < 0x20U || value == 0x7FU;
});
}
[[nodiscard]] Void::Result::Result<void>
validate_address(std::string_view field, std::string_view value)
{
if (value.empty()) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
std::format("SMTP: {} must not be empty", field))};
}
if (has_control(value) || value.find('<') != std::string_view::npos ||
value.find('>') != std::string_view::npos) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
std::format("SMTP: {} contains invalid characters",
field))};
}
return {};
}
struct SmtpReply {
int code{0};
std::vector<std::string> lines{};
};
[[nodiscard]] std::string
reply_summary(const SmtpReply& reply)
{
if (reply.lines.empty()) {
return std::to_string(reply.code);
}
return std::format("{} {}", reply.code, reply.lines.front());
}
[[nodiscard]] Void::Result::Error
rejected_error(std::string_view context,
const SmtpReply& reply)
{
return make_net_error(
NetErrorCode::smtp_rejected,
std::format("SMTP: {} rejected: {}", context,
reply_summary(reply)));
}
[[nodiscard]] std::string encode_data(std::string_view data)
{
std::string out;
out.reserve(data.size() + data.size() / 16U + 8U);
bool line_start = true;
for (std::size_t i = 0; i < data.size(); ++i) {
const char c = data[i];
if (line_start && c == '.') {
out.push_back('.');
}
if (c == '\r') {
if (i + 1U < data.size() && data[i + 1U] == '\n') {
++i;
}
out += "\r\n";
line_start = true;
continue;
}
if (c == '\n') {
out += "\r\n";
line_start = true;
continue;
}
out.push_back(c);
line_start = false;
}
if (!line_start) {
out += "\r\n";
}
out += ".\r\n";
return out;
}
} // namespace
struct SmtpClient::Impl {
TlsClientStream stream;
SmtpOptions options;
std::string pending{};
std::vector<std::string> capabilities{};
Impl(TlsClientStream s, SmtpOptions o)
: stream(std::move(s)), options(std::move(o))
{
}
[[nodiscard]] Void::Result::Result<std::string> read_line()
{
for (;;) {
const std::size_t end = pending.find("\r\n");
if (end != std::string::npos) {
std::string line = pending.substr(0, end);
pending.erase(0, end + 2U);
if (line.size() >
options.limits.max_line_bytes) {
return std::unexpected{make_net_error(
NetErrorCode::protocol_error,
std::format("SMTP: reply line exceeds {} "
"bytes",
options.limits
.max_line_bytes))};
}
return line;
}
if (pending.size() >
options.limits.max_line_bytes) {
return std::unexpected{make_net_error(
NetErrorCode::protocol_error,
"SMTP: reply line too long")};
}
std::array<std::byte, 1024> chunk{};
auto count = stream.read(chunk, options.io_timeout,
options.stop);
if (!count.has_value()) {
return std::unexpected{
std::move(count.error())};
}
if (*count == 0) {
return std::unexpected{make_net_error(
NetErrorCode::protocol_error,
"SMTP: server closed the connection")};
}
pending.append(
reinterpret_cast<const char*>(chunk.data()),
*count);
}
}
[[nodiscard]] Void::Result::Result<SmtpReply> read_reply()
{
SmtpReply reply;
std::uint64_t total = 0;
for (;;) {
auto line = read_line();
if (!line.has_value()) {
return std::unexpected{
std::move(line.error())};
}
total += line->size() + 2U;
if (total >
options.limits.max_response_bytes) {
return std::unexpected{make_net_error(
NetErrorCode::protocol_error,
std::format("SMTP: reply exceeds {} bytes",
options.limits
.max_response_bytes))};
}
if (line->size() < 3U) {
return std::unexpected{make_net_error(
NetErrorCode::protocol_error,
"SMTP: malformed reply")};
}
int code = 0;
const char* begin = line->data();
const char* finish = begin + 3;
const auto parsed =
std::from_chars(begin, finish, code);
if (parsed.ec != std::errc{} ||
parsed.ptr != finish || code < 100 ||
code > 599) {
return std::unexpected{make_net_error(
NetErrorCode::protocol_error,
"SMTP: malformed reply code")};
}
const char separator =
line->size() > 3U ? (*line)[3] : ' ';
if (separator != '-' && separator != ' ') {
return std::unexpected{make_net_error(
NetErrorCode::protocol_error,
"SMTP: malformed reply separator")};
}
if (!reply.lines.empty() &&
reply.code != code) {
return std::unexpected{make_net_error(
NetErrorCode::protocol_error,
"SMTP: inconsistent multi-line reply")};
}
reply.code = code;
reply.lines.push_back(
line->size() > 4U ? line->substr(4)
: std::string{});
if (separator == ' ') {
return reply;
}
}
}
[[nodiscard]] Void::Result::Result<void>
command(std::string_view line)
{
std::string wire{line};
wire += "\r\n";
return stream.write_all(wire, options.io_timeout,
options.stop);
}
[[nodiscard]] Void::Result::Result<SmtpReply>
command_reply(std::string_view line)
{
auto sent = command(line);
if (!sent.has_value()) {
return std::unexpected{std::move(sent.error())};
}
return read_reply();
}
[[nodiscard]] bool
has_capability(std::string_view name) const
{
const std::string wanted = upper_ascii(name);
return std::ranges::any_of(
capabilities, [&](const std::string& capability) {
return capability == wanted ||
capability.starts_with(wanted + " ") ||
capability.starts_with(wanted + "=");
});
}
[[nodiscard]] bool auth_plain_supported() const
{
for (const auto& capability : capabilities) {
if (!capability.starts_with("AUTH ") &&
!capability.starts_with("AUTH=")) {
continue;
}
std::string mechanisms = capability.substr(5);
std::ranges::replace(mechanisms, '=', ' ');
std::size_t begin = 0;
while (begin < mechanisms.size()) {
const std::size_t end =
mechanisms.find(' ', begin);
const std::string_view mechanism{
mechanisms.data() + begin,
(end == std::string::npos ? mechanisms.size()
: end) -
begin};
if (mechanism == "PLAIN") {
return true;
}
if (end == std::string::npos) {
break;
}
begin = end + 1U;
}
}
return false;
}
[[nodiscard]] std::optional<std::uint64_t>
server_size_limit() const
{
for (const auto& capability : capabilities) {
if (!capability.starts_with("SIZE")) {
continue;
}
if (capability.size() == 4U) {
return std::nullopt;
}
if (capability[4] != ' ') {
continue;
}
std::uint64_t limit = 0;
const char* begin = capability.data() + 5;
const char* end =
capability.data() + capability.size();
const auto parsed =
std::from_chars(begin, end, limit);
if (parsed.ec == std::errc{} &&
parsed.ptr == end) {
return limit;
}
}
return std::nullopt;
}
[[nodiscard]] Void::Result::Result<void> ehlo()
{
auto reply =
command_reply("EHLO " + options.client_domain);
if (!reply.has_value()) {
return std::unexpected{std::move(reply.error())};
}
if (reply->code != 250) {
return std::unexpected{
rejected_error("EHLO", *reply)};
}
capabilities.clear();
for (std::size_t i = 1; i < reply->lines.size(); ++i) {
const std::string_view capability =
trimmed(reply->lines[i]);
if (!capability.empty()) {
capabilities.push_back(
upper_ascii(capability));
}
}
return {};
}
[[nodiscard]] Void::Result::Result<void> authenticate()
{
if (!options.credentials.has_value()) {
return {};
}
if (!stream.secure()) {
// Credentials are never sent on a plaintext channel.
return std::unexpected{make_net_error(
NetErrorCode::tls_required,
"SMTP: refusing to send credentials without TLS")};
}
if (!auth_plain_supported()) {
return std::unexpected{make_net_error(
NetErrorCode::auth_failed,
"SMTP: server does not advertise AUTH PLAIN")};
}
std::string payload;
payload.reserve(1U + options.credentials->username.size() +
1U +
options.credentials->password.size());
payload.push_back('\0');
payload += options.credentials->username;
payload.push_back('\0');
payload += options.credentials->password;
const std::string token =
Void::Encoding::Base64::encode(payload);
auto reply = command_reply("AUTH PLAIN " + token);
if (!reply.has_value()) {
return std::unexpected{std::move(reply.error())};
}
if (reply->code != 235) {
return std::unexpected{make_net_error(
NetErrorCode::auth_failed,
std::format("SMTP: authentication failed: {}",
reply_summary(*reply)))};
}
return {};
}
[[nodiscard]] Void::Result::Result<void>
expect(const SmtpReply& reply, int code,
std::string_view context)
{
if (reply.code != code) {
return std::unexpected{
rejected_error(context, reply)};
}
return {};
}
};
SmtpClient::SmtpClient() noexcept = default;
SmtpClient::SmtpClient(std::unique_ptr<Impl> impl) noexcept
: m_impl(std::move(impl))
{
}
SmtpClient::~SmtpClient() noexcept = default;
SmtpClient::SmtpClient(SmtpClient&&) noexcept = default;
SmtpClient& SmtpClient::operator=(SmtpClient&&) noexcept = default;
bool SmtpClient::valid() const noexcept
{
return m_impl != nullptr && m_impl->stream.valid();
}
bool SmtpClient::secure() const noexcept
{
return m_impl != nullptr && m_impl->stream.secure();
}
Void::Result::Result<SmtpClient>
SmtpClient::connect(SmtpOptions options)
{
if (options.host.empty() || options.port == 0) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"SMTP: connect requires a host and port")};
}
TlsClientOptions tls;
tls.host = options.host;
tls.port = options.port;
tls.server_name = options.server_name;
tls.ca_file = options.ca_file;
tls.connect_timeout = options.connect_timeout;
tls.io_timeout = options.io_timeout;
tls.stop = options.stop;
auto stream =
options.security == SmtpSecurity::implicit_tls
? TlsClientStream::connect(std::move(tls))
: TlsClientStream::connect_plain(std::move(tls));
if (!stream.has_value()) {
return std::unexpected{std::move(stream.error())};
}
auto impl =
std::make_unique<Impl>(std::move(*stream), std::move(options));
auto greeting = impl->read_reply();
if (!greeting.has_value()) {
return std::unexpected{std::move(greeting.error())};
}
if (greeting->code != 220) {
return std::unexpected{
rejected_error("greeting", *greeting)};
}
auto hello = impl->ehlo();
if (!hello.has_value()) {
return std::unexpected{std::move(hello.error())};
}
if (impl->options.security ==
SmtpSecurity::starttls_required) {
if (!impl->has_capability("STARTTLS")) {
return std::unexpected{make_net_error(
NetErrorCode::tls_required,
"SMTP: server does not advertise STARTTLS")};
}
auto reply = impl->command_reply("STARTTLS");
if (!reply.has_value()) {
return std::unexpected{std::move(reply.error())};
}
if (reply->code != 220) {
return std::unexpected{
rejected_error("STARTTLS", *reply)};
}
auto upgraded = impl->stream.start_tls();
if (!upgraded.has_value()) {
return std::unexpected{std::move(upgraded.error())};
}
auto hello_again = impl->ehlo();
if (!hello_again.has_value()) {
return std::unexpected{
std::move(hello_again.error())};
}
}
auto authenticated = impl->authenticate();
if (!authenticated.has_value()) {
return std::unexpected{std::move(authenticated.error())};
}
return SmtpClient{std::move(impl)};
}
Void::Result::Result<void>
SmtpClient::send(const SmtpMessage& message)
{
if (!valid()) {
return std::unexpected{make_net_error(
NetErrorCode::io_error, "SMTP: client is not connected")};
}
auto& impl = *m_impl;
const auto fail =
[&](Void::Result::Error error)
-> Void::Result::Result<void> {
impl.stream.close();
return std::unexpected{std::move(error)};
};
auto valid_from = validate_address("from", message.from);
if (!valid_from.has_value()) {
return std::unexpected{std::move(valid_from.error())};
}
if (message.recipients.empty()) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"SMTP: at least one recipient is required")};
}
if (message.recipients.size() >
impl.options.limits.max_recipients) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
std::format("SMTP: {} recipients exceeds limit {}",
message.recipients.size(),
impl.options.limits.max_recipients))};
}
for (const auto& recipient : message.recipients) {
auto valid_recipient =
validate_address("recipient", recipient);
if (!valid_recipient.has_value()) {
return std::unexpected{
std::move(valid_recipient.error())};
}
}
if (message.data.size() >
impl.options.limits.max_message_bytes) {
return std::unexpected{make_net_error(
NetErrorCode::payload_too_large,
std::format("SMTP: message {} bytes exceeds limit {}",
message.data.size(),
impl.options.limits.max_message_bytes))};
}
if (const auto server_limit = impl.server_size_limit();
server_limit.has_value() && *server_limit > 0 &&
message.data.size() > *server_limit) {
return std::unexpected{make_net_error(
NetErrorCode::payload_too_large,
std::format("SMTP: message {} bytes exceeds server SIZE {}",
message.data.size(), *server_limit))};
}
auto mail = impl.command_reply("MAIL FROM:<" +
message.from + ">");
if (!mail.has_value()) {
return fail(std::move(mail.error()));
}
if (mail->code != 250) {
return fail(rejected_error("MAIL FROM", *mail));
}
for (const auto& recipient : message.recipients) {
auto rcpt =
impl.command_reply("RCPT TO:<" + recipient + ">");
if (!rcpt.has_value()) {
return fail(std::move(rcpt.error()));
}
if (rcpt->code != 250 && rcpt->code != 251) {
return fail(rejected_error("RCPT TO", *rcpt));
}
}
auto data = impl.command_reply("DATA");
if (!data.has_value()) {
return fail(std::move(data.error()));
}
if (data->code != 354) {
return fail(rejected_error("DATA", *data));
}
const std::string encoded = encode_data(message.data);
auto written = impl.stream.write_all(encoded,
impl.options.io_timeout,
impl.options.stop);
if (!written.has_value()) {
return fail(std::move(written.error()));
}
auto accepted = impl.read_reply();
if (!accepted.has_value()) {
return fail(std::move(accepted.error()));
}
if (accepted->code != 250) {
return fail(rejected_error("message body", *accepted));
}
return {};
}
Void::Result::Result<void> SmtpClient::quit()
{
if (m_impl == nullptr) {
return {};
}
auto& impl = *m_impl;
Void::Result::Result<void> result{};
if (impl.stream.valid()) {
auto reply = impl.command_reply("QUIT");
if (!reply.has_value()) {
result = std::unexpected{std::move(reply.error())};
} else if (reply->code != 221) {
result = std::unexpected{
rejected_error("QUIT", *reply)};
}
}
auto closed = impl.stream.shutdown();
if (result.has_value() && !closed.has_value()) {
result = std::unexpected{std::move(closed.error())};
}
return result;
}
void SmtpClient::close() noexcept
{
if (m_impl != nullptr) {
m_impl->stream.close();
}
}
Void::Result::Result<void>
SmtpClient::submit(SmtpOptions options,
const SmtpMessage& message)
{
auto client = connect(std::move(options));
if (!client.has_value()) {
return std::unexpected{std::move(client.error())};
}
auto sent = client->send(message);
if (!sent.has_value()) {
client->close();
return std::unexpected{std::move(sent.error())};
}
return client->quit();
}
} // namespace Void::Net
+872
View File
@@ -0,0 +1,872 @@
#include <Void/Net/Tls.hpp>
#include <Void/Net/Http.hpp>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <openssl/x509v3.h>
#if !defined(_WIN32)
#include <arpa/inet.h>
#include <fcntl.h>
#include <netdb.h>
#include <poll.h>
#include <sys/socket.h>
#include <unistd.h>
#endif
#include <algorithm>
#include <cerrno>
#include <chrono>
#include <climits>
#include <cstring>
#include <format>
#include <limits>
#include <memory>
#include <optional>
#include <utility>
namespace Void::Net
{
namespace
{
#if !defined(_WIN32)
using Clock = std::chrono::steady_clock;
[[nodiscard]] std::chrono::milliseconds
effective_timeout(std::chrono::milliseconds requested,
std::chrono::milliseconds fallback) noexcept
{
return requested.count() > 0 ? requested : fallback;
}
[[nodiscard]] Clock::time_point
deadline_for(std::chrono::milliseconds timeout) noexcept
{
if (timeout.count() <= 0) {
return Clock::time_point::max();
}
return Clock::now() + timeout;
}
[[nodiscard]] int poll_timeout_ms(Clock::time_point deadline) noexcept
{
if (deadline == Clock::time_point::max()) {
return -1;
}
const auto left = deadline - Clock::now();
if (left <= Clock::duration::zero()) {
return 0;
}
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(left);
if (std::chrono::duration_cast<Clock::duration>(ms) < left) {
ms += std::chrono::milliseconds{1};
}
return static_cast<int>(std::clamp<long long>(
ms.count(), 0, std::numeric_limits<int>::max()));
}
[[nodiscard]] std::string openssl_error_text()
{
const unsigned long code = ERR_get_error();
if (code == 0) {
return "no OpenSSL error detail";
}
char buffer[256];
ERR_error_string_n(code, buffer, sizeof(buffer));
return std::string{buffer};
}
[[nodiscard]] Void::Result::Error
cancelled_error(std::string_view operation)
{
return make_net_error(
NetErrorCode::cancelled,
std::format("Net: TLS {} cancelled", operation));
}
[[nodiscard]] Void::Result::Error
timeout_error(std::string_view operation)
{
return make_net_error(
NetErrorCode::timeout,
std::format("Net: TLS {} timed out", operation));
}
[[nodiscard]] Void::Result::Result<void>
wait_fd(int fd, short events, Clock::time_point deadline,
std::stop_token stop, std::string_view operation)
{
for (;;) {
if (stop.stop_requested()) {
return std::unexpected{cancelled_error(operation)};
}
pollfd descriptor{.fd = fd, .events = events, .revents = 0};
int wait_ms = poll_timeout_ms(deadline);
if (stop.stop_possible() &&
(wait_ms < 0 || wait_ms > 50)) {
// Keep cancellation latency bounded without closing the
// stream; poll again after the slice.
wait_ms = 50;
}
const int rc = ::poll(&descriptor, 1, wait_ms);
if (rc < 0) {
if (errno == EINTR) {
continue;
}
return std::unexpected{make_net_error(
NetErrorCode::io_error,
std::format("Net: TLS poll failed: {}",
std::strerror(errno)))};
}
if (rc == 0) {
if (Clock::now() >= deadline) {
return std::unexpected{timeout_error(operation)};
}
continue;
}
if ((descriptor.revents & events) != 0 ||
(descriptor.revents & (POLLHUP | POLLERR | POLLNVAL)) !=
0) {
// Let the caller perform the I/O and report the real
// error; POLLHUP still delivers buffered data and EOF.
return {};
}
}
}
[[nodiscard]] Void::Result::Result<int>
tcp_connect(const TlsClientOptions& options,
Clock::time_point deadline)
{
if (options.host.empty() || options.port == 0) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net: TLS connect requires a host and port")};
}
addrinfo hints{};
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
addrinfo* addresses = nullptr;
const std::string service = std::to_string(options.port);
const int resolved =
::getaddrinfo(options.host.c_str(), service.c_str(), &hints,
&addresses);
if (resolved != 0) {
return std::unexpected{make_net_error(
NetErrorCode::connect_failed,
std::format("Net: TLS resolve '{}': {}", options.host,
gai_strerror(resolved)))};
}
std::unique_ptr<addrinfo, decltype(&freeaddrinfo)> guard{
addresses, &freeaddrinfo};
Void::Result::Error last = make_net_error(
NetErrorCode::connect_failed,
std::format("Net: TLS connect to '{}:{}' failed", options.host,
options.port));
for (addrinfo* address = addresses; address != nullptr;
address = address->ai_next) {
#ifdef SOCK_CLOEXEC
const int fd =
::socket(address->ai_family,
address->ai_socktype | SOCK_CLOEXEC,
address->ai_protocol);
#else
const int fd =
::socket(address->ai_family, address->ai_socktype,
address->ai_protocol);
#endif
if (fd < 0) {
continue;
}
const int flags = ::fcntl(fd, F_GETFL, 0);
if (flags < 0 ||
::fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) {
::close(fd);
continue;
}
if (::connect(fd, address->ai_addr, address->ai_addrlen) ==
0) {
return fd;
}
if (errno != EINPROGRESS && errno != EINTR) {
last = make_net_error(
NetErrorCode::connect_failed,
std::format("Net: TLS connect failed: {}",
std::strerror(errno)));
::close(fd);
continue;
}
const auto waited =
wait_fd(fd, POLLOUT, deadline, options.stop, "connect");
if (!waited.has_value()) {
::close(fd);
return std::unexpected{std::move(waited.error())};
}
int socket_error = 0;
socklen_t length = sizeof(socket_error);
if (::getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error,
&length) != 0 ||
socket_error != 0) {
const int code =
socket_error != 0 ? socket_error : errno;
last = make_net_error(
NetErrorCode::connect_failed,
std::format("Net: TLS connect failed: {}",
std::strerror(code)));
::close(fd);
continue;
}
return fd;
}
return std::unexpected{std::move(last)};
}
[[nodiscard]] bool is_ip_literal(std::string_view host) noexcept
{
std::string text{host};
if (text.size() >= 2 && text.front() == '[' &&
text.back() == ']') {
text = text.substr(1, text.size() - 2);
}
unsigned char storage[sizeof(in6_addr)]{};
return ::inet_pton(AF_INET, text.c_str(), storage) == 1 ||
::inet_pton(AF_INET6, text.c_str(), storage) == 1;
}
[[nodiscard]] std::string
verification_name(const TlsClientOptions& options)
{
std::string name = options.server_name.empty() ? options.host
: options.server_name;
if (name.size() >= 2 && name.front() == '[' &&
name.back() == ']') {
name = name.substr(1, name.size() - 2);
}
return name;
}
#endif
} // namespace
struct TlsClientStream::Impl {
int fd{-1};
SSL_CTX* ctx{nullptr};
SSL* ssl{nullptr};
bool secure{false};
std::chrono::milliseconds io_timeout{
std::chrono::seconds{30}};
std::chrono::milliseconds handshake_timeout{
std::chrono::seconds{10}};
std::stop_token stop{};
std::string server_name{};
std::string ca_file{};
~Impl() noexcept { close_all(); }
[[nodiscard]] bool valid() const noexcept { return fd >= 0; }
void close_all() noexcept
{
if (ssl != nullptr) {
SSL_free(ssl);
ssl = nullptr;
}
if (ctx != nullptr) {
SSL_CTX_free(ctx);
ctx = nullptr;
}
#if !defined(_WIN32)
if (fd >= 0) {
(void)::shutdown(fd, SHUT_RDWR);
(void)::close(fd);
}
#endif
fd = -1;
secure = false;
}
};
TlsClientStream::TlsClientStream() noexcept = default;
TlsClientStream::TlsClientStream(std::unique_ptr<Impl> impl) noexcept
: m_impl(std::move(impl))
{
}
TlsClientStream::~TlsClientStream() noexcept = default;
TlsClientStream::TlsClientStream(TlsClientStream&&) noexcept = default;
TlsClientStream&
TlsClientStream::operator=(TlsClientStream&&) noexcept = default;
bool TlsClientStream::valid() const noexcept
{
return m_impl != nullptr && m_impl->valid();
}
bool TlsClientStream::secure() const noexcept
{
return m_impl != nullptr && m_impl->secure;
}
int TlsClientStream::native_handle() const noexcept
{
return m_impl != nullptr ? m_impl->fd : -1;
}
#if defined(_WIN32)
Void::Result::Result<TlsClientStream>
TlsClientStream::connect(TlsClientOptions)
{
return std::unexpected{make_net_error(
NetErrorCode::tls_error,
"Net: TlsClientStream is not implemented on Windows")};
}
Void::Result::Result<TlsClientStream>
TlsClientStream::connect_plain(TlsClientOptions)
{
return std::unexpected{make_net_error(
NetErrorCode::tls_error,
"Net: TlsClientStream is not implemented on Windows")};
}
Void::Result::Result<TlsClientStream>
TlsClientStream::adopt(int, TlsClientOptions)
{
return std::unexpected{make_net_error(
NetErrorCode::tls_error,
"Net: TlsClientStream is not implemented on Windows")};
}
Void::Result::Result<void> TlsClientStream::start_tls()
{
return std::unexpected{make_net_error(
NetErrorCode::tls_error,
"Net: TlsClientStream is not implemented on Windows")};
}
Void::Result::Result<std::size_t>
TlsClientStream::read(std::span<std::byte>, std::chrono::milliseconds,
std::stop_token)
{
return std::unexpected{make_net_error(
NetErrorCode::io_error, "Net: TLS stream is not open")};
}
Void::Result::Result<std::size_t>
TlsClientStream::write(std::span<const std::byte>,
std::chrono::milliseconds, std::stop_token)
{
return std::unexpected{make_net_error(
NetErrorCode::io_error, "Net: TLS stream is not open")};
}
Void::Result::Result<void>
TlsClientStream::write_all(std::span<const std::byte>,
std::chrono::milliseconds, std::stop_token)
{
return std::unexpected{make_net_error(
NetErrorCode::io_error, "Net: TLS stream is not open")};
}
Void::Result::Result<void>
TlsClientStream::write_all(std::string_view, std::chrono::milliseconds,
std::stop_token)
{
return std::unexpected{make_net_error(
NetErrorCode::io_error, "Net: TLS stream is not open")};
}
Void::Result::Result<void> TlsClientStream::shutdown()
{
if (m_impl != nullptr) {
m_impl->close_all();
}
return {};
}
void TlsClientStream::close() noexcept
{
if (m_impl != nullptr) {
m_impl->close_all();
}
}
#else
Void::Result::Result<TlsClientStream>
TlsClientStream::connect(TlsClientOptions options)
{
const auto timeout =
effective_timeout(options.connect_timeout,
std::chrono::seconds{10});
auto fd = tcp_connect(options, deadline_for(timeout));
if (!fd.has_value()) {
return std::unexpected{std::move(fd.error())};
}
auto impl = std::make_unique<Impl>();
impl->fd = *fd;
impl->io_timeout = options.io_timeout;
impl->handshake_timeout = options.handshake_timeout;
impl->stop = options.stop;
impl->server_name = verification_name(options);
impl->ca_file = std::move(options.ca_file);
TlsClientStream stream{std::move(impl)};
auto started = stream.start_tls();
if (!started.has_value()) {
return std::unexpected{std::move(started.error())};
}
return stream;
}
Void::Result::Result<TlsClientStream>
TlsClientStream::connect_plain(TlsClientOptions options)
{
const auto timeout =
effective_timeout(options.connect_timeout,
std::chrono::seconds{10});
auto fd = tcp_connect(options, deadline_for(timeout));
if (!fd.has_value()) {
return std::unexpected{std::move(fd.error())};
}
auto impl = std::make_unique<Impl>();
impl->fd = *fd;
impl->io_timeout = options.io_timeout;
impl->handshake_timeout = options.handshake_timeout;
impl->stop = options.stop;
impl->server_name = verification_name(options);
impl->ca_file = std::move(options.ca_file);
return TlsClientStream{std::move(impl)};
}
Void::Result::Result<TlsClientStream>
TlsClientStream::adopt(int native_socket, TlsClientOptions options)
{
if (native_socket < 0) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net: TLS adopt requires an open socket")};
}
const int flags = ::fcntl(native_socket, F_GETFL, 0);
if (flags < 0 ||
::fcntl(native_socket, F_SETFL, flags | O_NONBLOCK) < 0) {
return std::unexpected{make_net_error(
NetErrorCode::io_error,
std::format("Net: TLS adopt failed to configure socket: {}",
std::strerror(errno)))};
}
auto impl = std::make_unique<Impl>();
impl->fd = native_socket;
impl->io_timeout = options.io_timeout;
impl->handshake_timeout = options.handshake_timeout;
impl->stop = options.stop;
impl->server_name = verification_name(options);
impl->ca_file = std::move(options.ca_file);
TlsClientStream stream{std::move(impl)};
auto started = stream.start_tls();
if (!started.has_value()) {
return std::unexpected{std::move(started.error())};
}
return stream;
}
Void::Result::Result<void> TlsClientStream::start_tls()
{
if (m_impl == nullptr || !m_impl->valid()) {
return std::unexpected{make_net_error(
NetErrorCode::io_error, "Net: TLS stream is not open")};
}
auto& impl = *m_impl;
if (impl.secure) {
return {};
}
if (impl.ctx != nullptr || impl.ssl != nullptr) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net: TLS handshake already attempted")};
}
impl.ctx = SSL_CTX_new(TLS_client_method());
if (impl.ctx == nullptr) {
return std::unexpected{make_net_error(
NetErrorCode::tls_error,
"Net: TLS failed to create context: " +
openssl_error_text())};
}
if (SSL_CTX_set_min_proto_version(impl.ctx, TLS1_2_VERSION) != 1) {
const auto error = make_net_error(
NetErrorCode::tls_error,
"Net: TLS failed to require TLS 1.2: " + openssl_error_text());
impl.close_all();
return std::unexpected{error};
}
SSL_CTX_set_verify(impl.ctx, SSL_VERIFY_PEER, nullptr);
// The trust store is always applied; a failure is fatal and never
// downgrades verification.
const int loaded =
impl.ca_file.empty()
? SSL_CTX_set_default_verify_paths(impl.ctx)
: SSL_CTX_load_verify_locations(impl.ctx,
impl.ca_file.c_str(), nullptr);
if (loaded != 1) {
const auto error = make_net_error(
NetErrorCode::tls_error,
std::format("Net: TLS failed to load trust store{}: {}",
impl.ca_file.empty()
? std::string{}
: " '" + impl.ca_file + "'",
openssl_error_text()));
impl.close_all();
return std::unexpected{error};
}
impl.ssl = SSL_new(impl.ctx);
if (impl.ssl == nullptr) {
const auto error = make_net_error(
NetErrorCode::tls_error,
"Net: TLS failed to create session: " +
openssl_error_text());
impl.close_all();
return std::unexpected{error};
}
if (SSL_set_fd(impl.ssl, impl.fd) != 1) {
const auto error = make_net_error(
NetErrorCode::tls_error,
"Net: TLS failed to attach socket: " +
openssl_error_text());
impl.close_all();
return std::unexpected{error};
}
(void)SSL_set_mode(impl.ssl,
SSL_MODE_ENABLE_PARTIAL_WRITE |
SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
if (!is_ip_literal(impl.server_name) &&
SSL_set_tlsext_host_name(impl.ssl,
impl.server_name.c_str()) != 1) {
const auto error = make_net_error(
NetErrorCode::tls_error,
"Net: TLS failed to set SNI hostname: " +
openssl_error_text());
impl.close_all();
return std::unexpected{error};
}
X509_VERIFY_PARAM* param = SSL_get0_param(impl.ssl);
if (param == nullptr) {
const auto error = make_net_error(
NetErrorCode::tls_error,
"Net: TLS X509 verification parameters unavailable");
impl.close_all();
return std::unexpected{error};
}
X509_VERIFY_PARAM_set_hostflags(param,
X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
const int set_name =
is_ip_literal(impl.server_name)
? X509_VERIFY_PARAM_set1_ip_asc(param,
impl.server_name.c_str())
: X509_VERIFY_PARAM_set1_host(param,
impl.server_name.c_str(),
impl.server_name.size());
if (set_name != 1) {
const auto error = make_net_error(
NetErrorCode::tls_error,
"Net: TLS failed to set peer verification target");
impl.close_all();
return std::unexpected{error};
}
const auto deadline =
deadline_for(effective_timeout({}, impl.handshake_timeout));
for (;;) {
if (impl.stop.stop_requested()) {
const auto error = cancelled_error("handshake");
impl.close_all();
return std::unexpected{error};
}
ERR_clear_error();
const int rc = SSL_connect(impl.ssl);
if (rc == 1) {
break;
}
const int error_code = SSL_get_error(impl.ssl, rc);
if (error_code == SSL_ERROR_WANT_READ ||
error_code == SSL_ERROR_WANT_WRITE) {
const auto waited = wait_fd(
impl.fd,
error_code == SSL_ERROR_WANT_READ ? POLLIN : POLLOUT,
deadline, impl.stop, "handshake");
if (!waited.has_value()) {
const auto error = waited.error();
impl.close_all();
return std::unexpected{error};
}
continue;
}
if (error_code == SSL_ERROR_SYSCALL && errno == EINTR) {
continue;
}
const long verify = SSL_get_verify_result(impl.ssl);
std::string detail = openssl_error_text();
if (verify != X509_V_OK) {
detail += std::format(" (certificate verify: {})",
X509_verify_cert_error_string(verify));
}
const auto error = make_net_error(
NetErrorCode::tls_error,
"Net: TLS handshake failed: " + detail);
impl.close_all();
return std::unexpected{error};
}
const long verify = SSL_get_verify_result(impl.ssl);
if (verify != X509_V_OK) {
const auto error = make_net_error(
NetErrorCode::tls_error,
std::format("Net: TLS peer verification failed: {}",
X509_verify_cert_error_string(verify)));
impl.close_all();
return std::unexpected{error};
}
impl.secure = true;
return {};
}
Void::Result::Result<std::size_t>
TlsClientStream::read(std::span<std::byte> destination,
std::chrono::milliseconds timeout,
std::stop_token stop)
{
if (m_impl == nullptr || !m_impl->valid()) {
return std::unexpected{make_net_error(
NetErrorCode::io_error, "Net: TLS stream is not open")};
}
if (destination.empty()) {
return 0;
}
auto& impl = *m_impl;
const auto deadline =
deadline_for(effective_timeout(timeout, impl.io_timeout));
const std::stop_token token =
stop.stop_possible() ? stop : impl.stop;
for (;;) {
if (token.stop_requested()) {
return std::unexpected{cancelled_error("read")};
}
if (impl.secure) {
ERR_clear_error();
const int rc = SSL_read(
impl.ssl, destination.data(),
static_cast<int>(std::min<std::size_t>(
destination.size(),
static_cast<std::size_t>(INT_MAX))));
if (rc > 0) {
return static_cast<std::size_t>(rc);
}
const int error_code = SSL_get_error(impl.ssl, rc);
if (error_code == SSL_ERROR_WANT_READ ||
error_code == SSL_ERROR_WANT_WRITE) {
auto waited = wait_fd(
impl.fd,
error_code == SSL_ERROR_WANT_READ ? POLLIN
: POLLOUT,
deadline, token, "read");
if (!waited.has_value()) {
return std::unexpected{std::move(waited.error())};
}
continue;
}
if (error_code == SSL_ERROR_ZERO_RETURN) {
return 0;
}
if (error_code == SSL_ERROR_SYSCALL) {
if (errno == EINTR || errno == EAGAIN ||
errno == EWOULDBLOCK) {
continue;
}
if (rc == 0) {
return 0;
}
return std::unexpected{make_net_error(
NetErrorCode::io_error,
std::format("Net: TLS read failed: {}",
std::strerror(errno)))};
}
return std::unexpected{make_net_error(
NetErrorCode::tls_error,
"Net: TLS read failed: " + openssl_error_text())};
}
const ssize_t rc = ::recv(impl.fd, destination.data(),
destination.size(), 0);
if (rc > 0) {
return static_cast<std::size_t>(rc);
}
if (rc == 0) {
return 0;
}
if (errno == EINTR) {
continue;
}
if (errno == EAGAIN || errno == EWOULDBLOCK) {
auto waited = wait_fd(impl.fd, POLLIN, deadline, token,
"read");
if (!waited.has_value()) {
return std::unexpected{std::move(waited.error())};
}
continue;
}
return std::unexpected{make_net_error(
NetErrorCode::io_error,
std::format("Net: TCP read failed: {}",
std::strerror(errno)))};
}
}
Void::Result::Result<std::size_t>
TlsClientStream::write(std::span<const std::byte> source,
std::chrono::milliseconds timeout,
std::stop_token stop)
{
if (m_impl == nullptr || !m_impl->valid()) {
return std::unexpected{make_net_error(
NetErrorCode::io_error, "Net: TLS stream is not open")};
}
if (source.empty()) {
return 0;
}
auto& impl = *m_impl;
const auto deadline =
deadline_for(effective_timeout(timeout, impl.io_timeout));
const std::stop_token token =
stop.stop_possible() ? stop : impl.stop;
for (;;) {
if (token.stop_requested()) {
return std::unexpected{cancelled_error("write")};
}
if (impl.secure) {
ERR_clear_error();
const int rc = SSL_write(
impl.ssl, source.data(),
static_cast<int>(std::min<std::size_t>(
source.size(),
static_cast<std::size_t>(INT_MAX))));
if (rc > 0) {
return static_cast<std::size_t>(rc);
}
const int error_code = SSL_get_error(impl.ssl, rc);
if (error_code == SSL_ERROR_WANT_READ ||
error_code == SSL_ERROR_WANT_WRITE) {
auto waited = wait_fd(
impl.fd,
error_code == SSL_ERROR_WANT_READ ? POLLIN
: POLLOUT,
deadline, token, "write");
if (!waited.has_value()) {
return std::unexpected{std::move(waited.error())};
}
continue;
}
if (error_code == SSL_ERROR_SYSCALL) {
if (errno == EINTR || errno == EAGAIN ||
errno == EWOULDBLOCK) {
continue;
}
return std::unexpected{make_net_error(
NetErrorCode::io_error,
std::format("Net: TLS write failed: {}",
std::strerror(errno)))};
}
return std::unexpected{make_net_error(
NetErrorCode::tls_error,
"Net: TLS write failed: " + openssl_error_text())};
}
#ifdef MSG_NOSIGNAL
constexpr int flags = MSG_NOSIGNAL;
#else
constexpr int flags = 0;
#endif
const ssize_t rc =
::send(impl.fd, source.data(), source.size(), flags);
if (rc > 0) {
return static_cast<std::size_t>(rc);
}
if (rc < 0 && errno == EINTR) {
continue;
}
if (rc < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
auto waited = wait_fd(impl.fd, POLLOUT, deadline, token,
"write");
if (!waited.has_value()) {
return std::unexpected{std::move(waited.error())};
}
continue;
}
return std::unexpected{make_net_error(
NetErrorCode::io_error,
std::format("Net: TCP write failed: {}",
std::strerror(errno)))};
}
}
Void::Result::Result<void>
TlsClientStream::write_all(std::span<const std::byte> source,
std::chrono::milliseconds timeout,
std::stop_token stop)
{
while (!source.empty()) {
auto written = write(source, timeout, stop);
if (!written.has_value()) {
return std::unexpected{std::move(written.error())};
}
if (*written == 0) {
return std::unexpected{make_net_error(
NetErrorCode::io_error,
"Net: TLS write made no progress")};
}
source = source.subspan(*written);
}
return {};
}
Void::Result::Result<void>
TlsClientStream::write_all(std::string_view text,
std::chrono::milliseconds timeout,
std::stop_token stop)
{
return write_all(
std::span<const std::byte>{
reinterpret_cast<const std::byte*>(text.data()),
text.size()},
timeout, stop);
}
Void::Result::Result<void> TlsClientStream::shutdown()
{
if (m_impl == nullptr) {
return {};
}
auto& impl = *m_impl;
Void::Result::Result<void> result{};
if (impl.secure && impl.ssl != nullptr) {
const auto deadline =
deadline_for(effective_timeout({}, impl.io_timeout));
for (;;) {
ERR_clear_error();
const int rc = SSL_shutdown(impl.ssl);
if (rc >= 0) {
break;
}
const int error_code = SSL_get_error(impl.ssl, rc);
if (error_code == SSL_ERROR_WANT_READ ||
error_code == SSL_ERROR_WANT_WRITE) {
auto waited = wait_fd(
impl.fd,
error_code == SSL_ERROR_WANT_READ ? POLLIN
: POLLOUT,
deadline, impl.stop, "shutdown");
if (!waited.has_value()) {
result = std::unexpected{
std::move(waited.error())};
break;
}
continue;
}
break;
}
}
impl.close_all();
return result;
}
void TlsClientStream::close() noexcept
{
if (m_impl != nullptr) {
m_impl->close_all();
}
}
#endif
} // namespace Void::Net
+5
View File
@@ -1,5 +1,10 @@
void_add_module(Net
INTERNAL_DEPS Functional Text Time
# The HTTP server is POSIX-only. Windows builds get the client-side
# surface; a Windows server port is explicitly out of scope, and any
# server symbol left undefined fails closed at link time.
EXCLUDE_SOURCES_WIN32
HttpServer.cpp
EXTERNAL_DEPS
Boost::headers
Boost::beast
+337
View File
@@ -0,0 +1,337 @@
#include <Void/Script/Lua.hpp>
#if defined(VOID_SCRIPT_HAS_LUA)
#include <algorithm>
#include <cstdlib>
#include <exception>
#include <string>
#include <utility>
#include <vector>
extern "C" {
#include <lauxlib.h>
#include <lua.h>
#include <lualib.h>
}
namespace Void::Script
{
namespace
{
struct Context {
const Limits* limits{nullptr};
const std::vector<Host>* hosts{nullptr};
const CancelFunction* cancelled{nullptr};
std::size_t used_bytes{0};
std::size_t executed{0};
std::size_t hook_step{1};
std::size_t host_calls{0};
bool allocator_limit_hit{false};
bool instruction_limit_hit{false};
bool host_call_limit_hit{false};
bool cancel_requested{false};
std::string host_error;
std::vector<Integer> scratch_arguments;
std::vector<HostInvocation> invocations;
};
[[nodiscard]] Context* context_of(lua_State* state)
{
return *static_cast<Context**>(lua_getextraspace(state));
}
/// Polls the cancellation callback. Exceptions thrown by the callback count as
/// a cancellation request so a misbehaving policy can never escape into Lua's
/// C error machinery.
[[nodiscard]] bool cancellation_pending(Context& context)
{
if (context.cancel_requested) {
return true;
}
if (context.cancelled == nullptr || !*context.cancelled) {
return false;
}
try {
if ((*context.cancelled)()) {
context.cancel_requested = true;
}
} catch (...) {
context.cancel_requested = true;
}
return context.cancel_requested;
}
void* limited_alloc(void* user, void* pointer, std::size_t old_size,
std::size_t new_size)
{
auto* context = static_cast<Context*>(user);
if (new_size == 0) {
if (pointer != nullptr) {
context->used_bytes = old_size >= context->used_bytes
? 0
: context->used_bytes - old_size;
std::free(pointer);
}
return nullptr;
}
const std::size_t current = pointer != nullptr ? old_size : 0;
const std::size_t limit = context->limits->max_allocator_bytes;
const std::size_t used = context->used_bytes;
if (new_size > current &&
(used > limit || new_size - current > limit - used)) {
context->allocator_limit_hit = true;
return nullptr;
}
void* result = std::realloc(pointer, new_size);
if (result != nullptr) {
context->used_bytes = used - current + new_size;
}
return result;
}
void instruction_hook(lua_State* state, lua_Debug*)
{
Context* context = context_of(state);
if (cancellation_pending(*context)) {
luaL_error(state, "evaluation cancelled");
}
context->executed += context->hook_step;
if (context->executed >= context->limits->max_instructions) {
context->instruction_limit_hit = true;
luaL_error(state, "instruction limit exceeded");
}
}
/// Removes the base-library entry points that reach outside the sandbox.
void harden_base(lua_State* state)
{
const char* const removed[] = {"load", "loadfile", "dofile",
"print", "collectgarbage"};
for (const char* name : removed) {
lua_pushnil(state);
lua_setglobal(state, name);
}
}
void open_bindings(lua_State* state, const Bindings& bindings)
{
struct Library {
bool enabled;
const char* name;
lua_CFunction open;
};
const Library libraries[] = {
{bindings.base, LUA_GNAME, luaopen_base},
{bindings.table, LUA_TABLIBNAME, luaopen_table},
{bindings.string, LUA_STRLIBNAME, luaopen_string},
{bindings.math, LUA_MATHLIBNAME, luaopen_math},
{bindings.coroutine, LUA_COLIBNAME, luaopen_coroutine},
};
for (const auto& library : libraries) {
if (!library.enabled) {
continue;
}
luaL_requiref(state, library.name, library.open, 1);
lua_pop(state, 1);
}
if (bindings.base) {
harden_base(state);
}
}
int host_trampoline(lua_State* state)
{
Context* context = context_of(state);
if (cancellation_pending(*context)) {
lua_pushliteral(state, "evaluation cancelled");
return lua_error(state);
}
std::vector<Integer>& arguments = context->scratch_arguments;
arguments.clear();
const int argument_count = lua_gettop(state);
arguments.reserve(static_cast<std::size_t>(argument_count));
for (int index = 1; index <= argument_count; ++index) {
int is_integer = 0;
const lua_Integer value = lua_tointegerx(state, index, &is_integer);
if (is_integer == 0) {
lua_pushliteral(state, "host arguments must be integers");
return lua_error(state);
}
arguments.push_back(static_cast<Integer>(value));
}
const auto host_index = static_cast<std::size_t>(
lua_tointeger(state, lua_upvalueindex(1)));
const Host& host = (*context->hosts)[host_index];
if (context->host_calls >= context->limits->max_host_calls) {
context->host_call_limit_hit = true;
lua_pushliteral(state, "host call limit exceeded");
return lua_error(state);
}
++context->host_calls;
bool succeeded = false;
Integer value = 0;
try {
auto result = host.function(arguments);
if (result.has_value()) {
succeeded = true;
value = *result;
} else {
context->host_error = result.error();
}
} catch (const std::exception& exception) {
context->host_error = exception.what();
} catch (...) {
context->host_error = "host threw an unknown exception";
}
if (!succeeded) {
lua_pushfstring(state, "host '%s' failed: %s", host.name.c_str(),
context->host_error.c_str());
return lua_error(state);
}
try {
context->invocations.push_back(
HostInvocation{.host = host.name,
.arguments = std::move(arguments),
.result = value});
} catch (...) {
lua_pushliteral(state, "host result allocation failed");
return lua_error(state);
}
lua_pushinteger(state, static_cast<lua_Integer>(value));
return 1;
}
[[nodiscard]] std::string last_message(lua_State* state,
std::string_view fallback)
{
const char* message = lua_tostring(state, -1);
return message != nullptr ? std::string{message} : std::string{fallback};
}
} // namespace
std::expected<Result, Error>
LuaEvaluator::evaluate(std::string_view source,
std::span<const Input> inputs) const
{
const Limits& limits = configuration_.limits;
if (inputs.size() > limits.max_inputs) {
return std::unexpected{Error{.kind = ErrorKind::invalid_input,
.message = "too many inputs"}};
}
Context context;
context.limits = &limits;
context.hosts = &configuration_.hosts;
context.cancelled = &configuration_.cancelled;
lua_State* state = lua_newstate(limited_alloc, &context);
if (state == nullptr) {
return std::unexpected{
Error{.kind = ErrorKind::allocator_limit,
.message = "cannot create Lua state"}};
}
*static_cast<Context**>(lua_getextraspace(state)) = &context;
open_bindings(state, configuration_.bindings);
lua_createtable(state, 0, static_cast<int>(inputs.size()));
for (const auto& input : inputs) {
lua_pushinteger(state, static_cast<lua_Integer>(input.value));
lua_seti(state, -2, static_cast<lua_Integer>(input.key));
}
lua_setglobal(state, "input");
for (std::size_t index = 0; index < configuration_.hosts.size(); ++index) {
lua_pushinteger(state, static_cast<lua_Integer>(index));
lua_pushcclosure(state, host_trampoline, 1);
lua_setglobal(state, configuration_.hosts[index].name.c_str());
}
context.hook_step = std::clamp<std::size_t>(limits.max_instructions, 1, 1000);
lua_sethook(state, instruction_hook, LUA_MASKCOUNT,
static_cast<int>(context.hook_step));
if (luaL_loadbufferx(state, source.data(), source.size(), "chunk", "t") !=
LUA_OK) {
std::string message = last_message(state, "compile error");
lua_close(state);
return std::unexpected{
Error{.kind = ErrorKind::compile, .message = std::move(message)}};
}
if (cancellation_pending(context)) {
lua_close(state);
return std::unexpected{
Error{.kind = ErrorKind::cancelled, .message = "evaluation cancelled"}};
}
if (lua_pcall(state, 0, LUA_MULTRET, 0) != LUA_OK) {
std::string message = last_message(state, "runtime error");
ErrorKind kind = ErrorKind::runtime;
if (context.allocator_limit_hit) {
kind = ErrorKind::allocator_limit;
} else if (context.cancel_requested) {
kind = ErrorKind::cancelled;
} else if (context.instruction_limit_hit) {
kind = ErrorKind::instruction_limit;
} else if (context.host_call_limit_hit) {
kind = ErrorKind::host_call_limit;
} else if (!context.host_error.empty()) {
kind = ErrorKind::host_error;
}
lua_close(state);
return std::unexpected{
Error{.kind = kind, .message = std::move(message)}};
}
Result result;
const int result_count = lua_gettop(state);
for (int index = 1; index <= result_count; ++index) {
int is_integer = 0;
const lua_Integer value = lua_tointegerx(state, index, &is_integer);
if (is_integer == 0) {
lua_close(state);
return std::unexpected{
Error{.kind = ErrorKind::runtime,
.message = "script results must be integers"}};
}
if (result.integers.size() >= limits.max_result_integers) {
lua_close(state);
return std::unexpected{
Error{.kind = ErrorKind::result_limit,
.message = "result limit exceeded"}};
}
result.integers.push_back(static_cast<Integer>(value));
}
result.host_calls = std::move(context.invocations);
lua_close(state);
return result;
}
} // namespace Void::Script
#else
namespace Void::Script
{
std::expected<Result, Error>
LuaEvaluator::evaluate(std::string_view, std::span<const Input>) const
{
return std::unexpected{
Error{.kind = ErrorKind::runtime,
.message = "Lua adapter not compiled in"}};
}
} // namespace Void::Script
#endif // VOID_SCRIPT_HAS_LUA
+17
View File
@@ -0,0 +1,17 @@
set(_void_script_lua OFF)
if(VOID_SCRIPT_ENABLE_LUA)
find_package(Lua 5.4 QUIET)
if(LUA_FOUND OR VOID_FETCH_LUA)
set(_void_script_lua ON)
endif()
endif()
if(_void_script_lua)
void_add_module(Script
EXTERNAL_DEPS Lua::Lua
)
target_compile_definitions(Void_Script PUBLIC VOID_SCRIPT_HAS_LUA=1)
else()
message(STATUS "[Void] Lua 5.4 not available - building Script without the Lua adapter")
void_add_module(Script)
endif()
+164 -20
View File
@@ -383,14 +383,25 @@ namespace Void::Sqlite
namespace detail
{
struct ConnectionState {
struct WalUsage {
std::uint64_t size_bytes{0};
std::uint64_t uncheckpointed_bytes{0};
int log_frames{-1};
int checkpointed_frames{-1};
bool frames_known{false};
};
sqlite3* db{nullptr};
std::filesystem::path path{};
OpenOptions options{};
EffectiveCapabilities caps{};
int page_size{0};
bool closing{false};
bool closed{false};
std::size_t live_statements{0};
bool active_transaction{false};
std::uint64_t active_transaction_id{0};
std::uint64_t next_transaction_id{0};
std::size_t open_savepoints{0};
std::vector<std::unique_ptr<ScalarFunctionBox>> scalar_functions{};
@@ -422,6 +433,62 @@ namespace Void::Sqlite
return ec ? 0ULL : static_cast<std::uint64_t>(sz);
}
/// Measures WAL usage with an un-checkpointed-frame count. A passive
/// checkpoint is only attempted once the on-disk WAL reaches
/// `probe_threshold`; below that the file size is already a safe upper
/// bound and no native checkpoint work is done. Passive checkpoints never
/// block writers and never truncate, so this only advances nBackfill when
/// no reader pins the frames. If frame information is unavailable the
/// on-disk size is returned as a conservative fallback.
[[nodiscard]] WalUsage wal_usage(std::uint64_t probe_threshold) noexcept
{
WalUsage usage;
usage.size_bytes = current_wal_size_bytes();
if (usage.size_bytes == 0) {
return usage;
}
if (db == nullptr || usage.size_bytes < probe_threshold) {
usage.uncheckpointed_bytes = usage.size_bytes;
return usage;
}
int log_frames = -1;
int checkpointed_frames = -1;
const int rc = sqlite3_wal_checkpoint_v2(
db, "main", SQLITE_CHECKPOINT_PASSIVE, &log_frames, &checkpointed_frames);
if ((rc == SQLITE_OK || rc == SQLITE_BUSY) && log_frames >= 0 &&
checkpointed_frames >= 0) {
usage.log_frames = log_frames;
usage.checkpointed_frames = checkpointed_frames;
usage.frames_known = true;
const auto remaining = static_cast<std::uint64_t>(
std::max(0, log_frames - checkpointed_frames));
if (page_size > 0) {
usage.uncheckpointed_bytes =
std::min(usage.size_bytes,
remaining * static_cast<std::uint64_t>(page_size));
} else {
usage.uncheckpointed_bytes = usage.size_bytes;
}
return usage;
}
usage.uncheckpointed_bytes = usage.size_bytes;
return usage;
}
/// Clears wrapper transaction bookkeeping when SQLite ended the
/// transaction on its own (autocommit is back on). The original SQLite
/// error is never replaced by this observation.
void observe_autocommit_transition() noexcept
{
if (db != nullptr && active_transaction &&
sqlite3_get_autocommit(db) != 0) {
active_transaction = false;
active_transaction_id = 0;
}
}
~ConnectionState()
{
if (db != nullptr) {
@@ -890,16 +957,20 @@ namespace Void::Sqlite
++m_row_generation;
m_has_row = false;
if (!m_conn->active_transaction &&
sqlite3_stmt_readonly(m_stmt) == 0 &&
m_conn->current_wal_size_bytes() >=
if (!m_conn->active_transaction && sqlite3_stmt_readonly(m_stmt) == 0) {
const auto wal = m_conn->wal_usage(
m_conn->options.limits.wal_stop_writes_threshold_bytes);
if (wal.uncheckpointed_bytes >=
m_conn->options.limits.wal_stop_writes_threshold_bytes) {
return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::overloaded,
"Sqlite: WAL size reached write-admission stop threshold; checkpoint required"));
return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::overloaded,
"Sqlite: un-checkpointed WAL frames reached write-admission stop "
"threshold; checkpoint required"));
}
}
const int rc = sqlite3_step(m_stmt);
m_conn->observe_autocommit_transition();
if (rc == SQLITE_ROW) {
m_has_row = true;
return true;
@@ -1251,13 +1322,44 @@ namespace Void::Sqlite
// ── Transaction ──────────────────────────────────────────────────────────
Transaction::Transaction(std::shared_ptr<detail::ConnectionState> conn) noexcept
: m_conn(std::move(conn)), m_state(TransactionState::Active)
Transaction::Transaction(
std::shared_ptr<detail::ConnectionState> conn,
std::uint64_t id) noexcept
: m_conn(std::move(conn)), m_id(id), m_state(TransactionState::Active)
{
}
void Transaction::refresh_state() const noexcept
{
if (m_state != TransactionState::Active || !m_conn || m_conn->db == nullptr) {
return;
}
const bool owns_connection_transaction =
m_conn->active_transaction && m_conn->active_transaction_id == m_id;
if (!owns_connection_transaction ||
sqlite3_get_autocommit(m_conn->db) != 0) {
m_state = TransactionState::RolledBack;
if (m_conn->active_transaction_id == m_id) {
m_conn->active_transaction = false;
m_conn->active_transaction_id = 0;
}
}
}
TransactionState Transaction::state() const noexcept
{
refresh_state();
return m_state;
}
bool Transaction::is_active() const noexcept
{
return state() == TransactionState::Active;
}
Transaction::~Transaction()
{
refresh_state();
if (m_state == TransactionState::Active) {
auto r = rollback_checked();
if (!r && m_conn) {
@@ -1268,6 +1370,7 @@ namespace Void::Sqlite
Transaction::Transaction(Transaction&& o) noexcept
: m_conn(std::move(o.m_conn)),
m_id(std::exchange(o.m_id, 0)),
m_state(std::exchange(o.m_state, TransactionState::RolledBack))
{
}
@@ -1275,6 +1378,7 @@ namespace Void::Sqlite
Transaction& Transaction::operator=(Transaction&& o) noexcept
{
if (this != &o) {
refresh_state();
if (m_state == TransactionState::Active) {
auto r = rollback_checked();
if (!r && m_conn) {
@@ -1282,6 +1386,7 @@ namespace Void::Sqlite
}
}
m_conn = std::move(o.m_conn);
m_id = std::exchange(o.m_id, 0);
m_state = std::exchange(o.m_state, TransactionState::RolledBack);
}
return *this;
@@ -1289,10 +1394,13 @@ namespace Void::Sqlite
Result<void> Transaction::commit()
{
refresh_state();
if (m_state != TransactionState::Active) {
return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::misuse,
"Sqlite: commit() called on non-active transaction"));
m_state == TransactionState::RolledBack
? "Sqlite: commit() called on a transaction that was already rolled back"
: "Sqlite: commit() called on non-active transaction"));
}
if (!m_conn || m_conn->db == nullptr) {
m_state = TransactionState::RecoveryRequired;
@@ -1309,9 +1417,11 @@ namespace Void::Sqlite
if (sqlite3_get_autocommit(m_conn->db) == 0) {
m_state = TransactionState::Active;
m_conn->active_transaction = true;
m_conn->active_transaction_id = m_id;
} else {
m_state = TransactionState::RolledBack;
m_conn->active_transaction = false;
m_conn->active_transaction_id = 0;
}
return Void::Result::fail(make_sqlite_error(
map_sqlite_rc(fault.fail_next_commit_rc),
@@ -1325,6 +1435,7 @@ namespace Void::Sqlite
if (rc == SQLITE_OK) {
m_state = TransactionState::Committed;
m_conn->active_transaction = false;
m_conn->active_transaction_id = 0;
return {};
}
@@ -1338,9 +1449,11 @@ namespace Void::Sqlite
if (sqlite3_get_autocommit(m_conn->db) == 0) {
m_state = TransactionState::Active;
m_conn->active_transaction = true;
m_conn->active_transaction_id = m_id;
} else {
m_state = TransactionState::RolledBack;
m_conn->active_transaction = false;
m_conn->active_transaction_id = 0;
}
return Void::Result::fail(make_sqlite_error(
@@ -1352,6 +1465,7 @@ namespace Void::Sqlite
Result<void> Transaction::rollback_checked()
{
refresh_state();
if (m_state == TransactionState::RolledBack) {
return {};
}
@@ -1375,6 +1489,7 @@ namespace Void::Sqlite
if (rc == SQLITE_OK || sqlite3_get_autocommit(m_conn->db) != 0) {
m_state = TransactionState::RolledBack;
m_conn->active_transaction = false;
m_conn->active_transaction_id = 0;
return {};
}
@@ -1547,6 +1662,10 @@ namespace Void::Sqlite
state->caps.in_memory = is_memory_path(path);
state->caps.read_only = (state->options.mode == OpenMode::ReadOnly) ||
(sqlite3_db_readonly(raw_db, "main") > 0);
if (auto page_size = query_single_int_pragma(raw_db, "PRAGMA page_size");
page_size && *page_size > 0) {
state->page_size = *page_size;
}
// Disable extension loading by default.
int ext_enabled = 0;
@@ -1675,7 +1794,9 @@ namespace Void::Sqlite
SqliteErrorCode::invalid_argument, "Sqlite: SQL contains embedded NUL byte"));
}
const std::string s{sql};
return exec_raw_sql(m_conn->db, s, "exec");
auto result = exec_raw_sql(m_conn->db, s, "exec");
m_conn->observe_autocommit_transition();
return result;
}
Result<Statement> Database::prepare(std::string_view sql)
@@ -1753,12 +1874,16 @@ namespace Void::Sqlite
SqliteErrorCode::misuse,
"Sqlite: nested begin() rejected; use savepoint() for nested scopes"));
}
if (mode != BeginMode::Deferred &&
m_conn->current_wal_size_bytes() >=
if (mode != BeginMode::Deferred) {
const auto wal = m_conn->wal_usage(
m_conn->options.limits.wal_stop_writes_threshold_bytes);
if (wal.uncheckpointed_bytes >=
m_conn->options.limits.wal_stop_writes_threshold_bytes) {
return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::overloaded,
"Sqlite: WAL size reached write-admission stop threshold; checkpoint required"));
return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::overloaded,
"Sqlite: un-checkpointed WAL frames reached write-admission stop "
"threshold; checkpoint required"));
}
}
const char* sql = "BEGIN";
@@ -1771,7 +1896,11 @@ namespace Void::Sqlite
return Void::Result::fail(std::move(r).error());
}
m_conn->active_transaction = true;
return Transaction{m_conn};
m_conn->active_transaction_id = ++m_conn->next_transaction_id;
if (m_conn->active_transaction_id == 0) {
m_conn->active_transaction_id = ++m_conn->next_transaction_id;
}
return Transaction{m_conn, m_conn->active_transaction_id};
}
Result<Savepoint> Database::savepoint(std::string_view name)
@@ -1912,16 +2041,29 @@ namespace Void::Sqlite
{
ConnectionHealth out;
if (!m_conn) return out;
m_conn->observe_autocommit_transition();
out.live_statements = m_conn->live_statements;
out.active_transaction = m_conn->active_transaction;
out.open_savepoints = m_conn->open_savepoints;
out.wal_size_bytes = m_conn->current_wal_size_bytes();
const auto wal = m_conn->wal_usage(
m_conn->options.limits.wal_checkpoint_threshold_bytes);
out.wal_size_bytes = wal.size_bytes;
out.wal_frames_known = wal.frames_known;
out.wal_log_frames = std::max(0, wal.log_frames);
out.wal_checkpointed_frames = std::max(0, wal.checkpointed_frames);
out.wal_uncheckpointed_frames =
wal.frames_known
? std::max(0, wal.log_frames - wal.checkpointed_frames)
: 0;
out.wal_uncheckpointed_bytes = wal.uncheckpointed_bytes;
out.wal_checkpoint_recommended =
out.wal_size_bytes >= m_conn->options.limits.wal_checkpoint_threshold_bytes;
wal.uncheckpointed_bytes >=
m_conn->options.limits.wal_checkpoint_threshold_bytes;
out.wal_warn_exceeded =
out.wal_size_bytes >= m_conn->options.limits.wal_warn_threshold_bytes;
wal.uncheckpointed_bytes >= m_conn->options.limits.wal_warn_threshold_bytes;
out.wal_write_admission_blocked =
out.wal_size_bytes >= m_conn->options.limits.wal_stop_writes_threshold_bytes;
wal.uncheckpointed_bytes >=
m_conn->options.limits.wal_stop_writes_threshold_bytes;
return out;
}
@@ -2212,6 +2354,8 @@ namespace Void::Sqlite
CheckpointReport rep;
rep.log_frames = std::max(0, log_frames);
rep.checkpointed_frames = std::max(0, ckpt_frames);
rep.uncheckpointed_frames =
std::max(0, rep.log_frames - rep.checkpointed_frames);
rep.busy = (rc == SQLITE_BUSY) || (rep.log_frames > rep.checkpointed_frames);
rep.wal_size_bytes = m_conn->current_wal_size_bytes();
return rep;
+576 -134
View File
@@ -20,139 +20,7 @@
#include <utility>
#include <vector>
#ifdef _WIN32
namespace Void::Process
{
Child::Child(long long,
long long,
bool,
Void::System::OwnedFd,
Void::System::OwnedFd,
Void::System::OwnedFd,
std::chrono::milliseconds) noexcept
{
}
Child::~Child() noexcept = default;
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; }
int Child::stdin_fd() const noexcept { return -1; }
int Child::stdout_fd() const noexcept { return -1; }
int Child::stderr_fd() const noexcept { return -1; }
Void::System::OwnedFd Child::take_stdin_fd() noexcept { return {}; }
Void::System::OwnedFd Child::take_stdout_fd() noexcept { return {}; }
Void::System::OwnedFd Child::take_stderr_fd() noexcept { return {}; }
void Child::close_stdin() noexcept {}
Void::Result::Result<void, Void::Result::Error> Child::send_signal(int) noexcept
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"Process::Child::send_signal: not implemented on Windows")};
}
Void::Result::Result<ExitStatus, Void::Result::Error>
Child::terminate(std::chrono::milliseconds)
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"Process::Child::terminate: not implemented on Windows")};
}
Void::Result::Result<std::optional<ExitStatus>, Void::Result::Error>
Child::try_wait()
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"Process::Child::try_wait: not implemented on Windows")};
}
Void::Result::Result<ExitStatus, Void::Result::Error>
Child::wait_blocking(std::chrono::milliseconds,
std::stop_token,
std::chrono::milliseconds)
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"Process::Child::wait_blocking: not implemented on Windows")};
}
Void::Result::Result<Child, Void::Result::Error> spawn(const SpawnOptions&)
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"Process::spawn: not implemented on Windows")};
}
Void::Result::Result<CommunicateResult, Void::Result::Error>
communicate_blocking(Child&,
std::string_view,
CaptureLimits,
std::chrono::milliseconds,
std::stop_token,
const StreamCallbacks*)
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"Process::communicate_blocking: not implemented on Windows")};
}
Void::Result::Result<Output, Void::Result::Error> run(
const std::filesystem::path&,
std::vector<std::string>,
std::string_view,
std::chrono::milliseconds)
{
return Void::Result::fail("Process::run: not implemented on Windows");
}
Void::Result::Result<Output, Void::Result::Error> run_streaming(
const std::filesystem::path&,
std::vector<std::string>,
const StreamCallbacks&,
std::string_view,
std::chrono::milliseconds)
{
return Void::Result::fail(
"Process::run_streaming: not implemented on Windows");
}
Void::Result::Result<Output, Void::Result::Error>
shell(std::string_view, std::chrono::milliseconds)
{
return Void::Result::fail("Process::shell: not implemented on Windows");
}
Void::Result::Result<void, Void::Result::Error>
reexec(const std::filesystem::path&, const std::vector<std::string>&)
{
return Void::Result::fail("Process::reexec: not implemented on Windows");
}
Void::Result::Result<void, Void::Result::Error> reexec(
const std::filesystem::path&, const std::vector<std::string>&, bool)
{
return Void::Result::fail("Process::reexec: not implemented on Windows");
}
Void::Result::Result<void, Void::Result::Error> enable_subreaper() noexcept
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"Process::enable_subreaper: not supported on Windows")};
}
} // namespace Void::Process
#else // POSIX
#ifndef _WIN32
#include <dirent.h>
#include <fcntl.h>
@@ -740,6 +608,8 @@ void emit_lines_from_offset(const std::string& buf,
} // namespace
Child::Child() noexcept = default;
Child::Child(long long pid,
long long pgid,
bool owns_process_group,
@@ -1327,6 +1197,578 @@ Void::Result::Result<Child, Void::Result::Error>
options.kill_grace};
}
BinarySession::BinarySession(Child child, BinarySessionOptions options)
: child_(std::move(child)),
stdin_(child_.take_stdin_fd()),
stdout_(child_.take_stdout_fd()),
stderr_(child_.take_stderr_fd()),
stdout_eof_(!stdout_.valid()),
stderr_eof_(!stderr_.valid()),
stdin_closed_(!stdin_.valid()),
options_(options)
{
options_.max_stdout_buffer = std::max<std::size_t>(1, options_.max_stdout_buffer);
options_.max_stderr_buffer = std::max<std::size_t>(1, options_.max_stderr_buffer);
if (stdin_.valid()) {
(void)set_nonblock(stdin_.get());
}
if (stdout_.valid()) {
(void)set_nonblock(stdout_.get());
}
if (stderr_.valid()) {
(void)set_nonblock(stderr_.get());
}
}
BinarySession::~BinarySession() noexcept = default;
BinarySession::BinarySession(BinarySession&& other) noexcept
: child_(std::move(other.child_)),
stdin_(std::move(other.stdin_)),
stdout_(std::move(other.stdout_)),
stderr_(std::move(other.stderr_)),
stdout_buffer_(std::move(other.stdout_buffer_)),
stdout_offset_(std::exchange(other.stdout_offset_, 0)),
stderr_buffer_(std::move(other.stderr_buffer_)),
stderr_offset_(std::exchange(other.stderr_offset_, 0)),
stdout_eof_(other.stdout_eof_),
stderr_eof_(other.stderr_eof_),
stdin_closed_(other.stdin_closed_),
stdout_truncated_(other.stdout_truncated_),
stderr_truncated_(other.stderr_truncated_),
options_(other.options_),
cancelled_(other.cancelled_.exchange(false)),
status_(other.status_),
reaped_(other.reaped_)
{
other.stdout_eof_ = true;
other.stderr_eof_ = true;
other.stdin_closed_ = true;
other.reaped_ = true;
}
BinarySession& BinarySession::operator=(BinarySession&& other) noexcept
{
if (this != &other) {
child_ = std::move(other.child_);
stdin_ = std::move(other.stdin_);
stdout_ = std::move(other.stdout_);
stderr_ = std::move(other.stderr_);
stdout_buffer_ = std::move(other.stdout_buffer_);
stdout_offset_ = std::exchange(other.stdout_offset_, 0);
stderr_buffer_ = std::move(other.stderr_buffer_);
stderr_offset_ = std::exchange(other.stderr_offset_, 0);
stdout_eof_ = other.stdout_eof_;
stderr_eof_ = other.stderr_eof_;
stdin_closed_ = other.stdin_closed_;
stdout_truncated_ = other.stdout_truncated_;
stderr_truncated_ = other.stderr_truncated_;
options_ = other.options_;
cancelled_.store(other.cancelled_.exchange(false));
status_ = other.status_;
reaped_ = other.reaped_;
other.stdout_eof_ = true;
other.stderr_eof_ = true;
other.stdin_closed_ = true;
other.reaped_ = true;
}
return *this;
}
Void::Result::Result<BinarySession, Void::Result::Error>
BinarySession::spawn(const SpawnOptions& options, BinarySessionOptions session_options)
{
auto spawned = Process::spawn(options);
if (!spawned.has_value()) {
return std::unexpected{std::move(spawned.error())};
}
return BinarySession{std::move(*spawned), session_options};
}
bool BinarySession::valid() const noexcept { return child_.valid(); }
BinarySession::PollFill BinarySession::poll_fill(
int timeout_ms,
std::span<const std::byte> stdin_data,
std::size_t& stdin_written,
bool discard_on_full)
{
PollFill result;
std::array<struct pollfd, 3> pfds{};
nfds_t nfds = 0;
int stdin_index = -1;
int stdout_index = -1;
int stderr_index = -1;
if (!stdin_data.empty() && stdin_written < stdin_data.size() &&
!stdin_closed_ && stdin_.valid()) {
stdin_index = static_cast<int>(nfds);
pfds[nfds++] = {stdin_.get(), POLLOUT, 0};
}
const std::size_t stdout_used = stdout_buffer_.size() - stdout_offset_;
if (!stdout_eof_ && stdout_.valid() &&
(discard_on_full || stdout_used < options_.max_stdout_buffer)) {
stdout_index = static_cast<int>(nfds);
pfds[nfds++] = {stdout_.get(), POLLIN, 0};
}
const std::size_t stderr_used = stderr_buffer_.size() - stderr_offset_;
if (!stderr_eof_ && stderr_.valid() &&
(discard_on_full || stderr_used < options_.max_stderr_buffer)) {
stderr_index = static_cast<int>(nfds);
pfds[nfds++] = {stderr_.get(), POLLIN, 0};
}
if (nfds == 0) {
result.idle = true;
return result;
}
const int rc = ::poll(pfds.data(), nfds, timeout_ms);
if (rc < 0) {
if (errno == EINTR) {
return result;
}
const int err = errno;
result.failure = BinaryFailureCode::io_error;
result.error = Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"Process::BinarySession: poll failed",
err);
return result;
}
if (rc == 0) {
return result;
}
if (stdin_index >= 0) {
const short revents = pfds[static_cast<std::size_t>(stdin_index)].revents;
if ((revents & POLLOUT) != 0) {
while (stdin_written < stdin_data.size()) {
int write_err = 0;
const ssize_t n = write_pipe_nosigpipe(stdin_.get(),
stdin_data.data() + stdin_written,
stdin_data.size() - stdin_written,
write_err);
if (n > 0) {
stdin_written += static_cast<std::size_t>(n);
continue;
}
if (n == 0) {
break;
}
if (n < 0 && (write_err == EAGAIN || write_err == EWOULDBLOCK)) {
break;
}
stdin_closed_ = true;
stdin_.reset();
result.stdin_broken = true;
break;
}
}
if (!result.stdin_broken &&
(revents & (POLLERR | POLLHUP | POLLNVAL)) != 0 &&
(revents & POLLOUT) == 0) {
stdin_closed_ = true;
stdin_.reset();
result.stdin_broken = true;
}
}
std::array<std::byte, 8192> chunk{};
auto service_read = [&](int index,
int fd,
std::vector<std::byte>& buffer,
std::size_t& offset,
bool& eof,
bool& truncated,
std::size_t cap) {
if (index < 0) {
return;
}
const short revents = pfds[static_cast<std::size_t>(index)].revents;
if ((revents & (POLLIN | POLLHUP | POLLERR | POLLNVAL)) == 0) {
return;
}
for (;;) {
const std::size_t used = buffer.size() - offset;
const std::size_t space = (cap > used) ? (cap - used) : 0;
if (space == 0 && !discard_on_full) {
break;
}
const std::size_t want =
discard_on_full ? chunk.size() : std::min(chunk.size(), space);
if (want == 0) {
break;
}
const ssize_t n = ::read(fd, chunk.data(), want);
if (n > 0) {
if (offset > 0 && offset == buffer.size()) {
buffer.clear();
offset = 0;
}
std::size_t take = static_cast<std::size_t>(n);
if (take > space) {
take = space;
truncated = true;
}
buffer.insert(buffer.end(), chunk.begin(), chunk.begin() + take);
continue;
}
if (n == 0) {
eof = true;
break;
}
if (errno == EINTR) {
continue;
}
if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
}
const int err = errno;
eof = true;
result.failure = BinaryFailureCode::io_error;
result.error = Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"Process::BinarySession: read failed",
err);
break;
}
if ((revents & (POLLHUP | POLLERR | POLLNVAL)) != 0 && !eof) {
eof = true;
}
};
service_read(stdout_index,
stdout_.get(),
stdout_buffer_,
stdout_offset_,
stdout_eof_,
stdout_truncated_,
options_.max_stdout_buffer);
service_read(stderr_index,
stderr_.get(),
stderr_buffer_,
stderr_offset_,
stderr_eof_,
stderr_truncated_,
options_.max_stderr_buffer);
return result;
}
Void::Result::Result<BinaryTransfer, BinaryError> BinarySession::write_stdin(
std::span<const std::byte> data,
std::chrono::milliseconds timeout,
std::stop_token stop)
{
if (!valid()) {
return std::unexpected{BinaryError{
0,
false,
BinaryFailureCode::closed,
Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"Process::BinarySession::write_stdin: invalid session")}};
}
BinaryTransfer transfer;
if (data.empty()) {
return transfer;
}
if (stdin_closed_ || !stdin_.valid()) {
return std::unexpected{BinaryError{
0,
false,
BinaryFailureCode::closed,
Void::System::make_system_error(
Void::System::SystemErrorCode::busy,
"Process::BinarySession::write_stdin: stdin is closed")}};
}
const bool has_deadline = timeout.count() > 0;
const auto deadline = std::chrono::steady_clock::now() + timeout;
std::size_t written = 0;
while (written < data.size()) {
if (cancelled_.load(std::memory_order_acquire) || stop.stop_requested()) {
return std::unexpected{BinaryError{
written,
false,
BinaryFailureCode::cancelled,
Void::System::make_system_error(
Void::System::SystemErrorCode::cancelled,
"Process::BinarySession::write_stdin: cancelled")}};
}
if (has_deadline && std::chrono::steady_clock::now() >= deadline) {
return std::unexpected{BinaryError{
written,
false,
BinaryFailureCode::timeout,
Void::System::make_system_error(
Void::System::SystemErrorCode::timed_out,
"Process::BinarySession::write_stdin: timed out")}};
}
int poll_timeout_ms = -1;
if (has_deadline) {
const auto remaining =
std::chrono::duration_cast<std::chrono::milliseconds>(
deadline - std::chrono::steady_clock::now())
.count();
if (remaining <= 0) {
continue;
}
poll_timeout_ms =
static_cast<int>(std::min<long long>(remaining,
std::numeric_limits<int>::max()));
}
// Bound every wait so cancel() (which may come from another thread)
// and a stop request are observed promptly.
poll_timeout_ms =
(poll_timeout_ms < 0) ? 25 : std::min(poll_timeout_ms, 25);
auto filled = poll_fill(poll_timeout_ms, data, written, false);
if (filled.failure != BinaryFailureCode::none) {
return std::unexpected{BinaryError{
written, false, filled.failure, std::move(filled.error)}};
}
if (filled.stdin_broken) {
return std::unexpected{BinaryError{
written,
false,
BinaryFailureCode::closed,
Void::System::make_system_error(
Void::System::SystemErrorCode::busy,
"Process::BinarySession::write_stdin: child closed stdin")}};
}
if (filled.idle) {
break;
}
}
transfer.bytes = written;
return transfer;
}
Void::Result::Result<BinaryTransfer, BinaryError> BinarySession::read_stdout(
std::span<std::byte> out,
std::chrono::milliseconds timeout,
std::stop_token stop)
{
return read_stream(true, out, timeout, stop);
}
Void::Result::Result<BinaryTransfer, BinaryError> BinarySession::read_stderr(
std::span<std::byte> out,
std::chrono::milliseconds timeout,
std::stop_token stop)
{
return read_stream(false, out, timeout, stop);
}
Void::Result::Result<BinaryTransfer, BinaryError> BinarySession::read_stream(
bool is_stdout,
std::span<std::byte> out,
std::chrono::milliseconds timeout,
std::stop_token stop)
{
if (!valid()) {
return std::unexpected{BinaryError{
0,
false,
BinaryFailureCode::closed,
Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"Process::BinarySession: invalid session")}};
}
BinaryTransfer transfer;
if (out.empty()) {
return transfer;
}
auto& buffer = is_stdout ? stdout_buffer_ : stderr_buffer_;
auto& offset = is_stdout ? stdout_offset_ : stderr_offset_;
bool& eof = is_stdout ? stdout_eof_ : stderr_eof_;
bool& truncated = is_stdout ? stdout_truncated_ : stderr_truncated_;
const bool has_deadline = timeout.count() > 0;
const auto deadline = std::chrono::steady_clock::now() + timeout;
while ((buffer.size() - offset) == 0 && !eof) {
if (cancelled_.load(std::memory_order_acquire) || stop.stop_requested()) {
return std::unexpected{BinaryError{
0,
eof,
BinaryFailureCode::cancelled,
Void::System::make_system_error(
Void::System::SystemErrorCode::cancelled,
"Process::BinarySession: read cancelled")}};
}
if (has_deadline && std::chrono::steady_clock::now() >= deadline) {
return std::unexpected{BinaryError{
0,
eof,
BinaryFailureCode::timeout,
Void::System::make_system_error(
Void::System::SystemErrorCode::timed_out,
"Process::BinarySession: read timed out")}};
}
int poll_timeout_ms = -1;
if (has_deadline) {
const auto remaining =
std::chrono::duration_cast<std::chrono::milliseconds>(
deadline - std::chrono::steady_clock::now())
.count();
if (remaining <= 0) {
continue;
}
poll_timeout_ms =
static_cast<int>(std::min<long long>(remaining,
std::numeric_limits<int>::max()));
}
// Bound every wait so cancel() (which may come from another thread)
// and a stop request are observed promptly.
poll_timeout_ms =
(poll_timeout_ms < 0) ? 25 : std::min(poll_timeout_ms, 25);
std::span<const std::byte> no_stdin{};
std::size_t no_written = 0;
auto filled = poll_fill(poll_timeout_ms,
no_stdin,
no_written,
options_.truncate_output_on_overflow);
if (filled.failure != BinaryFailureCode::none) {
return std::unexpected{BinaryError{
0, eof, filled.failure, std::move(filled.error)}};
}
if (filled.idle) {
break;
}
}
const std::size_t used = buffer.size() - offset;
if (used > 0) {
const std::size_t take = std::min(used, out.size());
std::copy_n(buffer.begin() + static_cast<std::ptrdiff_t>(offset),
take,
out.begin());
offset += take;
transfer.bytes = take;
if (offset == buffer.size()) {
buffer.clear();
offset = 0;
} else if (offset >= 65536 && offset * 2 >= buffer.size()) {
buffer.erase(buffer.begin(),
buffer.begin() + static_cast<std::ptrdiff_t>(offset));
offset = 0;
}
} else if (eof) {
transfer.eof = true;
note_exit();
transfer.exited = reaped_;
transfer.status = status_;
}
transfer.truncated = truncated;
return transfer;
}
void BinarySession::note_exit() noexcept
{
if (reaped_ || !child_.valid()) {
return;
}
auto waited = child_.try_wait();
if (waited.has_value() && waited->has_value()) {
status_ = **waited;
reaped_ = true;
}
}
Void::Result::Result<void, Void::Result::Error> BinarySession::close_stdin()
{
if (stdin_closed_) {
return {};
}
stdin_closed_ = true;
return stdin_.close();
}
Void::Result::Result<ExitStatus, Void::Result::Error> BinarySession::wait(
std::chrono::milliseconds timeout,
std::stop_token stop)
{
if (!child_.valid()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"Process::BinarySession::wait: invalid session")};
}
if (reaped_) {
return status_;
}
const bool has_deadline = timeout.count() > 0;
const auto deadline = std::chrono::steady_clock::now() + timeout;
for (;;) {
auto waited = child_.try_wait();
if (!waited.has_value()) {
return std::unexpected{std::move(waited.error())};
}
if (waited->has_value()) {
status_ = **waited;
reaped_ = true;
return status_;
}
if (cancelled_.load(std::memory_order_acquire) || stop.stop_requested()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::cancelled,
"Process::BinarySession::wait: cancelled")};
}
if (has_deadline && std::chrono::steady_clock::now() >= deadline) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::timed_out,
"Process::BinarySession::wait: timed out")};
}
int poll_timeout_ms = 5;
if (has_deadline) {
const auto remaining =
std::chrono::duration_cast<std::chrono::milliseconds>(
deadline - std::chrono::steady_clock::now())
.count();
poll_timeout_ms = static_cast<int>(std::clamp<long long>(
remaining, 1, static_cast<long long>(poll_timeout_ms)));
}
std::span<const std::byte> no_stdin{};
std::size_t no_written = 0;
auto filled = poll_fill(
poll_timeout_ms, no_stdin, no_written, options_.truncate_output_on_overflow);
if (filled.failure != BinaryFailureCode::none) {
return std::unexpected{std::move(filled.error)};
}
if (filled.idle) {
std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
}
}
Void::Result::Result<ExitStatus, Void::Result::Error> BinarySession::terminate(
std::chrono::milliseconds grace)
{
if (!child_.valid()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"Process::BinarySession::terminate: invalid session")};
}
auto terminated = child_.terminate(grace);
if (terminated.has_value()) {
status_ = *terminated;
reaped_ = true;
}
return terminated;
}
Void::Result::Result<CommunicateResult, Void::Result::Error>
communicate_blocking(Child& child,
std::string_view stdin_data,
@@ -1783,4 +2225,4 @@ Void::Result::Result<void, Void::Result::Error> enable_subreaper() noexcept
} // namespace Void::Process
#endif // _WIN32
#endif // !_WIN32
File diff suppressed because it is too large. Load diff
+1
View File
@@ -34,6 +34,7 @@ void handle_assertion(AssertionResult result)
if (!passed) {
tr->state = TestState::Failed;
++tr->failed_assertions;
}
const std::size_t entry_bytes =
+27 -27
View File
@@ -8,14 +8,14 @@ namespace Void::Testing {
using namespace Void::Testing::Detail::Color;
void ConsoleReporter::on_run_start(const RunConfig&, int total_tests) {
os_ << "\n" << apply(bold_blue, "╭──────────────────────────────────────────────╮") << "\n"
<< apply(bold_blue, "│") << apply(bold_white, " Void Testing") << apply(dim, " v1.0") << std::string(31, ' ') << apply(bold_blue, "│") << "\n"
<< std::format("{}│{} Discovered {} test{}{}│\n", apply(bold_blue, "╰"), apply(dim, ""), apply(bold_white, std::to_string(total_tests)), total_tests != 1 ? "s" : "", std::string(total_tests < 10 ? 33 : 28, ' '))
<< apply(bold_blue, "╰──────────────────────────────────────────────╯") << "\n\n";
os_ << "\n" << Void::Testing::Detail::Color::apply(bold_blue, "╭──────────────────────────────────────────────╮") << "\n"
<< Void::Testing::Detail::Color::apply(bold_blue, "│") << Void::Testing::Detail::Color::apply(bold_white, " Void Testing") << Void::Testing::Detail::Color::apply(dim, " v1.0") << std::string(31, ' ') << Void::Testing::Detail::Color::apply(bold_blue, "│") << "\n"
<< std::format("{}│{} Discovered {} test{}{}│\n", Void::Testing::Detail::Color::apply(bold_blue, "╰"), Void::Testing::Detail::Color::apply(dim, ""), Void::Testing::Detail::Color::apply(bold_white, std::to_string(total_tests)), total_tests != 1 ? "s" : "", std::string(total_tests < 10 ? 33 : 28, ' '))
<< Void::Testing::Detail::Color::apply(bold_blue, "╰──────────────────────────────────────────────╯") << "\n\n";
}
void ConsoleReporter::on_suite_start(const std::string& suite_name, int test_count) {
os_ << std::format(" {} {} [{} test{}]\n", apply(bold_blue, "◆"), apply(bold_white, suite_name), apply(dim, std::to_string(test_count)), test_count != 1 ? "s" : "");
os_ << std::format(" {} {} [{} test{}]\n", Void::Testing::Detail::Color::apply(bold_blue, "◆"), Void::Testing::Detail::Color::apply(bold_white, suite_name), Void::Testing::Detail::Color::apply(dim, std::to_string(test_count)), test_count != 1 ? "s" : "");
}
void ConsoleReporter::on_test_start(const TestCase&) {}
@@ -25,46 +25,46 @@ void ConsoleReporter::on_test_end(const TestResult& result) {
double ms = std::chrono::duration<double, std::milli>(result.duration).count();
std::string time_str = ms < 1.0 ? std::format("{:.3f}ms", ms) : std::format("{:.1f}ms", ms);
std::string tags_str;
if (!result.tags.empty()) { for(const auto& t : result.tags) tags_str += "[" + t + "]"; tags_str = " " + apply(dim, tags_str); }
if (!result.tags.empty()) { for(const auto& t : result.tags) tags_str += "[" + t + "]"; tags_str = " " + Void::Testing::Detail::Color::apply(dim, tags_str); }
switch (result.state) {
case TestState::Passed: os_ << std::format(" {} {:<40s}{}{}\n", apply(bold_green, "✔"), apply(green, result.name), tags_str, apply(dim, time_str)); break;
case TestState::Passed: os_ << std::format(" {} {:<40s}{}{}\n", Void::Testing::Detail::Color::apply(bold_green, "✔"), Void::Testing::Detail::Color::apply(green, result.name), tags_str, Void::Testing::Detail::Color::apply(dim, time_str)); break;
case TestState::Failed:
os_ << std::format(" {} {:<40s}{}{}\n", apply(bold_red, "✘"), apply(red, result.name), tags_str, apply(dim, time_str));
os_ << std::format(" {} {:<40s}{}{}\n", Void::Testing::Detail::Color::apply(bold_red, "✘"), Void::Testing::Detail::Color::apply(red, result.name), tags_str, Void::Testing::Detail::Color::apply(dim, time_str));
for (const auto& ar : result.assertions) if (!ar.passed) print_assertion_failure(ar);
if (!result.crash_info.empty()) print_crash_info(result);
break;
case TestState::Skipped: os_ << std::format(" {} {:<40s}{}\n", apply(bold_yellow, "⊘"), apply(yellow, result.name), apply(dim, std::format("[SKIPPED: {}]", result.skip_reason.empty() ? "no reason" : result.skip_reason))); break;
case TestState::Crashed: os_ << std::format(" {} {:<40s}{}\n", apply(bold_red, "⚡"), apply(red, result.name), apply(dim, time_str)); print_crash_info(result); break;
case TestState::Skipped: os_ << std::format(" {} {:<40s}{}\n", Void::Testing::Detail::Color::apply(bold_yellow, "⊘"), Void::Testing::Detail::Color::apply(yellow, result.name), Void::Testing::Detail::Color::apply(dim, std::format("[SKIPPED: {}]", result.skip_reason.empty() ? "no reason" : result.skip_reason))); break;
case TestState::Crashed: os_ << std::format(" {} {:<40s}{}\n", Void::Testing::Detail::Color::apply(bold_red, "⚡"), Void::Testing::Detail::Color::apply(red, result.name), Void::Testing::Detail::Color::apply(dim, time_str)); print_crash_info(result); break;
}
}
void ConsoleReporter::print_assertion_failure(const AssertionResult& ar) {
os_ << apply(red, " ╭─── Assertion Failed") << apply(dim, " ──────────────────────╮") << "\n";
os_ << Void::Testing::Detail::Color::apply(red, " ╭─── Assertion Failed") << Void::Testing::Detail::Color::apply(dim, " ──────────────────────╮") << "\n";
std::filesystem::path p{ar.location.file_name()};
os_ << std::format(" │ {}:{}\n", apply(bold_white, p.filename().string()), ar.location.line());
if (!ar.expression.empty()) os_ << std::format(" │ {}\n", apply(cyan, ar.expression));
if (!ar.expected_repr.empty()) os_ << std::format(" │ {} {}\n", apply(bold_white, "expected:"), apply(green, ar.expected_repr));
if (!ar.actual_repr.empty()) os_ << std::format(" │ {} {}\n", apply(bold_white, "actual: "), apply(red, ar.actual_repr));
os_ << std::format(" │ {}:{}\n", Void::Testing::Detail::Color::apply(bold_white, p.filename().string()), ar.location.line());
if (!ar.expression.empty()) os_ << std::format(" │ {}\n", Void::Testing::Detail::Color::apply(cyan, ar.expression));
if (!ar.expected_repr.empty()) os_ << std::format(" │ {} {}\n", Void::Testing::Detail::Color::apply(bold_white, "expected:"), Void::Testing::Detail::Color::apply(green, ar.expected_repr));
if (!ar.actual_repr.empty()) os_ << std::format(" │ {} {}\n", Void::Testing::Detail::Color::apply(bold_white, "actual: "), Void::Testing::Detail::Color::apply(red, ar.actual_repr));
if (!ar.message.empty()) os_ << std::format(" │ {}\n", ar.message);
os_ << apply(red, " ╰────────────────────────────────────────────╯") << "\n";
os_ << Void::Testing::Detail::Color::apply(red, " ╰────────────────────────────────────────────╯") << "\n";
}
void ConsoleReporter::print_crash_info(const TestResult& result) {
os_ << apply(bold_red, " ╭─── Crash") << apply(dim, " ───────────────────────────╮") << "\n";
if (!result.crash_info.empty()) os_ << std::format(" │ {}\n", apply(red, result.crash_info));
os_ << apply(bold_red, " ╰────────────────────────────────────────────╯") << "\n";
if (!result.stacktrace.empty()) os_ << apply(dim, " Stacktrace:\n") << result.stacktrace << "\n";
os_ << Void::Testing::Detail::Color::apply(bold_red, " ╭─── Crash") << Void::Testing::Detail::Color::apply(dim, " ───────────────────────────╮") << "\n";
if (!result.crash_info.empty()) os_ << std::format(" │ {}\n", Void::Testing::Detail::Color::apply(red, result.crash_info));
os_ << Void::Testing::Detail::Color::apply(bold_red, " ╰────────────────────────────────────────────╯") << "\n";
if (!result.stacktrace.empty()) os_ << Void::Testing::Detail::Color::apply(dim, " Stacktrace:\n") << result.stacktrace << "\n";
}
void ConsoleReporter::on_run_end(const RunResult& result) {
os_ << "\n" << apply(dim, "╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍") << "\n"
<< std::format(" {} tests: ", apply(bold_white, std::to_string(result.total)));
if (result.passed > 0) os_ << std::format("{} {} ", apply(bold_green, std::to_string(result.passed)), apply(green, "✔"));
if (result.failed + result.crashed > 0) os_ << std::format("{} {} ", apply(bold_red, std::to_string(result.failed + result.crashed)), apply(red, "✘"));
if (result.skipped > 0) os_ << std::format("{} {} ", apply(bold_yellow, std::to_string(result.skipped)), apply(yellow, "⊘"));
os_ << "\n" << Void::Testing::Detail::Color::apply(dim, "╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍") << "\n"
<< std::format(" {} tests: ", Void::Testing::Detail::Color::apply(bold_white, std::to_string(result.total)));
if (result.passed > 0) os_ << std::format("{} {} ", Void::Testing::Detail::Color::apply(bold_green, std::to_string(result.passed)), Void::Testing::Detail::Color::apply(green, "✔"));
if (result.failed + result.crashed > 0) os_ << std::format("{} {} ", Void::Testing::Detail::Color::apply(bold_red, std::to_string(result.failed + result.crashed)), Void::Testing::Detail::Color::apply(red, "✘"));
if (result.skipped > 0) os_ << std::format("{} {} ", Void::Testing::Detail::Color::apply(bold_yellow, std::to_string(result.skipped)), Void::Testing::Detail::Color::apply(yellow, "⊘"));
double total_ms = std::chrono::duration<double, std::milli>(result.total_duration).count();
os_ << std::format(" {} {}\n", apply(dim, "in"), apply(bold_cyan, total_ms < 1000 ? std::format("{:.1f}ms", total_ms) : std::format("{:.2f}s", total_ms / 1000.0)))
<< apply(dim, "╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍") << "\n\n";
os_ << std::format(" {} {}\n", Void::Testing::Detail::Color::apply(dim, "in"), Void::Testing::Detail::Color::apply(bold_cyan, total_ms < 1000 ? std::format("{:.1f}ms", total_ms) : std::format("{:.2f}s", total_ms / 1000.0)))
<< Void::Testing::Detail::Color::apply(dim, "╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍") << "\n\n";
}
} // namespace Void::Testing
+44 -42
View File
@@ -115,6 +115,12 @@ namespace Void::Testing
return false;
}
}
// Failures are counted when recorded (TestResult::failed_assertions),
// independently of the bounded assertion vector kept for reporting.
[[nodiscard]] bool has_recorded_failure(const TestResult& result) noexcept
{
return result.failed_assertions > 0;
}
} // namespace
RunConfig Runner::parse_args(int argc, char** argv)
@@ -325,9 +331,7 @@ namespace Void::Testing
if (result.state != TestState::Skipped &&
result.state != TestState::Crashed) {
bool any = std::any_of(
result.assertions.begin(), result.assertions.end(),
[](const auto& a) { return !a.passed; });
const bool any = has_recorded_failure(result);
// An exception that escaped the body fails it too, with no failed
// assertion recorded.
const bool unhandled = !result.crash_info.empty() || !result.cleanup_error.empty();
@@ -376,9 +380,7 @@ namespace Void::Testing
if (result.state != TestState::Skipped &&
result.state != TestState::Crashed) {
bool any = std::any_of(
result.assertions.begin(), result.assertions.end(),
[](const auto& a) { return !a.passed; });
const bool any = has_recorded_failure(result);
// An exception that escaped the body fails it too, with no failed
// assertion recorded.
const bool unhandled = !result.crash_info.empty() || !result.cleanup_error.empty();
@@ -447,7 +449,7 @@ namespace Void::Testing
std::cout
<< "\n"
<< apply(bold_blue,
<< Void::Testing::Detail::Color::apply(bold_blue,
"\xe2\x95\xad\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
@@ -461,12 +463,12 @@ namespace Void::Testing
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
"\xe2\x94\x80\xe2\x94\x80\xe2\x95\xae")
<< "\n"
<< apply(bold_blue, "\xe2\x94\x82")
<< apply(bold_white, " Void Testing")
<< apply(dim, " \xe2\x80\x94 Command Line Interface")
<< std::string(28, ' ') << apply(bold_blue, "\xe2\x94\x82")
<< Void::Testing::Detail::Color::apply(bold_blue, "\xe2\x94\x82")
<< Void::Testing::Detail::Color::apply(bold_white, " Void Testing")
<< Void::Testing::Detail::Color::apply(dim, " \xe2\x80\x94 Command Line Interface")
<< std::string(28, ' ') << Void::Testing::Detail::Color::apply(bold_blue, "\xe2\x94\x82")
<< "\n"
<< apply(bold_blue,
<< Void::Testing::Detail::Color::apply(bold_blue,
"\xe2\x95\xb0\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
@@ -481,76 +483,76 @@ namespace Void::Testing
"\xe2\x94\x80\xe2\x94\x80\xe2\x95\xaf")
<< "\n"
<< "\n"
<< " " << apply(bold_white, "USAGE:") << "\n"
<< " " << apply(cyan, "<executable>") << " "
<< apply(dim, "[options]") << "\n"
<< " " << Void::Testing::Detail::Color::apply(bold_white, "USAGE:") << "\n"
<< " " << Void::Testing::Detail::Color::apply(cyan, "<executable>") << " "
<< Void::Testing::Detail::Color::apply(dim, "[options]") << "\n"
<< "\n"
<< " " << apply(bold_white, "OPTIONS:") << "\n";
<< " " << Void::Testing::Detail::Color::apply(bold_white, "OPTIONS:") << "\n";
constexpr std::size_t OPT_WIDTH = 23;
auto opt = [&](std::string_view name) {
#ifdef VOID_HAS_TEXT
return apply(green, Void::Str::pad_right(name, OPT_WIDTH));
return Void::Testing::Detail::Color::apply(green, Void::Str::pad_right(name, OPT_WIDTH));
#else
std::string s{name};
if (s.size() < OPT_WIDTH) {
s.append(OPT_WIDTH - s.size(), ' ');
}
return apply(green, s);
return Void::Testing::Detail::Color::apply(green, s);
#endif
};
std::cout
<< " " << opt("--filter <pattern>")
<< apply(dim, "Run tests matching the regex pattern") << "\n"
<< Void::Testing::Detail::Color::apply(dim, "Run tests matching the regex pattern") << "\n"
<< " " << opt("--suite <name>")
<< apply(dim, "Run only tests in the specified suite") << "\n"
<< Void::Testing::Detail::Color::apply(dim, "Run only tests in the specified suite") << "\n"
<< " " << opt("--tag <name>")
<< apply(dim, "Run only tests with the specified tag") << "\n"
<< Void::Testing::Detail::Color::apply(dim, "Run only tests with the specified tag") << "\n"
<< " " << opt("--list")
<< apply(dim, "List discovered tests without running them")
<< Void::Testing::Detail::Color::apply(dim, "List discovered tests without running them")
<< "\n"
<< " " << opt("--shuffle")
<< apply(dim, "Randomize the order of test execution") << "\n"
<< Void::Testing::Detail::Color::apply(dim, "Randomize the order of test execution") << "\n"
<< " " << opt("--seed <n>")
<< apply(dim, "Set the random seed (implies --shuffle)") << "\n"
<< Void::Testing::Detail::Color::apply(dim, "Set the random seed (implies --shuffle)") << "\n"
<< " " << opt("--repeat <n>")
<< apply(dim, "Repeat the test run n times") << "\n"
<< Void::Testing::Detail::Color::apply(dim, "Repeat the test run n times") << "\n"
<< " " << opt("--reporter <type>")
<< apply(dim, "Choose the output reporter: console, junit")
<< Void::Testing::Detail::Color::apply(dim, "Choose the output reporter: console, junit")
<< "\n"
<< " " << opt("--output <file>")
<< apply(dim, "Write reporter output to a file") << "\n"
<< Void::Testing::Detail::Color::apply(dim, "Write reporter output to a file") << "\n"
#ifdef VOID_HAS_LOG
<< " " << opt("--log-file <file>")
<< apply(dim,
<< Void::Testing::Detail::Color::apply(dim,
"Mirror test events to <file> via Void::Logging")
<< "\n"
#endif
#ifdef VOID_HAS_ASYNC
<< " " << opt("--parallel <n>")
<< apply(dim,
<< Void::Testing::Detail::Color::apply(dim,
"Run tests across n threads (no crash detection)")
<< "\n"
#endif
<< " " << opt("--verbose")
<< apply(dim, "Enable verbose output") << "\n"
<< Void::Testing::Detail::Color::apply(dim, "Enable verbose output") << "\n"
<< " " << opt("--no-color")
<< apply(dim, "Disable colored console output") << "\n"
<< Void::Testing::Detail::Color::apply(dim, "Disable colored console output") << "\n"
<< " " << opt("--allow-empty")
<< apply(dim, "Do not fail when selection matches zero tests") << "\n"
<< Void::Testing::Detail::Color::apply(dim, "Do not fail when selection matches zero tests") << "\n"
<< " " << opt("--help")
<< apply(dim, "Show this help message") << "\n"
<< Void::Testing::Detail::Color::apply(dim, "Show this help message") << "\n"
<< "\n"
<< " " << apply(bold_white, "EXAMPLES:") << "\n"
<< " " << apply(cyan, "./run_tests") << " "
<< apply(yellow, "--filter") << " \"math_tests.*\"" << "\n"
<< " " << apply(cyan, "./run_tests") << " "
<< apply(yellow, "--tag") << " integration "
<< apply(yellow, "--shuffle") << "\n"
<< " " << apply(cyan, "./run_tests") << " "
<< apply(yellow, "--reporter") << " junit "
<< apply(yellow, "--output") << " results.xml" << "\n"
<< " " << Void::Testing::Detail::Color::apply(bold_white, "EXAMPLES:") << "\n"
<< " " << Void::Testing::Detail::Color::apply(cyan, "./run_tests") << " "
<< Void::Testing::Detail::Color::apply(yellow, "--filter") << " \"math_tests.*\"" << "\n"
<< " " << Void::Testing::Detail::Color::apply(cyan, "./run_tests") << " "
<< Void::Testing::Detail::Color::apply(yellow, "--tag") << " integration "
<< Void::Testing::Detail::Color::apply(yellow, "--shuffle") << "\n"
<< " " << Void::Testing::Detail::Color::apply(cyan, "./run_tests") << " "
<< Void::Testing::Detail::Color::apply(yellow, "--reporter") << " junit "
<< Void::Testing::Detail::Color::apply(yellow, "--output") << " results.xml" << "\n"
<< "\n";
return {};
+48 -2
View File
@@ -11,6 +11,21 @@ get_property(ACTIVE_HEADERS GLOBAL PROPERTY VOID_ACTIVE_PUBLIC_HEADERS)
function(_void_test_requires_satisfied src_file active_modules active_headers out_var)
file(READ "${src_file}" _src_content)
# Whole-file capability gates. The test scanner is line-based and does not
# evaluate preprocessor conditionals, so a file whose tests live inside
# `#ifdef VOID_HAS_*_REFLECTION` would still get registrations generated
# for functions that are not defined. Such files declare
# `// @requires-reflection` and are skipped when the compiler cannot do
# C++26 reflection.
if(NOT VOID_HAS_CXX26_REFLECTION)
string(FIND "${_src_content}" "// @requires-reflection" _needs_reflection)
if(NOT _needs_reflection EQUAL -1)
message(STATUS
"[VoidTests] Skipping ${src_file} (requires C++26 reflection)")
set(${out_var} FALSE PARENT_SCOPE)
return()
endif()
endif()
string(REGEX MATCHALL "#[ \t]*include[ \t]*[<\"](Void/[^/\">]+/[^>\"]+)[>\"]"
_matches "${_src_content}")
set(_ok TRUE)
@@ -114,10 +129,24 @@ endforeach()
if(_all_generated)
add_executable(VoidTests ${_all_generated})
# The generated test translation units belong to VoidTests, not to a module
# target, so the warnings-as-errors policy from void_add_module does not
# reach them unless it is applied here explicitly (X-QA-01).
if(VOID_WARNINGS_AS_ERRORS)
target_compile_options(VoidTests PRIVATE
"$<$<COMPILE_LANGUAGE:CXX>:$<$<CXX_COMPILER_ID:GNU,Clang,AppleClang>:-Wall;-Wextra;-Wpedantic;-Werror;-Wno-missing-field-initializers>>"
# Test helpers live in anonymous namespaces and are captured by
# coroutine frames; GCC's subobject-linkage diagnostic is noise for
# that pattern, not a defect in the test code.
"$<$<COMPILE_LANGUAGE:CXX>:$<$<CXX_COMPILER_ID:GNU>:-Wno-subobject-linkage>>")
endif()
# Disable auto-sweep: we already applied the scanner manually above.
set_target_properties(VoidTests PROPERTIES VOID_TESTING_NO_AUTO_SCAN TRUE)
target_link_libraries(VoidTests PRIVATE Void::Testing)
target_compile_definitions(VoidTests PRIVATE
"VOID_HAS_CXX26_REFLECTION=$<BOOL:${VOID_HAS_CXX26_REFLECTION}>")
foreach(mod ${ACTIVE_MODULES})
if(NOT mod STREQUAL "Testing" AND TARGET Void::${mod})
target_link_libraries(VoidTests PRIVATE Void::${mod})
@@ -158,6 +187,23 @@ if(_all_generated)
)
set_tests_properties(VoidInstalledComponentConsumers PROPERTIES
DEPENDS VoidTests)
add_test(NAME VoidTargetQualification
COMMAND ${CMAKE_COMMAND}
-DVOID_BUILD_DIR=${CMAKE_BINARY_DIR}
-DVOID_SOURCE_DIR=${CMAKE_SOURCE_DIR}
-DVOID_TEST_SOURCE_DIR=${CMAKE_CURRENT_SOURCE_DIR}/package
-DVOID_TEST_ROOT=${CMAKE_CURRENT_BINARY_DIR}/target-qualification
-DVOID_CXX_COMPILER=${CMAKE_CXX_COMPILER}
-DVOID_CTEST_COMMAND=${CMAKE_CTEST_COMMAND}
-DVOID_GENERATOR=${CMAKE_GENERATOR}
-DVOID_MAKE_PROGRAM=${CMAKE_MAKE_PROGRAM}
-DVOID_TARGET=${VOID_TARGET_DETECTED}
-DVOID_CROSSCOMPILING=${CMAKE_CROSSCOMPILING}
-DVOID_BUILD_CONFIG=$<CONFIG>
-P ${CMAKE_CURRENT_SOURCE_DIR}/package/TargetQualification.cmake)
set_tests_properties(VoidTargetQualification PROPERTIES
DEPENDS VoidTests)
endif()
# ── Test-support executables & libraries ──────────────────────────────────────
@@ -167,7 +213,7 @@ if(TARGET VoidTests AND (TARGET Void::System OR TARGET Void::IPC))
add_executable(VoidProcessHelper
"${CMAKE_CURRENT_SOURCE_DIR}/helpers/ProcessHelper.cpp")
set_target_properties(VoidProcessHelper PROPERTIES
CXX_STANDARD 26
CXX_STANDARD ${CMAKE_CXX_STANDARD}
CXX_STANDARD_REQUIRED ON
CXX_EXTENSIONS OFF
VOID_TESTING_NO_AUTO_SCAN TRUE)
@@ -181,7 +227,7 @@ if(TARGET VoidTests AND TARGET Void::Archive)
"${CMAKE_CURRENT_SOURCE_DIR}/helpers/ArchiveWorker.cpp")
target_link_libraries(VoidArchiveWorker PRIVATE Void::Archive)
set_target_properties(VoidArchiveWorker PROPERTIES
CXX_STANDARD 26
CXX_STANDARD ${CMAKE_CXX_STANDARD}
CXX_STANDARD_REQUIRED ON
CXX_EXTENSIONS OFF
VOID_TESTING_NO_AUTO_SCAN TRUE)
+189
View File
@@ -0,0 +1,189 @@
#pragma once
// Shared test-only support for loopback TLS/SMTP fixtures.
#include <Void/Testing/Assert.hpp>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cerrno>
#include <cstdio>
#include <filesystem>
#include <memory>
#include <string>
#include <string_view>
#include <system_error>
#include <utility>
namespace Void::Testing::NetSupport
{
inline std::filesystem::path make_scratch_dir(std::string_view prefix)
{
static unsigned counter = 0;
auto path = std::filesystem::temp_directory_path() /
(std::string{prefix} + std::to_string(::getpid()) + "_" +
std::to_string(counter++));
std::filesystem::create_directories(path);
return path;
}
struct ScratchDir {
std::filesystem::path path;
explicit ScratchDir(std::string_view prefix)
: path(make_scratch_dir(prefix))
{
}
ScratchDir(const ScratchDir&) = delete;
ScratchDir& operator=(const ScratchDir&) = delete;
~ScratchDir()
{
std::error_code ec;
std::filesystem::remove_all(path, ec);
}
};
struct GeneratedCert {
std::filesystem::path cert_file;
std::filesystem::path key_file;
};
inline GeneratedCert
generate_self_signed_cert(const std::filesystem::path& dir,
const char* san_value, const char* tag)
{
using PkeyPtr = std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)>;
using X509Ptr = std::unique_ptr<X509, decltype(&X509_free)>;
using ExtPtr =
std::unique_ptr<X509_EXTENSION, decltype(&X509_EXTENSION_free)>;
PkeyPtr pkey{EVP_RSA_gen(2048), &EVP_PKEY_free};
Void::Testing::require(static_cast<bool>(pkey));
X509Ptr cert{X509_new(), &X509_free};
Void::Testing::require(static_cast<bool>(cert));
X509_set_version(cert.get(), 2);
ASN1_INTEGER_set(X509_get_serialNumber(cert.get()), 1);
X509_gmtime_adj(X509_get_notBefore(cert.get()), -60);
X509_gmtime_adj(X509_get_notAfter(cert.get()), 3600);
X509_set_pubkey(cert.get(), pkey.get());
X509_NAME* name = X509_get_subject_name(cert.get());
X509_NAME_add_entry_by_txt(
name, "CN", MBSTRING_ASC,
reinterpret_cast<const unsigned char*>("127.0.0.1"), -1, -1, 0);
X509_set_issuer_name(cert.get(), name);
X509V3_CTX ctx{};
X509V3_set_ctx_nodb(&ctx);
X509V3_set_ctx(&ctx, cert.get(), cert.get(), nullptr, nullptr, 0);
ExtPtr ext{X509V3_EXT_conf_nid(nullptr, &ctx, NID_subject_alt_name,
const_cast<char*>(san_value)),
&X509_EXTENSION_free};
Void::Testing::require(static_cast<bool>(ext));
Void::Testing::require(X509_add_ext(cert.get(), ext.get(), -1) == 1);
Void::Testing::require(
X509_sign(cert.get(), pkey.get(), EVP_sha256()) > 0);
const auto cert_path = dir / (std::string{"cert_"} + tag + ".pem");
const auto key_path = dir / (std::string{"key_"} + tag + ".pem");
FILE* cf = std::fopen(cert_path.c_str(), "wb");
Void::Testing::require(cf != nullptr);
Void::Testing::require(PEM_write_X509(cf, cert.get()) == 1);
std::fclose(cf);
FILE* kf = std::fopen(key_path.c_str(), "wb");
Void::Testing::require(kf != nullptr);
Void::Testing::require(PEM_write_PrivateKey(
kf, pkey.get(), nullptr, nullptr, 0,
nullptr, nullptr) == 1);
std::fclose(kf);
return GeneratedCert{cert_path, key_path};
}
/// Bound TCP listener on 127.0.0.1 with an ephemeral port.
struct LoopbackListener {
int fd{-1};
std::uint16_t port{0};
LoopbackListener()
{
fd = ::socket(AF_INET, SOCK_STREAM, 0);
Void::Testing::require(fd >= 0);
int yes = 1;
::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes,
sizeof(yes));
sockaddr_in address{};
address.sin_family = AF_INET;
address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
address.sin_port = 0;
Void::Testing::require(
::bind(fd, reinterpret_cast<sockaddr*>(&address),
sizeof(address)) == 0);
socklen_t length = sizeof(address);
Void::Testing::require(
::getsockname(fd, reinterpret_cast<sockaddr*>(&address),
&length) == 0);
port = ntohs(address.sin_port);
Void::Testing::require(::listen(fd, 4) == 0);
}
LoopbackListener(const LoopbackListener&) = delete;
LoopbackListener& operator=(const LoopbackListener&) = delete;
~LoopbackListener()
{
if (fd >= 0) {
::close(fd);
}
}
[[nodiscard]] int accept_one() const
{
return ::accept(fd, nullptr, nullptr);
}
};
inline bool write_all(int fd, std::string_view data)
{
while (!data.empty()) {
const ssize_t written =
::send(fd, data.data(), data.size(), MSG_NOSIGNAL);
if (written <= 0) {
if (written < 0 && errno == EINTR) {
continue;
}
return false;
}
data.remove_prefix(static_cast<std::size_t>(written));
}
return true;
}
/// Read until `delimiter` is found or `max_bytes` is exceeded.
inline std::string read_until(int fd, std::string_view delimiter,
std::size_t max_bytes)
{
std::string buffer;
while (buffer.find(delimiter) == std::string::npos &&
buffer.size() <= max_bytes) {
char chunk[1024];
const ssize_t count = ::recv(fd, chunk, sizeof(chunk), 0);
if (count <= 0) {
break;
}
buffer.append(chunk, static_cast<std::size_t>(count));
}
return buffer;
}
} // namespace Void::Testing::NetSupport
+28
View File
@@ -245,6 +245,31 @@ int mode_grandchild_ignore_sigterm(int argc, char** argv)
::_exit(0);
}
int mode_descendant_holds_stdout(int argc, char** argv)
{
std::int64_t hold_ms = 5000;
if (argc >= 3 && !parse_i64(argv[2], hold_ms)) {
return usage_error("descendant-holds-stdout duration must be an integer");
}
if (hold_ms < 0) {
hold_ms = 0;
}
const pid_t descendant = ::fork();
if (descendant < 0) {
return 1;
}
if (descendant == 0) {
// Keep the inherited stdout write end open while ignoring graceful
// termination, so the parent's reader sees no EOF.
std::signal(SIGTERM, SIG_IGN);
std::this_thread::sleep_for(std::chrono::milliseconds{hold_ms});
::_exit(0);
}
static constexpr char kReady[] = "ready\n";
(void)write_all_fd(STDOUT_FILENO, kReady, sizeof(kReady) - 1);
::_exit(0);
}
int mode_simultaneous_io(int argc, char** argv)
{
if (argc != 3) {
@@ -539,6 +564,9 @@ int main(int argc, char** argv)
if (mode == "grandchild-ignore-sigterm") {
return mode_grandchild_ignore_sigterm(argc, argv);
}
if (mode == "descendant-holds-stdout") {
return mode_descendant_holds_stdout(argc, argv);
}
if (mode == "simultaneous-io") {
return mode_simultaneous_io(argc, argv);
}
@@ -0,0 +1,50 @@
cmake_minimum_required(VERSION 4.0)
project(VoidTargetProfileConsumer LANGUAGES CXX)
# Records and asserts the target tuple of an installed Void package. The
# qualification driver (tests/package/TargetQualification.cmake) passes the
# expected target and then checks the emitted profile file. Core is the
# always-present leaf module; per-module consumption is covered by the other
# tests/package fixtures.
if(NOT DEFINED VOID_EXPECTED_TARGET OR VOID_EXPECTED_TARGET STREQUAL "")
message(FATAL_ERROR "VOID_EXPECTED_TARGET is required")
endif()
find_package(Void CONFIG REQUIRED COMPONENTS Core)
include("${Void_DIR}/void-target-manifest.cmake")
if(NOT VOID_TARGET_MANIFEST_TARGET STREQUAL VOID_EXPECTED_TARGET)
message(FATAL_ERROR
"[TargetProfile] installed manifest target "
"'${VOID_TARGET_MANIFEST_TARGET}' does not match expected "
"'${VOID_EXPECTED_TARGET}'")
endif()
if(NOT Core IN_LIST VOID_TARGET_MANIFEST_MODULES)
message(FATAL_ERROR
"[TargetProfile] installed manifest does not record module 'Core' "
"(modules: ${VOID_TARGET_MANIFEST_MODULES})")
endif()
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/target-profile.txt"
"target=${VOID_TARGET_MANIFEST_TARGET}\n"
"triple=${VOID_TARGET_MANIFEST_TRIPLE}\n"
"compiler=${VOID_TARGET_MANIFEST_COMPILER_ID}-${VOID_TARGET_MANIFEST_COMPILER_VERSION}\n"
"cxx_standard=${VOID_TARGET_MANIFEST_CXX_STANDARD}\n"
"linkage=${VOID_TARGET_MANIFEST_LINKAGE}\n"
"reflection=${VOID_TARGET_MANIFEST_REFLECTION}\n"
"sanitizers=${VOID_TARGET_MANIFEST_SANITIZERS}\n"
"modules=${VOID_TARGET_MANIFEST_MODULES}\n"
)
message(STATUS
"[TargetProfile] target=${VOID_TARGET_MANIFEST_TARGET} "
"triple=${VOID_TARGET_MANIFEST_TRIPLE} "
"compiler=${VOID_TARGET_MANIFEST_COMPILER_ID}-${VOID_TARGET_MANIFEST_COMPILER_VERSION} "
"linkage=${VOID_TARGET_MANIFEST_LINKAGE} "
"reflection=${VOID_TARGET_MANIFEST_REFLECTION}")
add_executable(void_target_profile_consumer main.cpp)
target_link_libraries(void_target_profile_consumer PRIVATE Void::Core)
enable_testing()
add_test(NAME VoidTargetProfileConsumer COMMAND void_target_profile_consumer)
+28
View File
@@ -0,0 +1,28 @@
// Isolated consumer fixture for target qualification. Exercises a small
// runtime behaviour from the always-present Core module so an install/consume
// check covers headers, linkage and the module dependency closure.
#include <Void/Core/CheckedBits.hpp>
#include <Void/Core/Hash.hpp>
#include <Void/Core/Uuid.hpp>
#include <random>
#include <string_view>
int main()
{
std::mt19937_64 rng{11};
const auto uuid = Void::Uuid::v4(rng);
const auto chars = Void::Uuid::format_chars(uuid);
const auto reparsed =
Void::Uuid::parse(std::string_view{chars.data(), chars.size()});
if (!reparsed || *reparsed != uuid) {
return 1;
}
const auto aligned = Void::Bits::checked_align_up(13u, 8u);
if (!aligned || *aligned != 16u) {
return 1;
}
return Void::Hash::fnv1a64("target-profile") != 0 ? 0 : 1;
}
+167
View File
@@ -0,0 +1,167 @@
# Target qualification driver.
#
# 1. Installs the build tree and consumes it through an isolated fixture that
# records the target tuple (target, triple, compiler, linkage, reflection,
# modules) and runs one behaviour per module.
# 2. Re-configures the source tree for negative cases: unknown target,
# unsupported module on a target, and a missing external dependency. Each
# must fail at configure time with a useful message.
# 3. Re-configures the wasm subset positively to prove the allowlist accepts
# a pure computation selection without native networking/SQLite/reflection.
foreach(required IN ITEMS VOID_BUILD_DIR VOID_SOURCE_DIR VOID_TEST_SOURCE_DIR
VOID_TEST_ROOT VOID_CXX_COMPILER VOID_CTEST_COMMAND)
if(NOT DEFINED ${required} OR "${${required}}" STREQUAL "")
message(FATAL_ERROR "${required} is required")
endif()
endforeach()
file(REMOVE_RECURSE "${VOID_TEST_ROOT}")
file(MAKE_DIRECTORY "${VOID_TEST_ROOT}")
set(_gen_args "")
if(DEFINED VOID_GENERATOR AND NOT VOID_GENERATOR STREQUAL "")
list(APPEND _gen_args -G "${VOID_GENERATOR}")
endif()
if(DEFINED VOID_MAKE_PROGRAM AND NOT VOID_MAKE_PROGRAM STREQUAL "")
list(APPEND _gen_args "-DCMAKE_MAKE_PROGRAM=${VOID_MAKE_PROGRAM}")
endif()
# ── 1. Install and consume the current target ─────────────────────────────────
set(_install_prefix "${VOID_TEST_ROOT}/install")
set(_install_command "${CMAKE_COMMAND}" --install "${VOID_BUILD_DIR}"
--prefix "${_install_prefix}")
if(DEFINED VOID_BUILD_CONFIG AND NOT VOID_BUILD_CONFIG STREQUAL "")
list(APPEND _install_command --config "${VOID_BUILD_CONFIG}")
endif()
execute_process(COMMAND ${_install_command} COMMAND_ERROR_IS_FATAL ANY)
set(_consumer_build "${VOID_TEST_ROOT}/TargetProfile")
set(_consumer_source "${VOID_TEST_SOURCE_DIR}/TargetProfile")
set(_no_external_deps
-DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_Threads=TRUE)
execute_process(
COMMAND "${CMAKE_COMMAND}" -S "${_consumer_source}" -B "${_consumer_build}"
${_gen_args}
"-DCMAKE_PREFIX_PATH=${_install_prefix}"
"-DCMAKE_CXX_COMPILER=${VOID_CXX_COMPILER}"
"-DVOID_EXPECTED_TARGET=${VOID_TARGET}"
${_no_external_deps}
COMMAND_ERROR_IS_FATAL ANY)
set(_consumer_build_command "${CMAKE_COMMAND}" --build "${_consumer_build}")
if(DEFINED VOID_BUILD_CONFIG AND NOT VOID_BUILD_CONFIG STREQUAL "")
list(APPEND _consumer_build_command --config "${VOID_BUILD_CONFIG}")
endif()
execute_process(COMMAND ${_consumer_build_command} COMMAND_ERROR_IS_FATAL ANY)
set(_profile_file "${_consumer_build}/target-profile.txt")
if(NOT EXISTS "${_profile_file}")
message(FATAL_ERROR "[TargetQualification] consumer did not record a profile")
endif()
file(READ "${_profile_file}" _profile)
foreach(_field IN ITEMS target triple compiler linkage reflection modules)
if(NOT _profile MATCHES "(^|\n)${_field}=")
message(FATAL_ERROR
"[TargetQualification] profile misses '${_field}':\n${_profile}")
endif()
endforeach()
if(NOT _profile MATCHES "(^|\n)target=${VOID_TARGET}(\n|$)")
message(FATAL_ERROR
"[TargetQualification] profile target mismatch (expected ${VOID_TARGET}):\n${_profile}")
endif()
if(NOT DEFINED VOID_CROSSCOMPILING OR NOT VOID_CROSSCOMPILING)
execute_process(
COMMAND "${VOID_CTEST_COMMAND}" --test-dir "${_consumer_build}"
--output-on-failure
COMMAND_ERROR_IS_FATAL ANY)
endif()
# ── 2. Negative and positive configure cases ─────────────────────────────────
set(_configure_result 0)
set(_configure_output "")
function(run_void_configure name)
set(_build_dir "${VOID_TEST_ROOT}/configure-${name}")
file(REMOVE_RECURSE "${_build_dir}")
execute_process(
COMMAND "${CMAKE_COMMAND}" -S "${VOID_SOURCE_DIR}" -B "${_build_dir}"
${_gen_args}
"-DCMAKE_CXX_COMPILER=${VOID_CXX_COMPILER}"
-DCMAKE_BUILD_TYPE=Debug
${ARGN}
RESULT_VARIABLE _result
OUTPUT_VARIABLE _stdout
ERROR_VARIABLE _stderr)
set(_configure_result "${_result}" PARENT_SCOPE)
set(_configure_output "${_stdout}${_stderr}" PARENT_SCOPE)
set(_configure_build_dir "${_build_dir}" PARENT_SCOPE)
endfunction()
function(expect_configure_failure name pattern)
run_void_configure("${name}" ${ARGN})
if(_configure_result EQUAL 0)
message(FATAL_ERROR
"[TargetQualification] '${name}' configured successfully but "
"was expected to fail")
endif()
if(NOT _configure_output MATCHES "${pattern}")
message(FATAL_ERROR
"[TargetQualification] '${name}' failed without matching "
"'${pattern}'. Output:\n${_configure_output}")
endif()
message(STATUS "[TargetQualification] ${name}: rejected as expected")
endfunction()
# Unknown target profile.
expect_configure_failure(unknown-target "Unknown VOID_TARGET"
-DVOID_TARGET=plan9
-DVOID_ENABLED_MODULES=Core
-DVOID_ENABLE_TESTING=OFF)
# Native module on the browser/Wasm target. IPC pulls IO/Async/Resilience,
# which are also outside the wasm allowlist.
expect_configure_failure(wasm-rejects-native
"Modules not supported on target 'wasm'"
-DVOID_TARGET=wasm
-DVOID_ENABLED_MODULES=IPC
-DVOID_ENABLE_TESTING=OFF)
# Native networking is rejected before Boost/OpenSSL are even resolved.
expect_configure_failure(wasm-rejects-net
"Modules not supported on target 'wasm'"
-DVOID_TARGET=wasm
-DVOID_ENABLED_MODULES=Net
-DVOID_ENABLE_TESTING=OFF)
# Missing external dependency fails with the dependency name.
expect_configure_failure(missing-sqlite "SQLite3"
-DVOID_ENABLED_MODULES=Sqlite
-DVOID_ENABLE_TESTING=OFF
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
# The pure subset must configure for wasm and record the target.
run_void_configure(wasm-subset
-DVOID_TARGET=wasm
-DVOID_ENABLED_MODULES=Data
-DVOID_ENABLE_TESTING=OFF)
if(NOT _configure_result EQUAL 0)
message(FATAL_ERROR
"[TargetQualification] wasm subset failed to configure:\n${_configure_output}")
endif()
set(_manifest "${_configure_build_dir}/void-target-manifest.cmake")
if(NOT EXISTS "${_manifest}")
message(FATAL_ERROR "[TargetQualification] wasm subset wrote no manifest")
endif()
file(READ "${_manifest}" _manifest_text)
if(NOT _manifest_text MATCHES "VOID_TARGET_MANIFEST_TARGET \"wasm\"")
message(FATAL_ERROR
"[TargetQualification] wasm manifest does not record target wasm:\n${_manifest_text}")
endif()
message(STATUS "[TargetQualification] wasm subset: configured and recorded")
@@ -0,0 +1,135 @@
#include <Void/Algorithms/RevisionReadSet.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <cstdint>
#include <map>
#include <optional>
#include <string>
namespace
{
using Void::Algorithms::ReadSetStatus;
using Void::Algorithms::ReadSetValidation;
using Void::Algorithms::RevisionReadSet;
using View = std::map<std::string, std::uint64_t>;
[[nodiscard]] auto lookup(const View& view)
{
return [&view](const std::string& key) -> std::optional<std::uint64_t> {
const auto found = view.find(key);
if (found == view.end()) {
return std::nullopt;
}
return found->second;
};
}
} // namespace
Void::Testing::Test read_set_deduplicates_unchanged_reads()
{
RevisionReadSet set{1};
Void::Testing::expect(set.observe("chunk", 3) == ReadSetStatus::recorded);
Void::Testing::expect(set.observe("chunk", 3) == ReadSetStatus::unchanged);
Void::Testing::expect_eq(set.size(), std::size_t{1});
Void::Testing::expect_eq(set.revision_of("chunk"), std::uint64_t{3});
}
Void::Testing::Test read_set_detects_conflicting_observations()
{
RevisionReadSet set{1};
Void::Testing::expect(set.observe("chunk", 3) == ReadSetStatus::recorded);
Void::Testing::expect(set.observe("chunk", 4) ==
ReadSetStatus::conflicting);
Void::Testing::expect(set.conflicted());
// The first observation is retained, but the set cannot be published.
Void::Testing::expect_eq(set.revision_of("chunk"), std::uint64_t{3});
const View view{{"chunk", 3}};
Void::Testing::expect(set.validate(1, lookup(view)) ==
ReadSetValidation::conflicted);
}
Void::Testing::Test read_set_reports_capacity_exhaustion()
{
RevisionReadSet set{1, RevisionReadSet::Limits{.max_entries = 2}};
Void::Testing::expect(set.observe("a", 1) == ReadSetStatus::recorded);
Void::Testing::expect(set.observe("b", 1) == ReadSetStatus::recorded);
Void::Testing::expect(set.observe("c", 1) ==
ReadSetStatus::capacity_exceeded);
Void::Testing::expect(set.incomplete());
Void::Testing::expect_eq(set.size(), std::size_t{2});
const View view{{"a", 1}, {"b", 1}, {"c", 1}};
Void::Testing::expect(set.validate(1, lookup(view)) ==
ReadSetValidation::incomplete);
}
Void::Testing::Test read_set_validates_against_stable_view()
{
RevisionReadSet set{1};
Void::Testing::expect(set.observe("route", 10) == ReadSetStatus::recorded);
Void::Testing::expect(set.observe("support", 20) ==
ReadSetStatus::recorded);
View view{{"route", 10}, {"support", 20}};
Void::Testing::expect(set.validate(1, lookup(view)) ==
ReadSetValidation::valid);
// An unrelated edit does not invalidate the cached result.
view["unrelated"] = 99;
Void::Testing::expect(set.validate(1, lookup(view)) ==
ReadSetValidation::valid);
// A change to a consulted revision does.
view["support"] = 21;
Void::Testing::expect(set.validate(1, lookup(view)) ==
ReadSetValidation::invalidated);
// A missing consulted key does too.
view["support"] = 20;
view.erase("route");
Void::Testing::expect(set.validate(1, lookup(view)) ==
ReadSetValidation::invalidated);
}
Void::Testing::Test read_set_rejects_epoch_change_even_with_matching_revisions()
{
RevisionReadSet set{1};
Void::Testing::expect(set.observe("route", 10) == ReadSetStatus::recorded);
const View view{{"route", 10}};
Void::Testing::expect(set.validate(2, lookup(view)) ==
ReadSetValidation::epoch_changed);
}
Void::Testing::Test read_set_failed_search_frontier_opening()
{
// A failed search consulted a closed frontier at revision 0.
RevisionReadSet set{7};
Void::Testing::expect(set.observe("frontier", 0) ==
ReadSetStatus::recorded);
View view{{"frontier", 0}};
Void::Testing::expect(set.validate(7, lookup(view)) ==
ReadSetValidation::valid);
// The frontier opens: the cached failure must not be reused.
view["frontier"] = 1;
Void::Testing::expect(set.validate(7, lookup(view)) ==
ReadSetValidation::invalidated);
}
Void::Testing::Test read_set_rejects_empty_key_and_sorts_entries()
{
RevisionReadSet set{1};
Void::Testing::expect(set.observe("", 1) == ReadSetStatus::invalid_key);
Void::Testing::expect_eq(set.size(), std::size_t{0});
Void::Testing::expect(set.observe("b", 2) == ReadSetStatus::recorded);
Void::Testing::expect(set.observe("a", 1) == ReadSetStatus::recorded);
const auto& entries = set.entries();
Void::Testing::require(entries.size() == 2);
Void::Testing::expect_eq(entries.begin()->first, std::string{"a"});
}
+3 -1
View File
@@ -44,7 +44,9 @@ namespace
}
}
void write_raw_tar(const std::filesystem::path& path,
// Used only when the upstream LibArchive backend is absent; keep it
// compiled so the pure-C++ fallback path is covered in that build.
[[maybe_unused]] void write_raw_tar(const std::filesystem::path& path,
std::span<const ArchiveEntry> entries)
{
std::ofstream out{path, std::ios::binary | std::ios::trunc};
+100
View File
@@ -1181,3 +1181,103 @@ Void::Testing::Test async_retry_matches_blocking_schedule_same_seed()
expect_eq(async_log.calls(), std::size_t{6});
expect(async_log.times == blocking_log.times);
}
Void::Testing::Test async_retry_backoff_stop_reason_mapping()
{
using R::RetryStopReason;
// A timeout from the backoff sleep is a deadline, not a user stop.
expect(R::RetryStopReason::deadline_exceeded ==
detail::retry_backoff_stop_reason(make_async_error(AsyncErrorCode::timeout)));
// Everything else is terminal and must never retry without a wait.
for (const AsyncErrorCode code : {AsyncErrorCode::cancelled,
AsyncErrorCode::stopped,
AsyncErrorCode::closed,
AsyncErrorCode::overloaded,
AsyncErrorCode::backend_error,
AsyncErrorCode::limit_exceeded}) {
expect(R::RetryStopReason::stop_requested ==
detail::retry_backoff_stop_reason(make_async_error(code)));
}
// A non-Async domain error is treated conservatively as a stop.
expect(R::RetryStopReason::stop_requested ==
detail::retry_backoff_stop_reason(Void::Result::Error{
Void::Result::ErrorKind::internal,
"foreign domain",
Void::Result::ErrorCode{.domain = 999, .value = 1}}));
}
Void::Testing::Test async_retry_stop_poll_handshake_alternation()
{
// Both deterministic interleavings of "stop requested" and "timer polled"
// must produce exactly one resume, one attempt and one terminal result.
for (const bool stop_first : {true, false}) {
ManualExecutor exec;
ManualClock clock;
auto q = make_queue(exec, clock);
std::stop_source source;
int calls = 0;
RetryProbe<IntOut> probe;
auto task = collect(
retry_async(constant_spec(10ms, 5),
[&calls]() -> std::expected<int, std::string> {
++calls;
return std::unexpected{std::string{"e"}};
},
*q,
OperationOptions{.stop = source.get_token()}),
&probe);
start(task);
expect_eq(calls, 1);
advance_clock(clock, 10ms);
if (stop_first) {
expect(source.request_stop());
(void)q->poll_expired();
} else {
expect_eq(q->poll_expired(), std::size_t{1});
expect(source.request_stop());
}
expect_eq(exec.drain(), std::size_t{1});
expect(task.done());
expect_stop(probe, R::RetryStopReason::stop_requested, 1);
expect_eq(calls, 1);
expect_eq(q->active_timers(), std::size_t{0});
}
}
Void::Testing::Test async_retry_throwing_classifier_propagates()
{
ManualExecutor exec;
ManualClock clock;
auto q = make_queue(exec, clock);
int calls = 0;
RetryProbe<IntOut> probe;
auto classifier = [](const std::string&) -> R::AttemptOutcome {
throw std::runtime_error{"classifier threw"};
};
auto task = collect(
retry_async(constant_spec(10ms, 5),
[&calls]() -> std::expected<int, std::string> {
++calls;
return std::unexpected{std::string{"e"}};
},
*q,
{},
classifier),
&probe);
start(task);
// The classifier exception escapes the retry task; nothing is retried and
// no timer is left armed.
expect(task.done());
expect(probe.threw);
expect_eq(probe.what, std::string{"classifier threw"});
expect_eq(calls, 1);
expect_eq(q->active_timers(), std::size_t{0});
}
@@ -0,0 +1,137 @@
#include <Void/Async/PublicationGatedQueue.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <atomic>
#include <cstdint>
#include <future>
#include <memory>
#include <thread>
#include <utility>
namespace
{
struct Token {
std::uint64_t epoch{0};
std::uint64_t revision{0};
[[nodiscard]] bool operator==(const Token&) const noexcept = default;
};
[[nodiscard]] Token token(std::uint64_t epoch, std::uint64_t revision)
{
return Token{.epoch = epoch, .revision = revision};
}
using Queue =
Void::Async::PublicationGatedQueue<std::unique_ptr<int>, Token>;
using Status = Queue::Status;
} // namespace
Void::Testing::Test gated_queue_rejects_stale_publication_without_moving()
{
Queue queue{token(1, 1), Queue::Limits{.capacity = 4}};
Void::Testing::require(queue.publish(token(1, 2)));
auto payload = std::make_unique<int>(7);
Void::Testing::expect(queue.try_submit(token(1, 1), std::move(payload)) ==
Status::publication_changed);
// The payload was not moved and the queue is unchanged.
Void::Testing::require(payload != nullptr);
Void::Testing::expect_eq(*payload, 7);
Void::Testing::expect_eq(queue.size(), std::size_t{0});
Void::Testing::expect(queue.try_submit(token(1, 2), std::move(payload)) ==
Status::admitted);
Void::Testing::expect(payload == nullptr);
Void::Testing::expect_eq(queue.size(), std::size_t{1});
}
Void::Testing::Test gated_queue_saturation_and_capacity_reuse()
{
Queue queue{token(1, 1), Queue::Limits{.capacity = 1}};
auto first = std::make_unique<int>(1);
Void::Testing::expect(queue.try_submit(token(1, 1), std::move(first)) ==
Status::admitted);
auto second = std::make_unique<int>(2);
Void::Testing::expect(queue.try_submit(token(1, 1), std::move(second)) ==
Status::saturated);
Void::Testing::require(second != nullptr);
auto popped = queue.try_pop();
Void::Testing::require(popped.has_value());
Void::Testing::expect_eq(**popped, 1);
Void::Testing::expect(queue.try_submit(token(1, 1), std::move(second)) ==
Status::admitted);
}
Void::Testing::Test gated_queue_closed()
{
Queue queue{token(1, 1)};
auto pending = std::make_unique<int>(3);
Void::Testing::expect(queue.try_submit(token(1, 1), std::move(pending)) ==
Status::admitted);
queue.close();
Void::Testing::expect(!queue.publish(token(1, 2)));
Void::Testing::expect(queue.closed());
auto rejected = std::make_unique<int>(4);
Void::Testing::expect(queue.try_submit(token(1, 1), std::move(rejected)) ==
Status::closed);
Void::Testing::require(rejected != nullptr);
// Already admitted work can still be drained.
auto popped = queue.try_pop();
Void::Testing::require(popped.has_value());
Void::Testing::expect_eq(**popped, 3);
}
Void::Testing::Test gated_queue_admitted_work_finishes_once()
{
Queue queue{token(1, 1)};
auto payload = std::make_unique<int>(9);
Void::Testing::require(queue.try_submit(token(1, 1), std::move(payload)) ==
Status::admitted);
auto first = queue.try_pop();
Void::Testing::require(first.has_value());
Void::Testing::expect_eq(**first, 9);
Void::Testing::expect(!queue.try_pop().has_value());
}
Void::Testing::Test gated_queue_stale_submission_after_concurrent_publish()
{
Queue queue{token(1, 1)};
std::promise<void> validated;
std::promise<void> published;
std::atomic<Status> status{Status::admitted};
std::unique_ptr<int> retained;
std::thread producer{[&] {
auto payload = std::make_unique<int>(5);
validated.set_value();
published.get_future().wait();
status = queue.try_submit(token(1, 1), std::move(payload));
retained = std::move(payload);
}};
validated.get_future().wait();
// Same epoch, newer revision: the producer's retained publication is
// obsolete before its submission.
Void::Testing::require(queue.publish(token(1, 2)));
published.set_value();
producer.join();
Void::Testing::expect(status.load() == Status::publication_changed);
Void::Testing::require(retained != nullptr);
Void::Testing::expect_eq(*retained, 5);
Void::Testing::expect_eq(queue.size(), std::size_t{0});
// A fresh producer can submit against the new publication.
auto fresh = std::make_unique<int>(6);
Void::Testing::expect(queue.try_submit(token(1, 2), std::move(fresh)) ==
Status::admitted);
}
@@ -1,3 +1,4 @@
// @requires-reflection
#include <Void/Configuration/Argparse.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
+1
View File
@@ -1,3 +1,4 @@
// @requires-reflection
#include <Void/Configuration/Bind.hpp>
#include <Void/Configuration/Config.hpp>
#include <Void/Testing/Assert.hpp>
@@ -1,3 +1,4 @@
// @requires-reflection
#include <Void/Configuration/Bind.hpp>
#include <Void/Configuration/Config.hpp>
#include <Void/Testing/Assert.hpp>
@@ -1,3 +1,4 @@
// @requires-reflection
#include <Void/Configuration/Bind.hpp>
#include <Void/Configuration/Config.hpp>
#include <Void/Configuration/Schema.hpp>
@@ -1,3 +1,4 @@
// @requires-reflection
#include <Void/Async/Executor.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Configuration/ReloadController.hpp>
+4
View File
@@ -16,9 +16,13 @@ namespace
// @tag reflection
Void::Testing::Test debug_dump_reflects_struct_elements()
{
#if !VOID_HAS_CXX26_REFLECTION
Void::Testing::skip("C++26 reflection is not available");
#else
std::vector<P> v{{1, 2}, {3, 4}};
Void::Testing::expect_eq(Void::Containers::debug_dump(v),
std::string{"[P{x: 1, y: 2}, P{x: 3, y: 4}]"});
#endif
}
// @tag reflection
+2 -2
View File
@@ -67,7 +67,7 @@ Void::Testing::Test lru_get_promotes_entry()
c.put(1, "a");
c.put(2, "b");
c.put(3, "c");
c.get(1); // promote 1 to MRU
(void)c.get(1); // promote 1 to MRU
c.put(4, "d"); // evicts 2 (now LRU)
Void::Testing::expect(c.contains(1));
Void::Testing::expect(!c.contains(2));
@@ -106,7 +106,7 @@ Void::Testing::Test lru_peek_does_not_promote()
c.put(1, "a");
c.put(2, "b");
c.put(3, "c");
c.peek(1); // peek 1 but do NOT promote
(void)c.peek(1); // peek 1 but do NOT promote
c.put(4, "d"); // evicts 1 (still LRU despite peek)
Void::Testing::expect(!c.contains(1));
}
+3 -3
View File
@@ -44,7 +44,7 @@ Void::Testing::Test spsc_full_push_returns_false()
Void::Testing::Test spsc_fifo_order()
{
Void::Ring::SpscRing<int, 8> ring;
for (int i = 0; i < 5; ++i) ring.push(i);
for (int i = 0; i < 5; ++i) (void)ring.push(i);
for (int i = 0; i < 5; ++i) {
const auto v = ring.pop();
Void::Testing::expect(v.has_value());
@@ -61,14 +61,14 @@ Void::Testing::Test spsc_capacity_is_n_minus_one()
Void::Testing::Test spsc_full_flag()
{
Void::Ring::SpscRing<int, 4> ring;
ring.push(1); ring.push(2); ring.push(3);
(void)ring.push(1); (void)ring.push(2); (void)ring.push(3);
Void::Testing::expect(ring.full());
}
Void::Testing::Test spsc_string_values()
{
Void::Ring::SpscRing<std::string, 4> ring;
ring.push(std::string{"hello"});
(void)ring.push(std::string{"hello"});
const auto v = ring.pop();
Void::Testing::expect(v.has_value());
Void::Testing::expect_eq(*v, std::string{"hello"});
@@ -0,0 +1,193 @@
#include <Void/Containers/SparsePageTable.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <cstdint>
#include <limits>
#include <optional>
#include <vector>
namespace
{
using Table = Void::Containers::SparsePageTable<std::uint32_t, 2>;
using Address = Table::CellAddress;
using Changed = Table::ChangedPage;
using Edit = Table::Edit;
using EditStatus = Table::EditStatus;
using Page = Table::PageId;
using Revision = Table::Revision;
constexpr std::uint32_t kEmpty = 0;
[[nodiscard]] Address at(std::int64_t x, std::int64_t y = 0,
std::int64_t z = 0)
{
return Address{.x = x, .y = y, .z = z};
}
[[nodiscard]] Page page(std::int64_t x, std::int64_t y = 0,
std::int64_t z = 0)
{
return Page{.x = x, .y = y, .z = z};
}
[[nodiscard]] Edit edit(Address address, std::uint32_t value,
std::optional<Revision> expected = std::nullopt)
{
return Edit{.address = address,
.value = value,
.expected_revision = expected};
}
[[nodiscard]] bool same_changes(const std::vector<Changed>& lhs,
const std::vector<Changed>& rhs)
{
return lhs == rhs;
}
} // namespace
Void::Testing::Test sparse_page_edit_spans_adjacent_pages()
{
Table table{Table::Limits{.max_pages = 4}};
const Edit edits[] = {edit(at(1), 7), edit(at(2), 8)};
auto result = table.apply(edits);
Void::Testing::require(result.committed());
Void::Testing::require(result.changed.size() == 2);
// Changed pages are reported in page order.
Void::Testing::expect(result.changed[0] ==
Changed{.page = page(0), .revision = 1});
Void::Testing::expect(result.changed[1] ==
Changed{.page = page(1), .revision = 1});
Void::Testing::expect_eq(table.get(at(1)), 7u);
Void::Testing::expect_eq(table.get(at(2)), 8u);
Void::Testing::expect_eq(table.page_count(), std::size_t{2});
}
Void::Testing::Test sparse_page_batch_is_atomic_on_stale_revision()
{
Table table{Table::Limits{.max_pages = 4}};
const Edit first[] = {edit(at(1), 7)};
Void::Testing::require(table.apply(first).committed());
const Edit batch[] = {edit(at(0), 1, Revision{1}),
edit(at(2), 9, Revision{5})};
auto result = table.apply(batch);
Void::Testing::expect(result.status == EditStatus::stale_revision);
// Neither page changed.
Void::Testing::expect_eq(table.get(at(0)), kEmpty);
Void::Testing::expect_eq(table.get(at(1)), 7u);
Void::Testing::expect_eq(table.get(at(2)), kEmpty);
Void::Testing::expect_eq(*table.page_revision(page(0)), Revision{1});
Void::Testing::expect(!table.page_revision(page(1)).has_value());
}
Void::Testing::Test sparse_page_budget_exceeded()
{
Table table{Table::Limits{.max_pages = 1}};
const Edit edits[] = {edit(at(0), 1), edit(at(2), 2)};
auto result = table.apply(edits);
Void::Testing::expect(result.status == EditStatus::page_budget_exceeded);
Void::Testing::expect_eq(table.page_count(), std::size_t{0});
}
Void::Testing::Test sparse_page_revision_exhausted()
{
Table table{Table::Limits{.max_pages = 4}};
const Edit first[] = {edit(at(0), 1)};
Void::Testing::require(table.apply(first).committed());
auto state = table.save();
Void::Testing::require(state.pages.size() == 1);
state.pages[0].revision = std::numeric_limits<Revision>::max();
auto restored = Table::restore(state, Table::Limits{.max_pages = 4});
Void::Testing::require(restored.has_value());
const Edit second[] = {edit(at(0), 2)};
auto result = restored->apply(second);
Void::Testing::expect(result.status == EditStatus::revision_exhausted);
Void::Testing::expect_eq(restored->get(at(0)), 1u);
}
Void::Testing::Test sparse_page_duplicate_edit_rejected()
{
Table table{Table::Limits{.max_pages = 4}};
const Edit edits[] = {edit(at(0), 1), edit(at(0), 2)};
auto result = table.apply(edits);
Void::Testing::expect(result.status == EditStatus::duplicate_edit);
Void::Testing::expect_eq(table.page_count(), std::size_t{0});
}
Void::Testing::Test sparse_page_unchanged_value_does_not_bump()
{
Table table{Table::Limits{.max_pages = 4}};
const Edit noop[] = {edit(at(0), kEmpty)};
auto first = table.apply(noop);
Void::Testing::require(first.committed());
Void::Testing::expect(first.changed.empty());
Void::Testing::expect_eq(table.page_count(), std::size_t{0});
const Edit write[] = {edit(at(0), 5)};
Void::Testing::require(table.apply(write).committed());
Void::Testing::expect_eq(*table.page_revision(page(0)), Revision{1});
const Edit repeat[] = {edit(at(0), 5)};
auto again = table.apply(repeat);
Void::Testing::require(again.committed());
Void::Testing::expect(again.changed.empty());
Void::Testing::expect_eq(*table.page_revision(page(0)), Revision{1});
}
Void::Testing::Test sparse_page_permuted_batch_matches()
{
Table first{Table::Limits{.max_pages = 4}};
Table second{Table::Limits{.max_pages = 4}};
const std::vector<Edit> ordered{edit(at(0), 1), edit(at(1), 2),
edit(at(2), 3), edit(at(5), 4)};
std::vector<Edit> permuted{ordered[2], ordered[0], ordered[3], ordered[1]};
auto a = first.apply(ordered);
auto b = second.apply(permuted);
Void::Testing::require(a.committed() && b.committed());
Void::Testing::expect(same_changes(a.changed, b.changed));
for (const auto& edit : ordered) {
Void::Testing::expect_eq(first.get(edit.address),
second.get(edit.address));
}
}
Void::Testing::Test sparse_page_negative_coordinates()
{
Table table{Table::Limits{.max_pages = 4}};
const Edit edits[] = {edit(at(-1), 3), edit(at(-2), 4), edit(at(-3), 5)};
auto result = table.apply(edits);
Void::Testing::require(result.committed());
// PageSize 2: -1 and -2 live in page -1 (offsets 1 and 0); -3 in page -2.
Void::Testing::expect_eq(*table.page_revision(page(-1)), Revision{1});
Void::Testing::expect_eq(*table.page_revision(page(-2)), Revision{1});
Void::Testing::expect_eq(table.get(at(-1)), 3u);
Void::Testing::expect_eq(table.get(at(-2)), 4u);
Void::Testing::expect_eq(table.get(at(-3)), 5u);
}
Void::Testing::Test sparse_page_restore_rejects_invalid_state()
{
Table::State duplicate;
duplicate.pages.push_back(
Table::PageState{.page = page(0), .revision = 1});
duplicate.pages.push_back(
Table::PageState{.page = page(0), .revision = 2});
Void::Testing::expect(
!Table::restore(duplicate, Table::Limits{.max_pages = 4}).has_value());
Table::State too_many;
too_many.pages.push_back(
Table::PageState{.page = page(0), .revision = 1});
too_many.pages.push_back(
Table::PageState{.page = page(1), .revision = 1});
Void::Testing::expect(
!Table::restore(too_many, Table::Limits{.max_pages = 1}).has_value());
}
+1
View File
@@ -1,3 +1,4 @@
// @requires-reflection
#include <Void/Core/Flags.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
+1
View File
@@ -1,3 +1,4 @@
// @requires-reflection
#include <Void/Core/Meta.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
+75 -29
View File
@@ -123,35 +123,8 @@ 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<std::int32_t>(CryptoErrorCode::unsupported_algorithm));
const std::array<std::byte, Ed25519PublicKeySize> dummy_pub{};
const std::array<std::byte, Ed25519SignatureSize> dummy_sig{};
for (const std::size_t bad_key_len : {0U, 1U, 31U, 33U, 64U}) {
std::vector<std::byte> bad_key(bad_key_len, std::byte{0x11});
auto r = verifyEd25519({}, dummy_sig, bad_key);
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(
r.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::invalid_key_size));
}
for (const std::size_t bad_sig_len : {0U, 1U, 63U, 65U}) {
std::vector<std::byte> bad_sig(bad_sig_len, std::byte{0x22});
auto r = verifyEd25519({}, bad_sig, dummy_pub);
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(
r.error().code().value,
static_cast<std::int32_t>(
CryptoErrorCode::invalid_signature_size));
}
return;
}
// Runs on the OpenSSL backend and on the portable built-in backend, so
// the same RFC 8032 vectors qualify both.
struct Rfc8032Vector {
std::string_view seed_hex;
std::string_view pub_hex;
@@ -273,6 +246,79 @@ Void::Testing::Test crypto_ed25519_signing_vectors_and_boundaries()
}
}
Void::Testing::Test crypto_ed25519_convenience_api()
{
using namespace Void::Crypto;
// RFC 8032 TEST 1: seed, public key and empty-message signature.
const auto seed = from_hex(
"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60");
const auto public_key = from_hex(
"d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a");
const auto expected_signature = from_hex(
"e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e06522490155"
"5fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b");
auto signature = ed25519_sign(seed, {});
Void::Testing::require(signature.has_value());
Void::Testing::expect_eq(to_hex(signature->view()),
to_hex(expected_signature));
auto verified = ed25519_verify(public_key, {}, signature->view());
Void::Testing::require(verified.has_value());
Void::Testing::expect(*verified);
// Tampered signature and tampered message return false, not an error.
auto tampered_signature = *signature;
tampered_signature.bytes[0] ^= std::byte{0x01};
auto bad_signature =
ed25519_verify(public_key, {}, tampered_signature.view());
Void::Testing::require(bad_signature.has_value());
Void::Testing::expect(!*bad_signature);
auto bad_message =
ed25519_verify(public_key, as_bytes("not empty"), signature->view());
Void::Testing::require(bad_message.has_value());
Void::Testing::expect(!*bad_message);
// Generated key pair round-trip.
auto keypair = ed25519_keypair();
Void::Testing::require(keypair.has_value());
Void::Testing::expect(keypair->secret_key.valid());
const auto message = as_bytes("VoidBuildSystem provenance");
auto round_signature = ed25519_sign(keypair->secret_key.view(), message);
Void::Testing::require(round_signature.has_value());
auto round_verified = ed25519_verify(keypair->public_key.view(), message,
round_signature->view());
Void::Testing::require(round_verified.has_value());
Void::Testing::expect(*round_verified);
// Wrong-length secret keys and public keys are errors.
for (const std::size_t bad_len : {0U, 1U, 31U, 33U, 64U}) {
std::vector<std::byte> bad_key(bad_len, std::byte{0x11});
auto r = ed25519_sign(bad_key, {});
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(
r.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::invalid_key_size));
auto v = ed25519_verify(bad_key, {}, signature->view());
Void::Testing::require(!v.has_value());
Void::Testing::expect_eq(
v.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::invalid_key_size));
}
for (const std::size_t bad_len : {0U, 1U, 63U, 65U}) {
std::vector<std::byte> bad_signature(bad_len, std::byte{0x22});
auto v = ed25519_verify(public_key, {}, bad_signature);
Void::Testing::require(!v.has_value());
Void::Testing::expect_eq(
v.error().code().value,
static_cast<std::int32_t>(
CryptoErrorCode::invalid_signature_size));
}
}
Void::Testing::Test crypto_hmac_sha256_and_hkdf_sha256_vectors_and_guards()
{
using namespace Void::Crypto;
+395
View File
@@ -0,0 +1,395 @@
#include <Void/Crypto/Crypto.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace
{
int hex_nibble(char c)
{
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'a' && c <= 'f') {
return c - 'a' + 10;
}
if (c >= 'A' && c <= 'F') {
return c - 'A' + 10;
}
return -1;
}
std::vector<std::byte> from_hex(std::string_view hex)
{
Void::Testing::require(hex.size() % 2 == 0);
std::vector<std::byte> out;
out.reserve(hex.size() / 2);
for (std::size_t i = 0; i < hex.size(); i += 2) {
const int hi = hex_nibble(hex[i]);
const int lo = hex_nibble(hex[i + 1]);
Void::Testing::require(hi >= 0 && lo >= 0);
out.push_back(static_cast<std::byte>((hi << 4) | lo));
}
return out;
}
std::string to_hex(std::span<const std::byte> data)
{
static constexpr char kHex[] = "0123456789abcdef";
std::string out;
out.reserve(data.size() * 2);
for (const std::byte b : data) {
const auto v = static_cast<unsigned char>(b);
out.push_back(kHex[v >> 4]);
out.push_back(kHex[v & 0x0F]);
}
return out;
}
std::span<const std::byte> as_bytes(std::string_view text)
{
return std::as_bytes(std::span{text.data(), text.size()});
}
std::string hotp(std::span<const std::byte> secret, std::uint64_t counter,
int digits)
{
std::array<std::byte, 8> message{};
for (std::size_t i = 0; i < message.size(); ++i) {
message[message.size() - 1 - i] =
static_cast<std::byte>((counter >> (8 * i)) & 0xFFU);
}
auto mac = Void::Crypto::hmac_sha1(secret, message);
Void::Testing::require(mac.has_value());
const auto offset = static_cast<std::size_t>(
std::to_integer<unsigned>(mac->back()) & 0x0FU);
const std::uint32_t binary =
((std::to_integer<std::uint32_t>((*mac)[offset]) & 0x7FU) << 24U) |
((std::to_integer<std::uint32_t>((*mac)[offset + 1]) & 0xFFU)
<< 16U) |
((std::to_integer<std::uint32_t>((*mac)[offset + 2]) & 0xFFU)
<< 8U) |
(std::to_integer<std::uint32_t>((*mac)[offset + 3]) & 0xFFU);
std::uint32_t modulus = 1;
for (int i = 0; i < digits; ++i) {
modulus *= 10U;
}
std::string code = std::to_string(binary % modulus);
while (code.size() < static_cast<std::size_t>(digits)) {
code.insert(code.begin(), '0');
}
return code;
}
std::string totp(std::span<const std::byte> secret, std::uint64_t unix_time,
int digits)
{
return hotp(secret, unix_time / 30U, digits);
}
} // namespace
Void::Testing::Test crypto_hmac_sha1_rfc2202_vectors()
{
using namespace Void::Crypto;
const std::array<std::string_view, 6> macs = {
"b617318655057264e28bc0b6fb378c8ef146be00",
"effcdf6ae5eb2fa2d27416d5f184df9c259a7c79",
"125d7342b9ac11cd91a39af48aa17b4f63f175d3",
"4c9007f4026250c6bc8414f9bf50c86c2d7235da",
"aa4ae5e15272d00e95705637ce8a3b55ed402112",
"e8e99d0f45237d786d6bbaa7965c7808bbff1a91"};
const std::vector<std::byte> twenty_0b(20, std::byte{0x0b});
const std::vector<std::byte> twenty_aa(20, std::byte{0xaa});
const std::vector<std::byte> eighty_aa(80, std::byte{0xaa});
const std::vector<std::byte> fifty_dd(50, std::byte{0xdd});
const std::vector<std::byte> fifty_cd(50, std::byte{0xcd});
const auto key4 =
from_hex("0102030405060708090a0b0c0d0e0f10111213141516171819");
// Keys/messages that are not pure hex are supplied directly.
struct RawVector {
std::span<const std::byte> key;
std::span<const std::byte> data;
std::string_view mac_hex;
};
const std::array<RawVector, 6> raw = {{
{twenty_0b, as_bytes("Hi There"), macs[0]},
{as_bytes("Jefe"), as_bytes("what do ya want for nothing?"),
macs[1]},
{twenty_aa, fifty_dd, macs[2]},
{key4, fifty_cd, macs[3]},
{eighty_aa,
as_bytes("Test Using Larger Than Block-Size Key - Hash Key First"),
macs[4]},
{eighty_aa,
as_bytes("Test Using Larger Than Block-Size Key and Larger Than One "
"Block-Size Data"),
macs[5]},
}};
const ProviderOptions builtin{.prefer_builtin = true};
for (const auto& vec : raw) {
for (const auto& opts : {ProviderOptions{}, builtin}) {
if (opts.prefer_builtin == false && !has_openssl_backend()) {
continue;
}
auto mac = hmac_sha1(vec.key, vec.data, opts);
Void::Testing::require(mac.has_value());
Void::Testing::expect_eq(to_hex(*mac), std::string{vec.mac_hex});
}
}
}
Void::Testing::Test crypto_hmac_sha1_boundaries_and_guards()
{
using namespace Void::Crypto;
// Empty key and message are valid.
auto empty = hmac_sha1({}, {});
Void::Testing::require(empty.has_value());
Void::Testing::expect_eq(empty->size(), HmacSha1Size);
// Wrong output size is rejected before touching the buffer.
std::array<std::byte, HmacSha1Size + 1> wrong_size{};
auto bad_size =
hmac_sha1_into(as_bytes("key"), as_bytes("msg"), wrong_size);
Void::Testing::require(!bad_size.has_value());
Void::Testing::expect_eq(
bad_size.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::invalid_argument));
// Overlapping input/output is rejected.
std::array<std::byte, 64> shared{};
shared.fill(std::byte{0x5A});
auto overlap = hmac_sha1_into(std::span{shared}.subspan(0, 20),
std::span{shared}.subspan(20, 20),
std::span{shared}.subspan(0, 20));
Void::Testing::require(!overlap.has_value());
Void::Testing::expect_eq(
overlap.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::overlapping_buffers));
// Injected backend fault wipes the destination.
std::array<std::byte, HmacSha1Size> wiped{};
wiped.fill(std::byte{0xCC});
{
ScopedFaultGuard fault{FaultConfig{FaultOperation::hmac,
CryptoErrorCode::provider_error, 0}};
auto failed = hmac_sha1_into(as_bytes("key"), as_bytes("msg"), wiped);
Void::Testing::require(!failed.has_value());
}
Void::Testing::expect(
std::all_of(wiped.begin(), wiped.end(),
[](std::byte b) { return b == std::byte{0}; }));
// property_query is unavailable on the built-in backend.
ProviderOptions bad_provider{.property_query = "provider=none",
.prefer_builtin = true};
auto unavailable =
hmac_sha1(as_bytes("key"), as_bytes("msg"), bad_provider);
Void::Testing::require(!unavailable.has_value());
Void::Testing::expect_eq(
unavailable.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::provider_error));
}
Void::Testing::Test crypto_hotp_totp_rfc4226_6238_vectors()
{
const auto secret = as_bytes("12345678901234567890");
// RFC 4226 Appendix D.
const std::array<std::string_view, 10> hotp_expected = {
"755224", "287082", "359152", "969429", "338314",
"254676", "287922", "162583", "399871", "520489"};
for (std::uint64_t counter = 0; counter < hotp_expected.size(); ++counter) {
Void::Testing::expect_eq(hotp(secret, counter, 6),
std::string{hotp_expected[counter]});
}
// RFC 6238 Appendix B (SHA-1 rows, 8 digits).
struct TotpVector {
std::uint64_t time;
std::string_view code;
};
const std::array<TotpVector, 6> totp_vectors = {{
{59, "94287082"},
{1111111109, "07081804"},
{1111111111, "14050471"},
{1234567890, "89005924"},
{2000000000, "69279037"},
{20000000000, "65353130"},
}};
for (const auto& vec : totp_vectors) {
Void::Testing::expect_eq(totp(secret, vec.time, 8),
std::string{vec.code});
}
}
Void::Testing::Test crypto_pbkdf2_hmac_sha256_rfc7914_vectors()
{
using namespace Void::Crypto;
const ProviderOptions builtin{.prefer_builtin = true};
// RFC 7914 section 11, first vector (c = 1, 64-byte output).
{
const auto expected = std::string{
"55ac046e56e3089fec1691c22544b605f94185216dde0465e68b9d57c20dacbc"
"49ca9cccf179b645991664b39d77ef317c71b845b1e30bd509112041d3a19783"};
for (const auto& opts : {ProviderOptions{}, builtin}) {
if (!opts.prefer_builtin && !has_openssl_backend()) {
continue;
}
auto derived = pbkdf2_hmac_sha256(as_bytes("passwd"),
as_bytes("salt"), 1, 64, opts);
Void::Testing::require(derived.has_value());
Void::Testing::expect_eq(to_hex(*derived), expected);
}
}
// RFC 7914 section 11, second vector (c = 80000, 64-byte output).
{
auto derived = pbkdf2_hmac_sha256(as_bytes("Password"),
as_bytes("NaCl"), 80000, 64);
Void::Testing::require(derived.has_value());
Void::Testing::expect_eq(
to_hex(*derived),
std::string{
"4ddcd8f60b98be21830cee5ef22701f9641a4418d04c0414aeff"
"08876b34ab56a1d425a1225833549adb841b51c9b3176a272bdebba1d0"
"78478f62b397f33c8d"});
}
}
Void::Testing::Test crypto_pbkdf2_hmac_sha256_boundaries_and_guards()
{
using namespace Void::Crypto;
const auto password = as_bytes("password");
const auto salt = as_bytes("salt");
// Zero and oversized iteration counts are rejected.
for (const std::uint32_t iterations :
{0U, CryptoLimits::kMaxPbkdf2Iterations + 1U}) {
std::array<std::byte, 32> out{};
auto r = pbkdf2_hmac_sha256_into(password, salt, iterations, out);
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(
r.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::invalid_argument));
}
// Oversized salt and output are rejected without mutating the output.
{
std::vector<std::byte> big_salt(CryptoLimits::kMaxPbkdf2SaltBytes + 1U,
std::byte{0x11});
std::array<std::byte, 32> out{};
auto r = pbkdf2_hmac_sha256_into(password, big_salt, 1, out);
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(
r.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::message_too_large));
std::vector<std::byte> big_out(CryptoLimits::kMaxPbkdf2OutputBytes + 1U,
std::byte{0x7A});
auto r_big = pbkdf2_hmac_sha256_into(password, salt, 1, big_out);
Void::Testing::require(!r_big.has_value());
Void::Testing::expect_eq(
r_big.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::output_too_large));
Void::Testing::expect(
std::all_of(big_out.begin(), big_out.end(),
[](std::byte b) { return b == std::byte{0x7A}; }));
std::span<std::byte> empty_out;
auto r_empty = pbkdf2_hmac_sha256_into(password, salt, 1, empty_out);
Void::Testing::require(!r_empty.has_value());
Void::Testing::expect_eq(
r_empty.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::invalid_argument));
// The Digest overload rejects an overflowing length before allocating.
auto r_overflow = pbkdf2_hmac_sha256(
password, salt, 1, std::numeric_limits<std::size_t>::max());
Void::Testing::require(!r_overflow.has_value());
Void::Testing::expect_eq(
r_overflow.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::output_too_large));
}
// Overlapping output is rejected.
{
std::array<std::byte, 64> shared{};
auto r = pbkdf2_hmac_sha256_into(std::span{shared}.subspan(0, 16), {},
1, std::span{shared}.subspan(8, 32));
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(
r.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::overlapping_buffers));
}
// Injected fault wipes the destination.
{
std::array<std::byte, 32> wiped{};
wiped.fill(std::byte{0xCC});
{
ScopedFaultGuard fault{FaultConfig{
FaultOperation::pbkdf2, CryptoErrorCode::provider_error, 0}};
auto r = pbkdf2_hmac_sha256_into(password, salt, 1, wiped);
Void::Testing::require(!r.has_value());
}
Void::Testing::expect(
std::all_of(wiped.begin(), wiped.end(),
[](std::byte b) { return b == std::byte{0}; }));
}
// Empty password and salt are valid; match hashlib reference values.
{
const auto expected = std::string{
"f7ce0b653d2d72a4108cf5abe912ffdd777616dbbb27a70e8204f3ae2d0f6fad"};
for (const auto& opts :
{ProviderOptions{}, ProviderOptions{.prefer_builtin = true}}) {
if (!opts.prefer_builtin && !has_openssl_backend()) {
continue;
}
auto derived = pbkdf2_hmac_sha256({}, {}, 1, 32, opts);
Void::Testing::require(derived.has_value());
Void::Testing::expect_eq(to_hex(*derived), expected);
}
}
// Partial final block and built-in/backend parity.
{
auto odd = pbkdf2_hmac_sha256(password, salt, 2, 33);
Void::Testing::require(odd.has_value());
Void::Testing::expect_eq(odd->size(), 33U);
auto prefix = pbkdf2_hmac_sha256(password, salt, 2, 32);
Void::Testing::require(prefix.has_value());
Void::Testing::expect(
std::equal(prefix->begin(), prefix->end(), odd->begin()));
auto builtin = pbkdf2_hmac_sha256(
password, salt, 2, 33, ProviderOptions{.prefer_builtin = true});
Void::Testing::require(builtin.has_value());
Void::Testing::expect_eq(*builtin, *odd);
auto gitea = pbkdf2_hmac_sha256(as_bytes("password"),
as_bytes("somesalt"), 10000, 32);
Void::Testing::require(gitea.has_value());
Void::Testing::expect_eq(
to_hex(*gitea),
std::string{"f47eaaf9fcacaf867696eaa1d205356d2d029bff08828a05d0dab"
"60b6e0c2de2"});
}
}
Loaded 100 of 134 files, more files were not shown because too many files have changed in this diff. Show more