diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index 46483c0..c8e7a0c 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -1,8 +1,8 @@ # Workflow state Updated: 2026-11-24. -Repository: VoidLibrary; active branch `feat/roadmap-p2-wave5` (from `main` -at `1e901ce`, merged Waves 1–4B and pushed to `origin/main`). +Repository: VoidLibrary; active branch `feat/roadmap-p2-wave6a` (from `main` +at `4479960`, merged Waves 1–5 and pushed to `origin/main`). ## Completed objective @@ -215,8 +215,45 @@ while leaving local untracked files untouched. `binary_reader_u64_be` 2.24 ns, `data_json_parse_small_object` 576.81 ns, `data_json_serialize_small_object` 284.87 ns. +## Verification already observed (Wave 6A — P2 System, SystemAsync, IPC) + +- Wave 6A prep & P2/P3 error domains (`3f67b1e`): reserved `kIpcErrorDomain = 16`.. + `kSqliteErrorDomain = 21` in `Error.hpp`, added thread-safe pipe `ENOTSOCK` fallback in + `EpollDriver.cpp`, enabled `VoidProcessHelper` for `Void::System` OR `Void::IPC`, added + `M-SYSTEM-01-05.md` and `S-IPC-01-03.md`. +- `System` (`fcdbc06`): `System;Testing` (`/tmp/void-w6a-system`, `-Werror`) `System*` + 53/53 passed (226.6 ms); `ctest` 2/2 (`VoidTests` 0.57 s, + `VoidInstalledComponentConsumers` including `SystemOnly` 3.95 s). +- `SystemAsync` (`9a3c5d8`): `SystemAsync;Testing` (`/tmp/void-w6a-sysasync`, `-Werror`) + `SystemAsync*` 2/2 passed (211.5 ms); `ctest` 2/2 (`VoidTests` 1.15 s, + `VoidInstalledComponentConsumers` including `SystemAsyncOnly` 9.43 s). +- `IPC` (`39a48d5`): `IPC;Testing` (`/tmp/void-w6a-ipc`, `-Werror`) `Ipc*` 3/3 passed + (8.8 ms); `ctest` 2/2 (`VoidTests` 0.49 s, `VoidInstalledComponentConsumers` including + `IPCOnly` 12.20 s, total 12.70 s). +- Full RelWithDebInfo + `-DVOID_WARNINGS_AS_ERRORS=ON` (`/tmp/void-w6a-full`, 39 modules, + `39a48d5`): `VoidTests` 1,386 tests — 1,383 passed, 3 intentional skips + (`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (4.68 s); + `ctest` 2/2 passed (`VoidTests` 4.58 s, `VoidInstalledComponentConsumers` 19 consumer + builds incl. `SystemOnly`, `SystemAsyncOnly`, `IPCOnly`, `RelocatedFoundation`, + `RelocatedExternal`, 31.05 s, total 35.63 s). +- Full Debug ASan + UBSan + `-DVOID_WARNINGS_AS_ERRORS=ON` (`/tmp/void-w6a-asan`, 39 + modules, `39a48d5`): `VoidTests` 1,386 tests — 1,383 passed, 3 skipped, 0 failed + (19.34 s), 0 ASan/LSan leaks, 0 UBSan errors. +- Wave 6A Debug TSan subset (`/tmp/void-w6a-tsan`, 14 modules, `39a48d5`): + `Process*|SystemHardening*|SystemAsync*|Ipc*|FileWatcher*|IoDriver*|OperationScope*` + 35/35 passed (609.4 ms), 0 TSan data races. +- `VoidFoundationBench` post-W6A (`rev=39a48d5c0a72`, `/tmp/void-w6a-full/post-w6a.json`): + `harness_empty_loop` 0.38 ns, `core_uuid_parse_hyphenated` 24.92 ns, + `core_uuid_to_string` 17.45 ns, `core_hash_fnv1a64_256b` 181.41 ns, + `core_hash_murmur3_256b` 67.93 ns, `functional_result_ok_chain` 1.13 ns, + `functional_error_with_context` 58.77 ns, `math_checked_add_loop` 0.47 ns, + `containers_spsc_ring_push_pop` 8.80 ns, `containers_lru_get_put` 20.61 ns, + `binary_reader_u64_be` 1.31 ns, `data_json_parse_small_object` 311.16 ns, + `data_json_serialize_small_object` 162.52 ns. + ## Ownership and next step -Waves 1–5 (`P0`, `P1`, and `P2` Operations Foundations: `Observability`, `Resilience`, -`Log`, `Stacktrace`) are complete and verified on `feat/roadmap-p2-wave5`, ready to merge -into `main`, push to `origin`, and proceed continuously to **P2 Wave 6**. +Waves 1–6A (`P0`, `P1`, `P2` Operations Foundations, `System`, `SystemAsync`, and `IPC`) +are complete and verified on `feat/roadmap-p2-wave6a`, ready to merge into `main`, push to +`origin`, and proceed continuously to **Wave 6B (`Crypto`, `Security`, `Archive`, +`Update`)**. diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index 27ce082..5aa78af 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -70,6 +70,15 @@ These tasks author plans. Future feature task IDs inside those plans remain plan | CMake test header check fix | Track `VOID_ACTIVE_PUBLIC_HEADERS` in `cmake/Module.cmake` so `tests/CMakeLists.txt` maps split `EXTRA_HEADERS` (e.g. `Void/Log/Log.hpp` -> `LogState`) accurately (`3d8dfb0`) | — | VERIFIED | `Stacktrace;Testing` discovers and passes `Stacktrace*` 4/4 without `Log`; full suite discovers all 1,378 tests | | M-STACKTRACE-01..04 | `src/Stacktrace/module.cmake` (`INTERNAL_DEPS Functional Time LogState`), split `capture()` (<=256 frames, zero log/source IO) & `Resolver` (1024-entry / 4 MiB cache, `invalidate_module`), `Capabilities`, checked `read_source_snippet_checked` (roots, symlink-escape & `..` rejection, overflow-safe `int64_t` math), `format_resolved_trace`, `write_fatal_signal_marker`, `tests/standalone/Stacktrace/Stacktrace.cpp` (`7b57b35`) | [M-STACKTRACE-01-04](tasks/M-STACKTRACE-01-04.md) | VERIFIED | `Stacktrace;Testing` `Stacktrace*` 4/4 (374.2ms), full RelWithDebInfo (1,375 ✔) & ASan+UBSan (0 leaks/UB) | +## Wave 6A — P2 System, SystemAsync, IPC (`feat/roadmap-p2-wave6a`) + +| ID | Deliverable | Spec | State | Verification summary | +| --- | --- | --- | --- | --- | +| Wave 6A prep, error domains & helper modes | Reserved P2/P3 domain IDs (`kIpcErrorDomain = 16`..`kSqliteErrorDomain = 21`) in `Error.hpp`, thread-safe pipe `ENOTSOCK` fallback in `EpollDriver.cpp`, enabled `VoidProcessHelper` for `Void::System` OR `Void::IPC` with `ignore-sigterm`, `simultaneous-io`, `flood`, `long-line`, `check-fds`, `env-dump`, `cwd`, `ipc-pipe-echo`, task specs (`3f67b1e`) | — | VERIFIED | Compiled cleanly with `-Werror`; verified via Wave 6A `System`, `SystemAsync`, `IPC`, ASan+UBSan, and TSan suites | +| M-SYSTEM-01..05 | Hardened `System` (`Types.hpp`, `Process.{hpp,cpp}`, `Path.hpp`, `Query.hpp`, `TempFile.hpp`, `TempDir.hpp`, `Metrics.hpp`), strict non-shell spawning + fd hygiene, pipe/arg limits, duplex `communicate()` & bounded escalation, `query_process` /proc validation, symlink-safe atomic `TempFile`/`TempDir`, `/bin/sh`-free `ProcessStream.cpp`, `SystemHardening.cpp`, `SystemOnly` consumer (`fcdbc06`) | [M-SYSTEM-01-05](tasks/M-SYSTEM-01-05.md) | VERIFIED | `System*` 53/53 (`226.6ms`), `ctest` 2/2 (`SystemOnly` `3.95s`), full RelWithDebInfo (`1,383 ✔`), ASan+UBSan (0 leaks/UB), TSan `16/16` (0 races) | +| M-SYSTEM-06 | Split async `SystemAsync` (`INTERNAL_DEPS System Async IO Time Functional LogState`, `EXTRA_HEADERS` `AsyncProcess.hpp`/`AsyncWatcher.hpp`), `ProcessManager`, `ManagedChild`, async `communicate`/`wait`/`close_and_join`, `WatcherService`/`WatchSubscription`, `SystemAsync.cpp`, `SystemAsyncOnly` consumer (`9a3c5d8`) | [M-SYSTEM-01-05](tasks/M-SYSTEM-01-05.md) | VERIFIED | `SystemAsync*` 2/2 (`211.5ms`), `ctest` 2/2 (`SystemAsyncOnly` `9.43s`), full RelWithDebInfo (`1,383 ✔`), ASan+UBSan (0 leaks/UB), TSan `2/2` (0 races) | +| S-IPC-01..03 | New `IPC` module (`src/IPC/module.cmake`, `Types.hpp`, `Codec.hpp`, `Transport.hpp`, `Session.hpp`, `IPC.hpp`), V1 `VDIP` 24B big-endian framing & pre-alloc `BufferQuota`/`QuotaPermit`, `LocalListener`/`connect_local` (`O_NOFOLLOW`, `0700`/`0600`, `flock`, `SO_PEERCRED` fail-closed), `adopt_pipe_pair`/`create_socket_pair_transports`, full-duplex `Session` with control lane/tombstones/token-bucket/graceful drain, `Ipc.cpp`, `IPCOnly` consumer (`39a48d5`) | [S-IPC-01-03](tasks/S-IPC-01-03.md) | VERIFIED | `Ipc*` 3/3 (`8.8ms`), `ctest` 2/2 (`IPCOnly` `12.20s`), full RelWithDebInfo (`1,383 ✔`), ASan+UBSan (0 leaks/UB), TSan `3/3` (0 races) | + All workers share the checkout and have disjoint file ownership defined in their persisted task specifications. Root owns all cross-cutting files and resolves contract changes. No worker owns application code, build files, existing docs/short-url.md, or Git diff --git a/docs/agent-workflow/VERIFICATION.md b/docs/agent-workflow/VERIFICATION.md index bc9d22a..a3f6f59 100644 --- a/docs/agent-workflow/VERIFICATION.md +++ b/docs/agent-workflow/VERIFICATION.md @@ -230,3 +230,17 @@ Branch: `feat/roadmap-p2-wave5` (branched from `main` at `1e901ce`, which was pu | Full Integrated ASan+UBSan (`7b57b35`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug (`/tmp/void-w5-asan`, 37 modules, `-DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1 /tmp/void-w5-asan/tests/VoidTests` | Initial run hit 1 timing assertion in unrelated existing `internal_fsm_service_hot_reload_under_load` (`FsmServiceHotReload.cpp:119`, 0 leaks/UB); full re-run on same binary passed 1,378 tests — 1,375 passed, 3 intentional skips (`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (50.16s), 0 ASan/LSan leaks, 0 UBSan errors | | Wave 5 TSan Subset (`7b57b35`) | `dev cpp-gcc -c` Debug (`Observability;ResilienceAsync;Log;IO;Async;Time;Testing`, `/tmp/void-w5-tsan`, 15 modules, `-DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `/tmp/void-w5-tsan/tests/VoidTests --filter "Observability*\|ResilienceHardening*\|AsyncPolicy*\|Log*\|AsyncLogger*\|LogScopeSnapshot*\|Io*\|OperationScope*"` | 68/68 passed (7.01s, including `AsyncLogger::async_multi_producer_no_loss` 6.53s, `Observability` 4/4, `ResilienceHardening` 4/4, `AsyncPolicy` 2/2, `Log` 12/12, `LogHardening` 4/4, `LogScopeSnapshot` 3/3, `IoDriver` 4/4, `OperationScope` 5/5), 0 TSan data races | | Post-W5 Benchmark (`7b57b35`, `rev=7b57b355cd75`) | `/tmp/void-w5-full/benchmarks/VoidFoundationBench --json /tmp/void-w5-full/post-w5.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.75ns, `core_uuid_parse_hyphenated` 43.49ns, `core_uuid_to_string` 32.51ns, `core_hash_fnv1a64_256b` 213.37ns, `core_hash_murmur3_256b` 92.34ns, `functional_result_ok_chain` 1.65ns, `functional_error_with_context` 94.82ns, `math_checked_add_loop` 0.86ns, `containers_spsc_ring_push_pop` 10.76ns, `containers_lru_get_put` 31.99ns, `binary_reader_u64_be` 2.24ns, `data_json_parse_small_object` 576.81ns, `data_json_serialize_small_object` 284.87ns | + +## Wave 6A / P2 System, SystemAsync, IPC Verification (2026-11-24) + +Branch: `feat/roadmap-p2-wave6a` (branched from `main` at `4479960`, which was pushed to `origin/main`). Toolchain via `dev cpp-gcc`: GCC 16.2.0, CMake 4.4.4, Ninja 1.13.2. + +| Scope | Command & configuration | Observed outcome | +| --- | --- | --- | +| M-SYSTEM-01..05 (`3f67b1e`, `fcdbc06`) | `System;Testing` RelWithDebInfo `-DVOID_WARNINGS_AS_ERRORS=ON` `/tmp/void-w6a-system` (`VoidTests --filter "System*"`, `ctest`) | `System*` 53/53 passed (226.6ms); `ctest` 2/2 passed (`VoidTests` 0.57s, `VoidInstalledComponentConsumers` including `SystemOnly` 3.95s) | +| M-SYSTEM-06 (`9a3c5d8`) | `SystemAsync;Testing` RelWithDebInfo `-DVOID_WARNINGS_AS_ERRORS=ON` `/tmp/void-w6a-sysasync` (`VoidTests --filter "SystemAsync*"`, `ctest`) | `SystemAsync*` 2/2 passed (211.5ms); `ctest` 2/2 passed (`VoidTests` 1.15s, `VoidInstalledComponentConsumers` including `SystemAsyncOnly` 9.43s) | +| S-IPC-01..03 (`39a48d5`) | `IPC;Testing` RelWithDebInfo `-DVOID_WARNINGS_AS_ERRORS=ON` `/tmp/void-w6a-ipc` (`VoidTests --filter "Ipc*"`, `ctest`) | `Ipc*` 3/3 passed (8.8ms); `ctest` 2/2 passed (`VoidTests` 0.49s, `VoidInstalledComponentConsumers` including `IPCOnly` 12.20s, total 12.70s) | +| Full Integrated RelWithDebInfo (`39a48d5`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` full build (`/tmp/void-w6a-full`, 39 modules, `-DVOID_WARNINGS_AS_ERRORS=ON -DVOID_ENABLE_BENCHMARKS=ON`), `/tmp/void-w6a-full/tests/VoidTests`, `ctest --test-dir /tmp/void-w6a-full --output-on-failure --timeout 300` | `VoidTests`: 1,386 tests — 1,383 passed, 3 intentional skips (`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (4.68s); `ctest`: 2/2 passed (`VoidTests` 4.58s + `VoidInstalledComponentConsumers` 31.05s across 19 consumer runs incl. `SystemOnly`, `SystemAsyncOnly`, `IPCOnly`, `RelocatedFoundation`, `RelocatedExternal`, total 35.63s) | +| Full Integrated ASan+UBSan (`39a48d5`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug (`/tmp/void-w6a-asan`, 39 modules, `-DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `/tmp/void-w6a-asan/tests/VoidTests` | 1,386 tests — 1,383 passed, 3 intentional skips (`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (19.34s), 0 ASan/LSan leaks, 0 UBSan errors | +| Wave 6A TSan Subset (`39a48d5`) | `dev cpp-gcc -c` Debug (`SystemAsync;IPC;IO;Async;Resilience;Testing`, `/tmp/void-w6a-tsan`, 14 modules, `-DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `/tmp/void-w6a-tsan/tests/VoidTests --filter "Process*\|SystemHardening*\|SystemAsync*\|Ipc*\|FileWatcher*\|IoDriver*\|OperationScope*"` | 35/35 passed (609.4ms: `OperationScope` 5, `IoDriver` 4, `Ipc` 3, `FileWatcher` 5, `Process` 10, `ProcessStream` 3, `SystemHardening` 3, `SystemAsync` 2), 0 TSan data races | +| Post-W6A Benchmark (`39a48d5`, `rev=39a48d5c0a72`) | `/tmp/void-w6a-full/benchmarks/VoidFoundationBench --json /tmp/void-w6a-full/post-w6a.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.38ns, `core_uuid_parse_hyphenated` 24.92ns, `core_uuid_to_string` 17.45ns, `core_hash_fnv1a64_256b` 181.41ns, `core_hash_murmur3_256b` 67.93ns, `functional_result_ok_chain` 1.13ns, `functional_error_with_context` 58.77ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.80ns, `containers_lru_get_put` 20.61ns, `binary_reader_u64_be` 1.31ns, `data_json_parse_small_object` 311.16ns, `data_json_serialize_small_object` 162.52ns | diff --git a/docs/agent-workflow/tasks/M-SYSTEM-01-05.md b/docs/agent-workflow/tasks/M-SYSTEM-01-05.md new file mode 100644 index 0000000..8b30fc8 --- /dev/null +++ b/docs/agent-workflow/tasks/M-SYSTEM-01-05.md @@ -0,0 +1,27 @@ +# System Process, Shared Watcher, Durable Filesystem & Temp Factories +Task ID: M-SYSTEM-01..05 +Phase: P2 (Wave 6A) +Status: APPROVED +Contracts: C-01, C-02, C-03, C-04, C-05 + +## 1. Context and baseline +`Void::System` preserves 1.x APIs (`Void::Process::{run,run_streaming,shell,reexec}`, `Void::FileSystem::{FileWatcher,Path,Query,TempFile,TempDir}`, `Void::SystemInfo::CpuSampler`) while fixing legacy bugs (zero-timeout 30s cutoff, full-duplex pipe deadlock, unescalated `SIGTERM` wait hangs, `SIGPIPE` on pipes, TOCTOU temp creation, unsafe `atomic_write`) and adding `System` (`Types`, `OwnedFd`, `Child`, `spawn`, `communicate_blocking`, `replace_file`, bounded `read_file`/`list_directory`, valid `CpuSampler::sample`) plus `Void::SystemAsync` (`ProcessManager`, async `communicate`/`wait`, shared `WatcherService`, `WatchSubscription`). + +## 2. Deliverables +- `src/System/module.cmake` (`INTERNAL_DEPS Functional Time LogState`, `EXCLUDE_HEADERS Void/System/AsyncProcess.hpp Void/System/AsyncWatcher.hpp`) & `src/SystemAsync/module.cmake` (`INTERNAL_DEPS System Async IO Time Functional LogState`). +- `include/Void/System/Types.hpp`: `kSystemErrorDomain = 10`, `SystemErrorCode`, `make_system_error`, move-only `OwnedFd`. +- `include/Void/System/Process.hpp` & `src/System/Process.cpp`: legacy compatibility fixes + `SpawnOptions`, `EnvironmentPolicy`, `CaptureLimits`, `OverflowPolicy`, `kMaxSpawnInputBytes = 256 KiB`, move-only `Child`, `spawn`, `communicate_blocking`, `reexec(..., close_extra_fds)`. +- `include/Void/System/{Path,Query,TempFile,TempDir,Metrics}.hpp`: `read_file_bounded`, `list_directory_bounded`, `replace_file` with `ReplaceDurability`/`ReplacePhase`/`ReplaceFaultHook`, atomic `0600`/`0700` `TempFile`/`TempDir` verified by `(dev, ino)` before removal, `CpuSample`. +- `include/Void/System/{AsyncProcess,AsyncWatcher}.hpp` & `src/SystemAsync/{AsyncProcess,AsyncWatcher}.cpp`: `ProcessManager`, async `communicate`/`wait`/`close_and_join`, shared `WatcherService`, `WatchSubscription`. +- `tests/helpers/ProcessHelper.cpp`, `tests/standalone/System/{ProcessStream,SystemHardening}.cpp`, `tests/standalone/SystemAsync/SystemAsync.cpp`, `tests/package/{SystemOnly,SystemAsyncOnly}/*`. + +## 3. Edge cases +- Between `fork()` and `exec*()`, strictly async-signal-safe operations only; `exec_failed` preserves `errno` via `CLOEXEC` error pipe and never collides with child exit `127`. +- `replace_file` cleans only owned temp files before rename and reports `visible_on_disk = true, durability_unknown = true` if post-rename directory `fsync` fails. +- `WatcherService::close_and_join()` drains admitted callbacks and rejects self-join. + +## 4. Verification commands +```sh +dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w6a-system -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVOID_ENABLED_MODULES="System;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w6a-system && /tmp/void-w6a-system/tests/VoidTests --filter "Process*|SystemHardening*|Path*|Query*|TempDir*|TempFile*|Metrics*|FileWatcher*|SignalWatcher*" && ctest --test-dir /tmp/void-w6a-system --output-on-failure --timeout 120' +dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w6a-sysasync -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVOID_ENABLED_MODULES="SystemAsync;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w6a-sysasync && /tmp/void-w6a-sysasync/tests/VoidTests --filter "SystemAsync*" && ctest --test-dir /tmp/void-w6a-sysasync --output-on-failure --timeout 120' +``` diff --git a/docs/agent-workflow/tasks/S-IPC-01-03.md b/docs/agent-workflow/tasks/S-IPC-01-03.md new file mode 100644 index 0000000..2c6b48c --- /dev/null +++ b/docs/agent-workflow/tasks/S-IPC-01-03.md @@ -0,0 +1,27 @@ +# IPC Wire Codec, Quota Reservations, Local UDS/Pipe Transport, and Session +Task ID: S-IPC-01..03 +Phase: P2 (Wave 6A) +Status: APPROVED +Contracts: C-01, C-02, C-03, C-04, C-05 + +## 1. Context and baseline +New subsystem `Void::IPC` (`src/IPC/module.cmake`, `INTERNAL_DEPS Core Functional Memory Time Binary Async IO Resilience`) providing V1 `VDIP` 24-byte big-endian framed RPC/messaging over pathname `AF_UNIX` `SOCK_STREAM` and supervised child pipe pairs (`adopt_pipe_pair`). + +## 2. Deliverables +- `include/Void/Functional/Error.hpp`: reserve `kIpcErrorDomain = 16` (plus remaining P2 domains `17..21`). +- `include/Void/IPC/{Types,Codec,Transport,Session,IPC}.hpp` & `src/IPC/{Codec,Transport,Session}.cpp`: + - `IpcErrorCode`, `IpcLimits`, `EffectStatus`, `CallFailure`, `PeerCredentials`, `PeerPolicy`, `HelloInfo`. + - V1 24B `VDIP` codec + `BufferQuota`/`QuotaPermit` + incremental `FrameDecoder` validating magic/version/flags/stream/request ID/limits and reserving global (`64 MiB`) + per-session quotas before payload allocation. + - `LocalListener` (0700 owned parent dir, `sun_path < 108`, startup `flock` + failed `connect` stale cleanup, `SOCK_NONBLOCK|SOCK_CLOEXEC`, `fchmod(0600)` before `bind()`, `SO_PEERCRED`), `connect_local`, `adopt_pipe_pair` (`PeerCredentials::available == false`). + - Full-duplex `Session` (`handshake`, `start`, `request`, `send_one_way`, `send_goaway`, `close_and_join` rejecting `self_join`), monotonic request IDs, `TokenBucket` per-peer rate limit, reserved control lane (`8 KiB`/`16` frames), `256` late-response tombstones, advisory `cancel`, single terminal completion, zero auto-replay. +- `tests/standalone/IPC/Ipc.cpp` & `tests/package/IPCOnly/*`. + +## 3. Edge cases +- Oversize/corrupt headers fail before any payload allocation or quota charge. +- Saturated data lane still delivers reserved control-lane `cancel`/`overloaded`/`rate_limited` replies without deadlock. +- Peer disconnect faults active requests once with `transport_lost` and `EffectStatus::unknown`. + +## 4. Verification commands +```sh +dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w6a-ipc -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVOID_ENABLED_MODULES="IPC;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w6a-ipc && /tmp/void-w6a-ipc/tests/VoidTests --filter "Ipc*" && ctest --test-dir /tmp/void-w6a-ipc --output-on-failure --timeout 120' +``` diff --git a/include/Void/Functional/Error.hpp b/include/Void/Functional/Error.hpp index 7578df5..1d686be 100644 --- a/include/Void/Functional/Error.hpp +++ b/include/Void/Functional/Error.hpp @@ -65,6 +65,12 @@ namespace Void::Result inline constexpr std::uint32_t kStacktraceErrorDomain = 13; inline constexpr std::uint32_t kObservabilityErrorDomain = 14; inline constexpr std::uint32_t kResilienceErrorDomain = 15; + inline constexpr std::uint32_t kIpcErrorDomain = 16; + inline constexpr std::uint32_t kArchiveErrorDomain = 17; + inline constexpr std::uint32_t kCryptoErrorDomain = 18; + inline constexpr std::uint32_t kSecurityErrorDomain = 19; + inline constexpr std::uint32_t kUpdateErrorDomain = 20; + inline constexpr std::uint32_t kSqliteErrorDomain = 21; struct ErrorCode { std::uint32_t domain{kGenericErrorDomain}; diff --git a/include/Void/IPC/Codec.hpp b/include/Void/IPC/Codec.hpp new file mode 100644 index 0000000..467bb58 --- /dev/null +++ b/include/Void/IPC/Codec.hpp @@ -0,0 +1,189 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::IPC +{ + +struct FrameHeader { + std::uint16_t version{kWireVersion}; + std::uint8_t flags{0}; + FrameType type{FrameType::request}; + std::uint32_t payload_len{0}; + std::uint32_t stream_id{0}; + std::uint64_t request_id{0}; +}; + +class BufferQuota; + +class QuotaPermit +{ +public: + QuotaPermit() noexcept = default; + ~QuotaPermit() noexcept; + + QuotaPermit(const QuotaPermit&) = delete; + QuotaPermit& operator=(const QuotaPermit&) = delete; + QuotaPermit(QuotaPermit&& other) noexcept; + QuotaPermit& operator=(QuotaPermit&& other) noexcept; + + [[nodiscard]] bool valid() const noexcept { return bytes_ > 0; } + [[nodiscard]] std::size_t bytes() const noexcept { return bytes_; } + void reset() noexcept; + +private: + friend class BufferQuota; + std::weak_ptr quota_{}; + std::size_t bytes_{0}; +}; + +class BufferQuota : public std::enable_shared_from_this +{ +public: + explicit BufferQuota(std::size_t capacity_bytes); + + [[nodiscard]] static std::shared_ptr + create(std::size_t capacity_bytes); + + [[nodiscard]] Void::Result::Result + reserve(std::size_t bytes); + + [[nodiscard]] std::size_t capacity() const noexcept { return capacity_; } + [[nodiscard]] std::size_t used() const noexcept; + +private: + friend class QuotaPermit; + void release(std::size_t bytes) noexcept; + + std::size_t capacity_{0}; + mutable std::mutex mu_{}; + std::size_t used_{0}; +}; + +struct DecodedFrame { + FrameHeader header{}; + Void::Binary::FrozenBytes payload{}; + QuotaPermit global_permit{}; + QuotaPermit session_permit{}; +}; + +[[nodiscard]] Void::Result::Result + validate_frame_header(const FrameHeader& header, const IpcLimits& limits); + +[[nodiscard]] Void::Result::Result + encode_frame_header(const FrameHeader& header, + std::span out); + +[[nodiscard]] Void::Result::Result + decode_frame_header(std::span in); + +[[nodiscard]] Void::Result::Result + encode_frame( + const FrameHeader& header, + std::span payload = {}, + const IpcLimits& limits = {}, + std::pmr::memory_resource* mr = std::pmr::get_default_resource()); + +[[nodiscard]] Void::Result::Result + encode_hello(const HelloInfo& info, + std::pmr::memory_resource* mr = std::pmr::get_default_resource()); + +[[nodiscard]] Void::Result::Result + decode_hello(std::span payload, + std::size_t max_bytes = 4096); + +[[nodiscard]] Void::Result::Result + encode_error_payload( + IpcErrorCode code, + std::string_view message, + std::pmr::memory_resource* mr = std::pmr::get_default_resource()); + +[[nodiscard]] Void::Result::Result, + Void::Result::Error> + decode_error_payload(std::span payload); + +[[nodiscard]] Void::Result::Result + encode_goaway_payload( + IpcErrorCode code, + std::uint64_t last_request_id, + std::string_view reason, + std::pmr::memory_resource* mr = std::pmr::get_default_resource()); + +[[nodiscard]] Void::Result::Result< + std::tuple, + Void::Result::Error> + decode_goaway_payload(std::span payload); + +class FrameDecoder +{ +public: + explicit FrameDecoder( + IpcLimits limits = {}, + std::shared_ptr global_quota = {}, + std::shared_ptr session_quota = {}, + std::pmr::memory_resource* mr = std::pmr::get_default_resource()); + + [[nodiscard]] static constexpr std::size_t + frame_quota_cost(std::size_t payload_len) noexcept + { + return kFrameHeaderSize + payload_len; + } + + [[nodiscard]] Void::Result::Result, + Void::Result::Error> + feed(std::span chunk); + + [[nodiscard]] std::size_t header_bytes_buffered() const noexcept + { + return header_len_; + } + + [[nodiscard]] std::size_t payload_bytes_buffered() const noexcept + { + return has_header_ ? payload_written_ : 0; + } + + [[nodiscard]] bool in_mid_frame() const noexcept + { + return header_len_ > 0 || has_header_; + } + +private: + enum class State { + reading_header, + reading_payload, + failed, + }; + + IpcLimits limits_{}; + std::shared_ptr global_quota_{}; + std::shared_ptr session_quota_{}; + std::pmr::memory_resource* mr_{nullptr}; + + State state_{State::reading_header}; + std::array header_buf_{}; + std::size_t header_len_{0}; + bool has_header_{false}; + FrameHeader current_header_{}; + QuotaPermit current_global_permit_{}; + QuotaPermit current_session_permit_{}; + std::optional payload_buf_{}; + std::size_t payload_written_{0}; + + void reset_frame_state() noexcept; +}; + +} // namespace Void::IPC diff --git a/include/Void/IPC/IPC.hpp b/include/Void/IPC/IPC.hpp new file mode 100644 index 0000000..8bc61c0 --- /dev/null +++ b/include/Void/IPC/IPC.hpp @@ -0,0 +1,6 @@ +#pragma once + +#include +#include +#include +#include diff --git a/include/Void/IPC/Session.hpp b/include/Void/IPC/Session.hpp new file mode 100644 index 0000000..578f373 --- /dev/null +++ b/include/Void/IPC/Session.hpp @@ -0,0 +1,81 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace Void::IPC +{ + +using RequestHandler = std::function>( + Void::Binary::FrozenBytes payload, std::stop_token cancel)>; + +using OneWayHandler = std::function; + +class Session +{ +public: + struct State; + + explicit Session( + Void::IO::Driver& driver, + Void::Async::Executor& executor, + DuplexTransport transport, + IpcLimits limits = {}, + const Void::Time::MonotonicClock& clock = + Void::Time::SystemMonotonicClock::instance(), + std::shared_ptr global_quota = {}); + + ~Session() noexcept; + + Session(const Session&) = delete; + Session& operator=(const Session&) = delete; + Session(Session&&) = delete; + Session& operator=(Session&&) = delete; + + [[nodiscard]] Void::Coro::Task> + handshake(HelloInfo local_hello = {}, + Void::Async::OperationOptions options = {}); + + [[nodiscard]] Void::Result::Result + start(RequestHandler on_request, OneWayHandler on_one_way = {}); + + [[nodiscard]] Void::Coro::Task< + std::expected> + request(Void::Binary::FrozenBytes payload, + Void::Async::OperationOptions options = {}); + + [[nodiscard]] Void::Result::Result + send_one_way(Void::Binary::FrozenBytes payload); + + [[nodiscard]] Void::Result::Result + send_goaway(IpcErrorCode code = IpcErrorCode::closed, + std::string_view reason = "closing"); + + [[nodiscard]] Void::Coro::Task> + close_and_join(Void::Async::OperationOptions options = {}); + + [[nodiscard]] SessionStats stats() const noexcept; + [[nodiscard]] HelloInfo negotiated_hello() const; + [[nodiscard]] const PeerCredentials& peer_credentials() const noexcept; + + // Test hook to inspect/force request ID near exhaustion without 2^64 calls. + void set_next_request_id_for_test(std::uint64_t next_id) noexcept; + +private: + std::shared_ptr state_{}; +}; + +} // namespace Void::IPC diff --git a/include/Void/IPC/Transport.hpp b/include/Void/IPC/Transport.hpp new file mode 100644 index 0000000..ea2328f --- /dev/null +++ b/include/Void/IPC/Transport.hpp @@ -0,0 +1,118 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace Void::IPC +{ + +class DuplexTransport +{ +public: + DuplexTransport() noexcept = default; + DuplexTransport(Void::IO::ByteStream unified_stream, + PeerCredentials creds) noexcept; + DuplexTransport(Void::IO::ByteStream read_stream, + Void::IO::ByteStream write_stream, + PeerCredentials creds) noexcept; + + DuplexTransport(const DuplexTransport&) = delete; + DuplexTransport& operator=(const DuplexTransport&) = delete; + DuplexTransport(DuplexTransport&&) noexcept = default; + DuplexTransport& operator=(DuplexTransport&&) noexcept = default; + + [[nodiscard]] bool valid() const noexcept; + [[nodiscard]] bool is_split() const noexcept { return split_; } + [[nodiscard]] const PeerCredentials& credentials() const noexcept + { + return credentials_; + } + + [[nodiscard]] Void::IO::ByteStream& reader_stream() noexcept + { + return read_stream_; + } + + [[nodiscard]] Void::IO::ByteStream& writer_stream() noexcept + { + return split_ ? write_stream_ : read_stream_; + } + + [[nodiscard]] Void::Coro::Task> + close_and_join(Void::Async::OperationOptions options = {}); + +private: + friend class LocalListener; + bool split_{false}; + Void::IO::ByteStream read_stream_{}; + Void::IO::ByteStream write_stream_{}; + PeerCredentials credentials_{}; + std::shared_ptr listener_slot_{}; +}; + +class LocalListener +{ +public: + struct SlotState; + + LocalListener() noexcept = default; + ~LocalListener() noexcept; + + LocalListener(const LocalListener&) = delete; + LocalListener& operator=(const LocalListener&) = delete; + LocalListener(LocalListener&& other) noexcept; + LocalListener& operator=(LocalListener&& other) noexcept; + + [[nodiscard]] static Void::Result::Result + listen(const std::filesystem::path& socket_path, + IpcLimits limits = {}, + PeerPolicy policy = {}); + + [[nodiscard]] Void::Result::Result, + Void::Result::Error> + try_accept(Void::IO::Driver& driver); + + [[nodiscard]] bool valid() const noexcept { return listen_fd_ >= 0; } + [[nodiscard]] std::size_t active_sessions() const noexcept; + [[nodiscard]] const std::filesystem::path& path() const noexcept + { + return socket_path_; + } + [[nodiscard]] int fd() const noexcept { return listen_fd_; } + + void close() noexcept; + +private: + int listen_fd_{-1}; + int dir_fd_{-1}; + int lock_fd_{-1}; + std::filesystem::path socket_path_{}; + std::string socket_name_{}; + std::uint64_t socket_dev_{0}; + std::uint64_t socket_ino_{0}; + IpcLimits limits_{}; + PeerPolicy policy_{}; + std::shared_ptr slot_state_{}; +}; + +[[nodiscard]] Void::Result::Result + connect_local(Void::IO::Driver& driver, + const std::filesystem::path& socket_path, + PeerPolicy policy = {}); + +[[nodiscard]] Void::Result::Result + adopt_pipe_pair(Void::IO::Driver& driver, int read_fd, int write_fd); + +[[nodiscard]] Void::Result::Result, + Void::Result::Error> + create_socket_pair_transports(Void::IO::Driver& driver); + +} // namespace Void::IPC diff --git a/include/Void/IPC/Types.hpp b/include/Void/IPC/Types.hpp new file mode 100644 index 0000000..aac0022 --- /dev/null +++ b/include/Void/IPC/Types.hpp @@ -0,0 +1,181 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::IPC +{ + +inline constexpr std::size_t kFrameHeaderSize = 24; +inline constexpr std::uint16_t kWireVersion = 1; + +enum class IpcErrorCode : std::int32_t { + invalid_argument = 1, + corrupt_frame = 2, + unsupported_version = 3, + frame_too_large = 4, + quota_exceeded = 5, + overloaded = 6, + rate_limited = 7, + cancelled = 8, + timed_out = 9, + transport_lost = 10, + closed = 11, + permission_denied = 12, + already_exists = 13, + not_found = 14, + handshake_failed = 15, + id_exhausted = 16, + self_join = 17, + peer_error = 18, + internal = 19, +}; + +[[nodiscard]] constexpr Void::Result::ErrorKind + classify_ipc_error(IpcErrorCode code) noexcept +{ + switch (code) { + case IpcErrorCode::invalid_argument: + return Void::Result::ErrorKind::invalid_argument; + case IpcErrorCode::corrupt_frame: + return Void::Result::ErrorKind::corrupt; + case IpcErrorCode::unsupported_version: + return Void::Result::ErrorKind::unsupported; + case IpcErrorCode::frame_too_large: + case IpcErrorCode::quota_exceeded: + case IpcErrorCode::id_exhausted: + return Void::Result::ErrorKind::exhausted; + case IpcErrorCode::overloaded: + case IpcErrorCode::rate_limited: + return Void::Result::ErrorKind::overloaded; + case IpcErrorCode::cancelled: + case IpcErrorCode::closed: + return Void::Result::ErrorKind::cancelled; + case IpcErrorCode::timed_out: + return Void::Result::ErrorKind::timeout; + case IpcErrorCode::not_found: + return Void::Result::ErrorKind::not_found; + case IpcErrorCode::already_exists: + case IpcErrorCode::self_join: + return Void::Result::ErrorKind::conflict; + case IpcErrorCode::permission_denied: + case IpcErrorCode::transport_lost: + case IpcErrorCode::handshake_failed: + case IpcErrorCode::peer_error: + return Void::Result::ErrorKind::io; + case IpcErrorCode::internal: + return Void::Result::ErrorKind::internal; + } + return Void::Result::ErrorKind::internal; +} + +[[nodiscard]] inline Void::Result::Error make_ipc_error( + IpcErrorCode code, std::string_view message, int sys_errno = 0) +{ + std::string detail; + std::error_code sys_ec{}; + if (sys_errno != 0) { + detail = std::format( + "{} (errno={}: {})", message, sys_errno, std::strerror(sys_errno)); + sys_ec = std::error_code{sys_errno, std::generic_category()}; + } else { + detail.assign(message); + } + return Void::Result::Error{ + classify_ipc_error(code), + std::move(detail), + Void::Result::ErrorCode{Void::Result::kIpcErrorDomain, + static_cast(code)}, + sys_ec}; +} + +enum class FrameType : std::uint8_t { + hello = 1, + request = 2, + response = 3, + error = 4, + cancel = 5, + one_way = 6, + goaway = 7, +}; + +enum class EffectStatus : std::uint8_t { + not_sent = 0, + unknown = 1, +}; + +struct CallFailure { + Void::Result::Error error{}; + EffectStatus effect{EffectStatus::not_sent}; + bool may_have_executed{false}; +}; + +struct IpcLimits { + std::size_t max_frame_payload{1024ULL * 1024ULL}; + std::size_t max_hello_bytes{4096}; + std::size_t max_inflight_requests{64}; + std::size_t max_active_handlers{64}; + std::size_t max_outbound_frames{128}; + std::size_t max_outbound_bytes{4ULL * 1024ULL * 1024ULL}; + std::size_t max_recv_buffer_bytes{2ULL * 1024ULL * 1024ULL}; + std::size_t max_tombstones{256}; + std::size_t max_sessions{128}; + std::size_t global_buffer_budget_bytes{64ULL * 1024ULL * 1024ULL}; + std::size_t max_waiters{128}; + std::size_t control_lane_max_bytes{8192}; + std::size_t control_lane_max_frames{16}; + double rate_limit_per_sec{1000.0}; + double rate_limit_burst{128.0}; + std::chrono::milliseconds handshake_timeout{std::chrono::milliseconds{5000}}; + std::chrono::milliseconds progress_timeout{std::chrono::milliseconds{5000}}; + std::chrono::milliseconds idle_timeout{std::chrono::milliseconds{60000}}; +}; + +struct PeerCredentials { + bool available{false}; + long long pid{-1}; + unsigned long uid{0}; + unsigned long gid{0}; +}; + +struct PeerPolicy { + bool require_uid_match{true}; + bool set_allowed_uid_to_current_user{true}; + unsigned long allowed_uid{0}; + std::optional required_gid{}; +}; + +struct HelloInfo { + std::string protocol_id{"void.ipc.v1"}; + std::uint32_t protocol_version{1}; + std::uint32_t capabilities{0}; + std::uint32_t max_frame_payload{1024u * 1024u}; + std::uint32_t max_inflight_requests{64u}; + std::uint32_t max_active_handlers{64u}; +}; + +struct SessionStats { + std::uint64_t frames_sent{0}; + std::uint64_t frames_received{0}; + std::uint64_t requests_sent{0}; + std::uint64_t requests_received{0}; + std::uint64_t late_responses_dropped{0}; + std::uint64_t cancels_coalesced{0}; + std::size_t active_inflight{0}; + std::size_t active_handlers{0}; + std::size_t outbound_queued_bytes{0}; + std::size_t control_queued_frames{0}; + std::uint64_t next_request_id{1}; +}; + +} // namespace Void::IPC diff --git a/include/Void/System/AsyncProcess.hpp b/include/Void/System/AsyncProcess.hpp new file mode 100644 index 0000000..592a4cc --- /dev/null +++ b/include/Void/System/AsyncProcess.hpp @@ -0,0 +1,111 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace Void::SystemAsync +{ + +struct ProcessManagerOptions { + std::size_t max_active_children{64}; + std::size_t max_pending_spawns{128}; + std::chrono::milliseconds default_kill_grace{std::chrono::milliseconds{2000}}; +}; + +class ProcessManager; + +class ManagedChild +{ +public: + ManagedChild() noexcept = default; + ~ManagedChild() noexcept; + + ManagedChild(const ManagedChild&) = delete; + ManagedChild& operator=(const ManagedChild&) = delete; + ManagedChild(ManagedChild&&) noexcept; + ManagedChild& operator=(ManagedChild&&) noexcept; + + [[nodiscard]] bool valid() const noexcept; + [[nodiscard]] Void::Process::Child& child() noexcept { return child_; } + [[nodiscard]] const Void::Process::Child& child() const noexcept + { + return child_; + } + + void release_slot() noexcept; + +private: + friend class ProcessManager; + struct SlotGuard; + + Void::Process::Child child_{}; + std::shared_ptr slot_token_{}; +}; + +class ProcessManager +{ +public: + struct Impl; + + explicit ProcessManager( + Void::IO::Driver& driver, + Void::Async::Executor& executor, + ProcessManagerOptions options = {}, + const Void::Time::MonotonicClock& clock = + Void::Time::SystemMonotonicClock::instance()); + + ~ProcessManager() noexcept; + + ProcessManager(const ProcessManager&) = delete; + ProcessManager& operator=(const ProcessManager&) = delete; + ProcessManager(ProcessManager&&) = delete; + ProcessManager& operator=(ProcessManager&&) = delete; + + [[nodiscard]] Void::Result::Result + spawn(const Void::Process::SpawnOptions& options); + + [[nodiscard]] Void::Coro::Task< + Void::Result::Result> + communicate(Void::Process::Child& child, + std::string stdin_data = {}, + Void::Process::CaptureLimits limits = {}, + Void::Async::OperationOptions options = {}); + + [[nodiscard]] Void::Coro::Task< + Void::Result::Result> + communicate(ManagedChild& managed, + std::string stdin_data = {}, + Void::Process::CaptureLimits limits = {}, + Void::Async::OperationOptions options = {}); + + [[nodiscard]] Void::Coro::Task< + Void::Result::Result> + wait(Void::Process::Child& child, + Void::Async::OperationOptions options = {}); + + [[nodiscard]] Void::Coro::Task< + Void::Result::Result> + wait(ManagedChild& managed, + Void::Async::OperationOptions options = {}); + + [[nodiscard]] Void::Coro::Task> + close_and_join(Void::Async::OperationOptions options = {}); + + [[nodiscard]] std::size_t active_children() const noexcept; + [[nodiscard]] bool closed() const noexcept; + +private: + std::shared_ptr impl_; +}; + +} // namespace Void::SystemAsync diff --git a/include/Void/System/AsyncWatcher.hpp b/include/Void/System/AsyncWatcher.hpp new file mode 100644 index 0000000..92895c0 --- /dev/null +++ b/include/Void/System/AsyncWatcher.hpp @@ -0,0 +1,116 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::SystemAsync +{ + +enum class WatchEventKind { + created, + modified, + deleted, + replaced_inode, + symlink_changed, + permission_denied, + rescan_required, +}; + +struct WatchEvent { + WatchEventKind kind{WatchEventKind::modified}; + std::filesystem::path path{}; + bool exists{false}; + std::uint64_t dev{0}; + std::uint64_t ino{0}; + std::uint64_t size{0}; + int sys_errno{0}; +}; + +struct WatcherLimits { + std::size_t max_watched_paths{1024}; + std::size_t max_queued_events{256}; + std::chrono::milliseconds poll_interval{std::chrono::milliseconds{250}}; + int debounce_polls{1}; +}; + +struct WatchPathOptions { + std::optional allowed_root{}; + bool allow_symlink{false}; +}; + +using WatchCallback = std::function; +using ErrorSink = std::function; + +class WatcherService; + +class WatchSubscription +{ +public: + WatchSubscription() noexcept = default; + ~WatchSubscription() noexcept; + + WatchSubscription(const WatchSubscription&) = delete; + WatchSubscription& operator=(const WatchSubscription&) = delete; + WatchSubscription(WatchSubscription&&) noexcept; + WatchSubscription& operator=(WatchSubscription&&) noexcept; + + [[nodiscard]] bool active() const noexcept; + [[nodiscard]] Void::Result::Result + close_and_join(); + +private: + friend class WatcherService; + + struct Token; + std::shared_ptr token_; +}; + +class WatcherService +{ +public: + struct Impl; + + explicit WatcherService( + Void::Async::Executor& executor, + WatcherLimits limits = {}, + const Void::Time::MonotonicClock& clock = + Void::Time::SystemMonotonicClock::instance(), + ErrorSink error_sink = {}, + bool start_background_thread = false); + + ~WatcherService() noexcept; + + WatcherService(const WatcherService&) = delete; + WatcherService& operator=(const WatcherService&) = delete; + WatcherService(WatcherService&&) = delete; + WatcherService& operator=(WatcherService&&) = delete; + + [[nodiscard]] Void::Result::Result + watch(const std::filesystem::path& path, + WatchCallback callback, + WatchPathOptions options = {}); + + void poll_once(); + + [[nodiscard]] std::size_t watch_count() const noexcept; + [[nodiscard]] std::size_t queued_event_count() const noexcept; + + [[nodiscard]] Void::Result::Result shutdown(); + +private: + std::shared_ptr impl_; +}; + +} // namespace Void::SystemAsync diff --git a/include/Void/System/Metrics.hpp b/include/Void/System/Metrics.hpp index da1215d..d7baf69 100644 --- a/include/Void/System/Metrics.hpp +++ b/include/Void/System/Metrics.hpp @@ -1,5 +1,7 @@ #pragma once +#include + #include #include #include @@ -12,113 +14,132 @@ #include #endif -// Generic, app-agnostic process/system resource queries. Used to feed monitors -// (e.g. Void::Resilience::ResourceMonitor) with real samples. Linux is fully -// supported; other platforms return nullopt / 0 so callers degrade gracefully. - namespace Void::SystemInfo { - // ── memory ────────────────────────────────────────────────────────────── - - /// Resident set size (physical memory) of the current process, in bytes. - /// nullopt if it cannot be determined on this platform. - [[nodiscard]] inline std::optional process_memory_bytes() - { +/// Resident set size (physical memory) of the current process, in bytes. +/// nullopt if it cannot be determined on this platform. +[[nodiscard]] inline std::optional process_memory_bytes() +{ #if defined(__linux__) - // /proc/self/statm: "size resident shared text lib data dt" in pages. - std::ifstream statm{"/proc/self/statm"}; - std::uint64_t total_pages = 0, resident_pages = 0; - if (statm >> total_pages >> resident_pages) { - const long page = ::sysconf(_SC_PAGESIZE); - if (page > 0) { - return resident_pages * static_cast(page); - } - } - return std::nullopt; + std::ifstream statm{"/proc/self/statm"}; + std::uint64_t total_pages = 0, resident_pages = 0; + if (statm >> total_pages >> resident_pages) { + const long page = ::sysconf(_SC_PAGESIZE); + if (page > 0) { + return resident_pages * static_cast(page); + } + } + return std::nullopt; #else - return std::nullopt; + return std::nullopt; #endif - } +} - struct SystemMemory { - std::uint64_t total = 0; ///< total physical RAM, bytes - std::uint64_t available = 0; ///< approx. RAM available to new work - }; +struct SystemMemory { + std::uint64_t total = 0; ///< total physical RAM, bytes + std::uint64_t available = 0; ///< approx. RAM available to new work +}; - /// Total and (approximately) available system memory in bytes. - [[nodiscard]] inline std::optional system_memory() - { +/// Total and (approximately) available system memory in bytes. +[[nodiscard]] inline std::optional system_memory() +{ #if defined(__linux__) - struct ::sysinfo info{}; - if (::sysinfo(&info) != 0) { - return std::nullopt; - } - const std::uint64_t unit = info.mem_unit ? info.mem_unit : 1; - SystemMemory m; - m.total = static_cast(info.totalram) * unit; - // freeram excludes reclaimable cache/buffers, so this is conservative. - m.available = - (static_cast(info.freeram) + info.bufferram) * unit; - return m; + struct ::sysinfo info{}; + if (::sysinfo(&info) != 0) { + return std::nullopt; + } + const std::uint64_t unit = info.mem_unit ? info.mem_unit : 1; + SystemMemory m; + m.total = static_cast(info.totalram) * unit; + m.available = + (static_cast(info.freeram) + info.bufferram) * unit; + return m; #else - return std::nullopt; + return std::nullopt; #endif - } +} - // ── CPU ───────────────────────────────────────────────────────────────── +struct CpuSample { + double ratio{0.0}; + bool valid{false}; +}; - /// Samples this process's CPU usage between successive calls. usage() - /// returns the fraction of a single core consumed since the previous - /// usage() call (0.0 = idle, 1.0 = one core saturated; may exceed 1.0 on - /// multi-core workloads). The first call establishes the baseline and - /// returns 0. - class CpuSampler - { - public: +/// Samples this process's CPU usage between successive calls. +/// `sample()` explicitly distinguishes real 0.0 from unavailable sampling. +class CpuSampler +{ +public: + explicit CpuSampler( + const Void::Time::MonotonicClock* clock = + &Void::Time::SystemMonotonicClock::instance()) + : clock_(clock != nullptr ? clock + : &Void::Time::SystemMonotonicClock::instance()) + { + reset(); + } - CpuSampler() { reset(); } - - void reset() - { - wall_ = std::chrono::steady_clock::now(); + void reset() + { + wall_ = clock_->now(); + baseline_valid_ = false; #if defined(__linux__) - struct ::tms t{}; - last_ticks_ = (::times(&t) == static_cast<::clock_t>(-1)) - ? 0 - : (t.tms_utime + t.tms_stime); + struct ::tms t{}; + if (::times(&t) != static_cast<::clock_t>(-1)) { + last_ticks_ = static_cast(t.tms_utime) + + static_cast(t.tms_stime); + baseline_valid_ = true; + } #endif - } + } - [[nodiscard]] double usage() - { - const auto now = std::chrono::steady_clock::now(); - const std::chrono::duration wall = now - wall_; - wall_ = now; + [[nodiscard]] CpuSample sample( + const Void::Time::MonotonicClock* override_clock = nullptr) + { + const Void::Time::MonotonicClock* active = + (override_clock != nullptr) ? override_clock : clock_; + const auto now = active->now(); + const std::chrono::duration wall = now - wall_; + wall_ = now; #if defined(__linux__) - const long hz = ::sysconf(_SC_CLK_TCK); - struct ::tms t{}; - if (hz <= 0 || ::times(&t) == static_cast<::clock_t>(-1) || - wall.count() <= 0.0) { - return 0.0; - } - const std::int64_t ticks = t.tms_utime + t.tms_stime; - const double cpu_seconds = - static_cast(ticks - last_ticks_) / - static_cast(hz); - last_ticks_ = ticks; - return cpu_seconds / wall.count(); + const long hz = ::sysconf(_SC_CLK_TCK); + struct ::tms t{}; + if (!baseline_valid_ || hz <= 0 || + ::times(&t) == static_cast<::clock_t>(-1) || wall.count() <= 0.0) { + if (::times(&t) != static_cast<::clock_t>(-1)) { + last_ticks_ = static_cast(t.tms_utime) + + static_cast(t.tms_stime); + baseline_valid_ = true; + } + return CpuSample{0.0, false}; + } + const std::int64_t ticks = static_cast(t.tms_utime) + + static_cast(t.tms_stime); + const std::int64_t delta_ticks = + (ticks >= last_ticks_) ? (ticks - last_ticks_) : 0; + last_ticks_ = ticks; + const double cpu_seconds = + static_cast(delta_ticks) / static_cast(hz); + return CpuSample{cpu_seconds / wall.count(), true}; #else - return 0.0; + (void)wall; + return CpuSample{0.0, false}; #endif - } + } - private: + [[nodiscard]] double usage() + { + const auto s = sample(); + return s.valid ? s.ratio : 0.0; + } - std::chrono::steady_clock::time_point wall_; +private: + const Void::Time::MonotonicClock* clock_; + Void::Time::MonotonicClock::time_point wall_{}; + bool baseline_valid_{false}; #if defined(__linux__) - std::int64_t last_ticks_ = 0; + std::int64_t last_ticks_{0}; #endif - }; +}; } // namespace Void::SystemInfo diff --git a/include/Void/System/Path.hpp b/include/Void/System/Path.hpp index d9712df..4627bf2 100644 --- a/include/Void/System/Path.hpp +++ b/include/Void/System/Path.hpp @@ -1,144 +1,551 @@ #pragma once -#include #include #include +#include +#include +#include +#include +#include +#include +#include +#include #include #include -#include -#include -#include +#include +#include +#include #include #include #include #include +#include + +#ifndef _WIN32 +#include +#include +#include +#if defined(__linux__) +#include +#endif +#endif namespace Void::FileSystem { - /// Read the entire contents of a file as a string. - /// - /// Failure modes wrapped in `Result`: - /// - File does not exist - /// - File cannot be opened (permissions, etc.) - /// - I/O error during read - [[nodiscard]] inline Void::Result::Result - read_file(const std::filesystem::path& path) - { - std::ifstream f{path, std::ios::binary}; - if (!f.is_open()) { - Void::Log::warn("FileSystem", "read_file: cannot open '{}'", path.string()); - return Void::Result::fail(std::format( - "FileSystem::read_file: cannot open '{}'", path.string())); - } - std::string content{std::istreambuf_iterator(f), - std::istreambuf_iterator()}; - if (f.bad()) { - Void::Log::warn("FileSystem", "read_file: I/O error reading '{}'", - path.string()); - return Void::Result::fail( - std::format("FileSystem::read_file: I/O error reading '{}'", - path.string())); - } - Void::Log::debug("FileSystem", "read_file: '{}' ({} bytes)", path.string(), - content.size()); - return Void::Result::ok(std::move(content)); - } - /// Write `content` to `path`, overwriting any existing file. - /// - /// This is NOT crash-safe — a process killed mid-write may leave a - /// truncated file. Use `atomic_write` when you need durability. - [[nodiscard]] inline Void::Result::Result - write_file(const std::filesystem::path& path, std::string_view content) - { - std::ofstream f{path, std::ios::binary | std::ios::trunc}; - if (!f.is_open()) { - Void::Log::warn("FileSystem", "write_file: cannot open '{}'", path.string()); - return Void::Result::fail(std::format( - "FileSystem::write_file: cannot open '{}'", path.string())); - } - f.write(content.data(), static_cast(content.size())); - f.flush(); - if (!f.good()) { - Void::Log::warn("FileSystem", "write_file: I/O error writing '{}'", - path.string()); - return Void::Result::fail( - std::format("FileSystem::write_file: I/O error writing '{}'", - path.string())); - } - return {}; - } +struct ReadFileOptions { + std::size_t max_bytes{16ULL * 1024ULL * 1024ULL}; +}; - /// Crash-safe write: stage `content` in a sibling `.tmp` file, then - /// atomically rename onto `path`. The rename is atomic on POSIX - /// within the same filesystem; std::filesystem::rename uses the - /// platform-appropriate primitive (`ReplaceFileW` on Windows). - /// - /// Note: this does NOT fsync the staged file before rename. A - /// process or kernel crash between write and rename may leave the - /// `.tmp` file behind, but the original `path` is never corrupted. - [[nodiscard]] inline Void::Result::Result - atomic_write(const std::filesystem::path& path, - std::string_view content) - { - auto staging = path; - staging += ".tmp"; - if (auto r = write_file(staging, content); !r) { - return r; - } - std::error_code ec; - std::filesystem::rename(staging, path, ec); - if (ec) { - std::error_code ignore; - std::filesystem::remove(staging, ignore); - Void::Log::warn("FileSystem", "atomic_write: rename failed for '{}': {}", - path.string(), ec.message()); - return Void::Result::fail(std::format( - "FileSystem::atomic_write: rename failed for '{}': {}", - path.string(), ec.message())); - } - Void::Log::debug("FileSystem", "atomic_write: '{}' committed ({} bytes)", - path.string(), content.size()); - return {}; - } +enum class ReplaceDurability { + atomic_visibility, + durable_sync, +}; - /// Create `path` as a directory, including any missing parents. - /// Succeeds (no-op) if `path` already exists as a directory. - [[nodiscard]] inline Void::Result::Result - ensure_directory(const std::filesystem::path& path) - { - std::error_code ec; - if (std::filesystem::is_directory(path, ec)) { - return {}; - } - std::filesystem::create_directories(path, ec); - if (ec) { - Void::Log::warn("FileSystem", "ensure_directory: cannot create '{}': {}", - path.string(), ec.message()); - return Void::Result::fail(std::format( - "FileSystem::ensure_directory: cannot create '{}': {}", - path.string(), ec.message())); - } - Void::Log::debug("FileSystem", "ensure_directory: created '{}'", path.string()); - return {}; - } +enum class ReplacePhase { + validation, + create_stage, + write_stage, + sync_stage, + rename, + sync_parent, +}; - /// Remove a file or directory (recursively for directories). - /// Succeeds (no-op) if the path doesn't exist. - [[nodiscard]] inline Void::Result::Result - remove_path(const std::filesystem::path& path) - { - std::error_code ec; - std::filesystem::remove_all(path, ec); - if (ec) { - Void::Log::warn("FileSystem", "remove_path: cannot remove '{}': {}", - path.string(), ec.message()); - return Void::Result::fail( - std::format("FileSystem::remove_path: cannot remove '{}': {}", - path.string(), ec.message())); - } - return {}; - } +struct ReplaceFailure { + Void::Result::Error error{}; + ReplacePhase phase{ReplacePhase::validation}; + bool visible_on_disk{false}; + bool durability_unknown{false}; +}; + +/// Optional test hook: return a POSIX errno to inject a failure at `phase`. +using ReplaceFaultHook = std::function(ReplacePhase phase)>; + +struct ReplaceOptions { + ReplaceDurability durability{ReplaceDurability::durable_sync}; + unsigned mode{0644}; + ReplaceFaultHook fault_hook{}; +}; + +namespace detail +{ + +[[nodiscard]] inline std::uint64_t next_temp_entropy() noexcept +{ + static std::atomic counter{0}; + std::uint64_t rnd = 0; +#if defined(__linux__) + if (::getrandom(&rnd, sizeof(rnd), 0) == static_cast(sizeof(rnd))) { + return rnd ^ (counter.fetch_add(1, std::memory_order_relaxed) << 12); + } +#endif + const auto now = static_cast( + std::chrono::steady_clock::now().time_since_epoch().count()); + return now ^ (counter.fetch_add(1, std::memory_order_relaxed) * + 0x9e3779b97f4a7c15ULL); +} + +#ifndef _WIN32 +[[nodiscard]] inline int fsync_eintr(int fd) noexcept +{ + for (;;) { + if (::fsync(fd) == 0) { + return 0; + } + if (errno == EINTR) { + continue; + } + return errno; + } +} +#endif + +} // namespace detail + +/// Read up to `options.max_bytes` from `path` cleanly with typed errors. +[[nodiscard]] inline Void::Result::Result + read_file_bounded(const std::filesystem::path& path, + ReadFileOptions options = {}) +{ +#ifndef _WIN32 + const int fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC); + if (fd < 0) { + const int err = errno; + Void::Log::warn("FileSystem", "read_file: cannot open '{}'", path.string()); + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + std::format("FileSystem::read_file: cannot open '{}'", path.string()), + err)}; + } + Void::System::OwnedFd guard{fd}; + + struct stat st {}; + if (::fstat(fd, &st) == 0 && S_ISREG(st.st_mode)) { + const auto sz = static_cast(st.st_size); + if (sz > options.max_bytes) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::limit_exceeded, + std::format("FileSystem::read_file: '{}' ({} bytes) exceeds limit ({})", + path.string(), + sz, + options.max_bytes))}; + } + } + + std::string content; + std::array buf{}; + for (;;) { + const ssize_t n = ::read(fd, buf.data(), buf.size()); + if (n > 0) { + const auto un = static_cast(n); + if (un > options.max_bytes - content.size()) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::limit_exceeded, + std::format("FileSystem::read_file: '{}' exceeded limit ({})", + path.string(), + options.max_bytes))}; + } + content.append(buf.data(), un); + } else if (n == 0) { + break; + } else { + if (errno == EINTR) { + continue; + } + const int err = errno; + Void::Log::warn("FileSystem", + "read_file: I/O error reading '{}'", + path.string()); + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + std::format("FileSystem::read_file: I/O error reading '{}'", + path.string()), + err)}; + } + } + Void::Log::debug("FileSystem", + "read_file: '{}' ({} bytes)", + path.string(), + content.size()); + return content; +#else + (void)path; + (void)options; + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::unsupported, + "FileSystem::read_file: unsupported platform")}; +#endif +} + +/// Read the entire contents of a file as a string (bounded at 16 MiB default). +[[nodiscard]] inline Void::Result::Result + read_file(const std::filesystem::path& path) +{ + return read_file_bounded(path, ReadFileOptions{}); +} + +/// Write `content` to `path`, overwriting any existing file (not crash-safe). +[[nodiscard]] inline Void::Result::Result + write_file(const std::filesystem::path& path, std::string_view content) +{ +#ifndef _WIN32 + const int fd = + ::open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); + if (fd < 0) { + const int err = errno; + Void::Log::warn("FileSystem", + "write_file: cannot open '{}'", + path.string()); + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + std::format("FileSystem::write_file: cannot open '{}'", path.string()), + err)}; + } + Void::System::OwnedFd guard{fd}; + + std::size_t off = 0; + while (off < content.size()) { + const ssize_t n = + ::write(fd, content.data() + off, content.size() - off); + if (n < 0) { + if (errno == EINTR) { + continue; + } + const int err = errno; + Void::Log::warn("FileSystem", + "write_file: I/O error writing '{}'", + path.string()); + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + std::format("FileSystem::write_file: I/O error writing '{}'", + path.string()), + err)}; + } + off += static_cast(n); + } + return guard.close(); +#else + (void)path; + (void)content; + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::unsupported, + "FileSystem::write_file: unsupported platform")}; +#endif +} + +/// Atomically stage and replace `path`, distinguishing atomic visibility vs +/// durable commit (`fsync` stage -> `renameat` -> `fsync` parent dir). +[[nodiscard]] inline std::expected replace_file( + const std::filesystem::path& path, + std::span bytes, + ReplaceOptions options = {}) +{ +#ifndef _WIN32 + auto check_fault = [&](ReplacePhase phase, + bool visible, + bool unknown) -> std::optional { + if (options.fault_hook) { + if (const auto injected = options.fault_hook(phase)) { + return ReplaceFailure{ + Void::System::make_system_error( + unknown + ? Void::System::SystemErrorCode::durability_unknown + : Void::System::map_errno_to_system_code(*injected), + std::format("FileSystem::replace_file: injected fault for '{}'", + path.string()), + *injected), + phase, + visible, + unknown}; + } + } + return std::nullopt; + }; + + if (auto f = check_fault(ReplacePhase::validation, false, false)) { + return std::unexpected{std::move(*f)}; + } + + if (path.empty() || !path.has_filename()) { + return std::unexpected{ReplaceFailure{ + Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "FileSystem::replace_file: empty path or missing filename"), + ReplacePhase::validation, + false, + false}}; + } + + const std::filesystem::path parent = + path.parent_path().empty() ? std::filesystem::path{"."} + : path.parent_path(); + const std::string target_name = path.filename().string(); + if (target_name == "." || target_name == "..") { + return std::unexpected{ReplaceFailure{ + Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "FileSystem::replace_file: invalid target filename"), + ReplacePhase::validation, + false, + false}}; + } + + const int raw_dir_fd = ::open( + parent.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (raw_dir_fd < 0) { + const int err = errno; + return std::unexpected{ReplaceFailure{ + Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + std::format("FileSystem::replace_file: cannot open parent '{}'", + parent.string()), + err), + ReplacePhase::validation, + false, + false}}; + } + Void::System::OwnedFd dir_fd{raw_dir_fd}; + + if (auto f = check_fault(ReplacePhase::create_stage, false, false)) { + return std::unexpected{std::move(*f)}; + } + + std::string tmp_name; + Void::System::OwnedFd tmp_fd; + int last_err = 0; + for (int attempt = 0; attempt < 32; ++attempt) { + tmp_name = std::format( + ".{}.void_tmp_{:016x}", target_name, detail::next_temp_entropy()); + const int fd = ::openat(dir_fd.get(), + tmp_name.c_str(), + O_CREAT | O_EXCL | O_WRONLY | O_NOFOLLOW | + O_CLOEXEC, + static_cast(options.mode)); + if (fd >= 0) { + tmp_fd.reset(fd); + break; + } + last_err = errno; + if (last_err != EEXIST) { + return std::unexpected{ReplaceFailure{ + Void::System::make_system_error( + Void::System::map_errno_to_system_code(last_err), + std::format( + "FileSystem::replace_file: cannot create temp in '{}'", + parent.string()), + last_err), + ReplacePhase::create_stage, + false, + false}}; + } + } + if (!tmp_fd.valid()) { + return std::unexpected{ReplaceFailure{ + Void::System::make_system_error( + Void::System::SystemErrorCode::already_exists, + "FileSystem::replace_file: exhausted temp names", + last_err), + ReplacePhase::create_stage, + false, + false}}; + } + + bool cleanup_temp = true; + struct TempCleanup { + int dir_fd{-1}; + const std::string* name{nullptr}; + bool* active{nullptr}; + ~TempCleanup() noexcept + { + if (active != nullptr && *active && dir_fd >= 0 && name != nullptr) { + (void)::unlinkat(dir_fd, name->c_str(), 0); + } + } + } temp_guard{dir_fd.get(), &tmp_name, &cleanup_temp}; + + if (auto f = check_fault(ReplacePhase::write_stage, false, false)) { + return std::unexpected{std::move(*f)}; + } + + std::size_t off = 0; + while (off < bytes.size()) { + const ssize_t n = + ::write(tmp_fd.get(), bytes.data() + off, bytes.size() - off); + if (n < 0) { + if (errno == EINTR) { + continue; + } + const int err = errno; + return std::unexpected{ReplaceFailure{ + Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + std::format("FileSystem::replace_file: write failed for '{}'", + path.string()), + err), + ReplacePhase::write_stage, + false, + false}}; + } + off += static_cast(n); + } + + if (options.durability == ReplaceDurability::durable_sync) { + if (auto f = check_fault(ReplacePhase::sync_stage, false, false)) { + return std::unexpected{std::move(*f)}; + } + if (const int err = detail::fsync_eintr(tmp_fd.get()); err != 0) { + return std::unexpected{ReplaceFailure{ + Void::System::make_system_error( + Void::System::SystemErrorCode::sync_failed, + std::format( + "FileSystem::replace_file: stage fsync failed for '{}'", + path.string()), + err), + ReplacePhase::sync_stage, + false, + false}}; + } + } + + if (auto closed = tmp_fd.close(); !closed.has_value()) { + return std::unexpected{ReplaceFailure{ + std::move(closed.error()), + ReplacePhase::write_stage, + false, + false}}; + } + + if (auto f = check_fault(ReplacePhase::rename, false, false)) { + return std::unexpected{std::move(*f)}; + } + + if (::renameat( + dir_fd.get(), tmp_name.c_str(), dir_fd.get(), target_name.c_str()) != + 0) { + const int err = errno; + return std::unexpected{ReplaceFailure{ + Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + std::format("FileSystem::replace_file: rename failed for '{}'", + path.string()), + err), + ReplacePhase::rename, + false, + false}}; + } + + // Rename succeeded: target is now visible on disk; never unlink target! + cleanup_temp = false; + + if (options.durability == ReplaceDurability::durable_sync) { + if (auto f = check_fault(ReplacePhase::sync_parent, true, true)) { + return std::unexpected{std::move(*f)}; + } + if (const int err = detail::fsync_eintr(dir_fd.get()); err != 0) { + return std::unexpected{ReplaceFailure{ + Void::System::make_system_error( + Void::System::SystemErrorCode::durability_unknown, + std::format( + "FileSystem::replace_file: parent dir fsync failed after rename for '{}'", + path.string()), + err), + ReplacePhase::sync_parent, + true, + true}}; + } + } + + Void::Log::debug("FileSystem", + "replace_file: '{}' committed ({} bytes)", + path.string(), + bytes.size()); + return {}; +#else + (void)path; + (void)bytes; + (void)options; + return std::unexpected{ReplaceFailure{ + Void::System::make_system_error( + Void::System::SystemErrorCode::unsupported, + "FileSystem::replace_file: unsupported platform"), + ReplacePhase::validation, + false, + false}}; +#endif +} + +[[nodiscard]] inline std::expected replace_file( + const std::filesystem::path& path, + std::string_view content, + ReplaceOptions options = {}) +{ + const auto* ptr = reinterpret_cast(content.data()); + return replace_file(path, std::span{ptr, content.size()}, std::move(options)); +} + +/// Crash-safe write: stages content in a unique temp file and atomically +/// renames onto `path`. Delegates to `replace_file(..., atomic_visibility)` to +/// preserve 1.x atomic replacement behavior safely across concurrent writers. +[[nodiscard]] inline Void::Result::Result + atomic_write(const std::filesystem::path& path, std::string_view content) +{ + auto res = replace_file( + path, + content, + ReplaceOptions{.durability = ReplaceDurability::atomic_visibility}); + if (!res.has_value()) { + Void::Log::warn("FileSystem", + "atomic_write: failed for '{}': {}", + path.string(), + res.error().error.message()); + return std::unexpected{std::move(res.error().error)}; + } + return {}; +} + +/// Create `path` as a directory, including any missing parents. +[[nodiscard]] inline Void::Result::Result + ensure_directory(const std::filesystem::path& path) +{ + std::error_code ec; + if (std::filesystem::is_directory(path, ec)) { + return {}; + } + std::filesystem::create_directories(path, ec); + if (ec) { + Void::Log::warn("FileSystem", + "ensure_directory: cannot create '{}': {}", + path.string(), + ec.message()); + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(ec.value()), + std::format("FileSystem::ensure_directory: cannot create '{}': {}", + path.string(), + ec.message()))}; + } + Void::Log::debug("FileSystem", "ensure_directory: created '{}'", path.string()); + return {}; +} + +/// Remove a file or directory (recursively for directories). +[[nodiscard]] inline Void::Result::Result + remove_path(const std::filesystem::path& path) +{ + std::error_code ec; + std::filesystem::remove_all(path, ec); + if (ec) { + Void::Log::warn("FileSystem", + "remove_path: cannot remove '{}': {}", + path.string(), + ec.message()); + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(ec.value()), + std::format("FileSystem::remove_path: cannot remove '{}': {}", + path.string(), + ec.message()))}; + } + return {}; +} } // namespace Void::FileSystem diff --git a/include/Void/System/Process.hpp b/include/Void/System/Process.hpp index 5e9c3f5..626e4d1 100644 --- a/include/Void/System/Process.hpp +++ b/include/Void/System/Process.hpp @@ -2,72 +2,203 @@ #include #include +#include #include +#include #include #include +#include +#include #include #include +#include #include namespace Void::Process { - /// Captured output from a completed subprocess. - struct Output { - int exit_code{0}; - std::string out; ///< captured stdout - std::string err; ///< captured stderr - }; +inline constexpr std::size_t kMaxSpawnInputBytes = 256ULL * 1024ULL; +inline constexpr std::size_t kDefaultMaxStdoutBytes = 1024ULL * 1024ULL; +inline constexpr std::size_t kDefaultMaxStderrBytes = 1024ULL * 1024ULL; +inline constexpr std::size_t kDefaultMaxLineBytes = 64ULL * 1024ULL; +inline constexpr std::size_t kDefaultMaxStdinBytes = 4ULL * 1024ULL * 1024ULL; - /// Live line callbacks for run_streaming(). Each fires (on the calling - /// thread, as output arrives) with one line of output, newline stripped. - /// Either may be left empty. The full output is still accumulated into the - /// returned Output. - struct StreamCallbacks { - std::function on_stdout; - std::function on_stderr; - }; +/// Captured output from a completed subprocess. +struct Output { + int exit_code{0}; + std::string out; ///< captured stdout + std::string err; ///< captured stderr +}; - /// Run an executable synchronously, capturing stdout and stderr separately. - /// - /// @param executable Path to the binary (searched via PATH when relative). - /// @param args Additional arguments passed after argv[0]. - /// @param stdin_data Data written to the process's stdin before reading. - /// @param timeout Wall-clock limit; zero means no limit. On expiry the - /// process receives SIGTERM and the call returns. - /// - /// Returns an error only when process creation itself fails (pipe or fork - /// failure). A process that exits non-zero still yields a successful Result - /// with the appropriate exit_code. A process whose executable is not found - /// exits with code 127 (POSIX convention). - [[nodiscard]] Void::Result::Result - run(const std::filesystem::path& executable, - std::vector args = {}, - std::string_view stdin_data = {}, - std::chrono::milliseconds timeout = std::chrono::milliseconds{0}); +/// Live line callbacks for run_streaming() and communicate_blocking(). +struct StreamCallbacks { + std::function on_stdout; + std::function on_stderr; +}; - /// Like run(), but invokes `callbacks` line-by-line as stdout/stderr - /// arrive, for progress reporting on long-running or streaming processes. - /// The complete output is still captured into the returned Output. - [[nodiscard]] Void::Result::Result - run_streaming( - const std::filesystem::path& executable, - std::vector args, - const StreamCallbacks& callbacks, - std::string_view stdin_data = {}, - std::chrono::milliseconds timeout = std::chrono::milliseconds{0}); +enum class OverflowPolicy { + fail_and_terminate, + drain_and_truncate, +}; - /// Run a command through /bin/sh -c "command". - [[nodiscard]] Void::Result::Result - shell(std::string_view command, - std::chrono::milliseconds timeout = std::chrono::milliseconds{0}); +enum class EnvMode { + inherit, + allowlist, + explicit_only, +}; - /// Replace the current process image while preserving its PID and inherited - /// environment. Returns only when the platform does not support re-exec or - /// exec fails. - [[nodiscard]] Void::Result::Result - reexec(const std::filesystem::path& executable, - const std::vector& arguments); +struct EnvironmentPolicy { + EnvMode mode{EnvMode::inherit}; + std::vector allowlist{}; + std::vector> set_vars{}; + std::vector unset_keys{}; + std::vector redacted_keys{}; +}; + +struct CaptureLimits { + std::size_t max_stdout_bytes{kDefaultMaxStdoutBytes}; + std::size_t max_stderr_bytes{kDefaultMaxStderrBytes}; + std::size_t max_line_bytes{kDefaultMaxLineBytes}; + std::size_t max_stdin_bytes{kDefaultMaxStdinBytes}; + OverflowPolicy overflow_policy{OverflowPolicy::fail_and_terminate}; +}; + +struct SpawnOptions { + std::filesystem::path executable{}; + std::vector arguments{}; + std::optional working_directory{}; + EnvironmentPolicy environment{}; + bool stdin_pipe{true}; + bool stdout_pipe{true}; + bool stderr_pipe{true}; + bool search_path{true}; + bool new_process_group{true}; + std::chrono::milliseconds kill_grace{std::chrono::milliseconds{2000}}; +}; + +struct ExitStatus { + bool exited{false}; + int code{-1}; + int signal{0}; + int raw_status{0}; +}; + +struct CommunicateResult { + ExitStatus status{}; + std::string out{}; + std::string err{}; + bool stdout_truncated{false}; + bool stderr_truncated{false}; + bool timed_out{false}; + bool cancelled{false}; + bool overflowed{false}; +}; + +class Child +{ +public: + Child() noexcept = default; + Child(long long pid, + long long pgid, + bool owns_process_group, + Void::System::OwnedFd stdin_fd, + Void::System::OwnedFd stdout_fd, + Void::System::OwnedFd stderr_fd, + std::chrono::milliseconds kill_grace) noexcept; + + ~Child() noexcept; + + Child(const Child&) = delete; + Child& operator=(const Child&) = delete; + Child(Child&& other) noexcept; + Child& operator=(Child&& other) noexcept; + + [[nodiscard]] bool valid() const noexcept; + [[nodiscard]] bool running() const noexcept; + [[nodiscard]] long long pid() const noexcept; + [[nodiscard]] long long pgid() const noexcept; + [[nodiscard]] bool owns_process_group() const noexcept; + + [[nodiscard]] int stdin_fd() const noexcept; + [[nodiscard]] int stdout_fd() const noexcept; + [[nodiscard]] int stderr_fd() const noexcept; + + [[nodiscard]] Void::System::OwnedFd take_stdin_fd() noexcept; + [[nodiscard]] Void::System::OwnedFd take_stdout_fd() noexcept; + [[nodiscard]] Void::System::OwnedFd take_stderr_fd() noexcept; + void close_stdin() noexcept; + + [[nodiscard]] Void::Result::Result + send_signal(int sig) noexcept; + + [[nodiscard]] Void::Result::Result + terminate(std::chrono::milliseconds grace = std::chrono::milliseconds{-1}); + + [[nodiscard]] Void::Result::Result, Void::Result::Error> + try_wait(); + + [[nodiscard]] Void::Result::Result + wait_blocking(std::chrono::milliseconds timeout = std::chrono::milliseconds{0}, + std::stop_token stop = {}, + std::chrono::milliseconds kill_grace = std::chrono::milliseconds{-1}); + +private: + long long pid_{-1}; + long long pgid_{-1}; + bool owns_group_{false}; + bool reaped_{true}; + ExitStatus cached_status_{}; + Void::System::OwnedFd stdin_{}; + Void::System::OwnedFd stdout_{}; + Void::System::OwnedFd stderr_{}; + std::chrono::milliseconds kill_grace_{std::chrono::milliseconds{2000}}; + + void reset_and_reap() noexcept; +}; + +[[nodiscard]] Void::Result::Result + spawn(const SpawnOptions& options); + +[[nodiscard]] Void::Result::Result + communicate_blocking(Child& child, + std::string_view stdin_data = {}, + CaptureLimits limits = {}, + std::chrono::milliseconds timeout = std::chrono::milliseconds{0}, + std::stop_token stop = {}, + const StreamCallbacks* callbacks = nullptr); + +/// Run an executable synchronously, capturing stdout and stderr separately. +[[nodiscard]] Void::Result::Result + run(const std::filesystem::path& executable, + std::vector args = {}, + std::string_view stdin_data = {}, + std::chrono::milliseconds timeout = std::chrono::milliseconds{0}); + +/// Like run(), but invokes `callbacks` line-by-line as stdout/stderr arrive. +[[nodiscard]] Void::Result::Result + run_streaming( + const std::filesystem::path& executable, + std::vector args, + const StreamCallbacks& callbacks, + std::string_view stdin_data = {}, + std::chrono::milliseconds timeout = std::chrono::milliseconds{0}); + +/// Run a command through /bin/sh -c "command". +[[nodiscard]] Void::Result::Result + shell(std::string_view command, + std::chrono::milliseconds timeout = std::chrono::milliseconds{0}); + +/// Replace the current process image while preserving its PID and inherited +/// environment. +[[nodiscard]] Void::Result::Result + reexec(const std::filesystem::path& executable, + const std::vector& arguments); + +/// Replace the current process image with explicit open-descriptor cleanup policy. +[[nodiscard]] Void::Result::Result + reexec(const std::filesystem::path& executable, + const std::vector& arguments, + bool close_extra_fds); } // namespace Void::Process diff --git a/include/Void/System/Query.hpp b/include/Void/System/Query.hpp index d004c9c..2cab9b2 100644 --- a/include/Void/System/Query.hpp +++ b/include/Void/System/Query.hpp @@ -1,9 +1,13 @@ #pragma once -#include #include #include +#include +#include +#include +#include +#include #include #include #include @@ -12,113 +16,161 @@ namespace Void::FileSystem { +struct ListDirectoryOptions { + std::size_t max_entries{65536}; +}; + /// Return true if path exists (file, directory, or symlink). [[nodiscard]] inline bool exists(const std::filesystem::path& path) noexcept { - std::error_code ec; - return std::filesystem::exists(path, ec); + std::error_code ec; + return std::filesystem::exists(path, ec); } /// Return the size of a regular file in bytes. [[nodiscard]] inline Void::Result::Result - file_size(const std::filesystem::path& path) + file_size(const std::filesystem::path& path) { - std::error_code ec; - auto sz = std::filesystem::file_size(path, ec); - if (ec) { - Void::Log::warn("FileSystem", "file_size: cannot stat '{}': {}", path.string(), - ec.message()); - return Void::Result::fail( - std::format("FileSystem::file_size: cannot stat '{}': {}", - path.string(), ec.message())); - } - return Void::Result::ok(sz); + std::error_code ec; + auto sz = std::filesystem::file_size(path, ec); + if (ec) { + Void::Log::warn("FileSystem", + "file_size: cannot stat '{}': {}", + path.string(), + ec.message()); + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(ec.value()), + std::format("FileSystem::file_size: cannot stat '{}': {}", + path.string(), + ec.message()))}; + } + return Void::Result::ok(sz); } /// Return the last-write time of a path. [[nodiscard]] inline Void::Result:: - Result - last_modified(const std::filesystem::path& path) + Result + last_modified(const std::filesystem::path& path) { - std::error_code ec; - auto t = std::filesystem::last_write_time(path, ec); - if (ec) { - Void::Log::warn("FileSystem", "last_modified: cannot stat '{}': {}", path.string(), - ec.message()); - return Void::Result::fail( - std::format("FileSystem::last_modified: cannot stat '{}': {}", - path.string(), ec.message())); - } - return Void::Result::ok(t); + std::error_code ec; + auto t = std::filesystem::last_write_time(path, ec); + if (ec) { + Void::Log::warn("FileSystem", + "last_modified: cannot stat '{}': {}", + path.string(), + ec.message()); + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(ec.value()), + std::format("FileSystem::last_modified: cannot stat '{}': {}", + path.string(), + ec.message()))}; + } + return Void::Result::ok(t); } -/// List all entries in a directory (non-recursive, filesystem order). +/// List entries in a directory up to `options.max_entries`. [[nodiscard]] inline Void::Result:: - Result, Void::Result::Error> - list_directory(const std::filesystem::path& path) + Result, Void::Result::Error> + list_directory_bounded(const std::filesystem::path& path, + ListDirectoryOptions options = {}) { - std::error_code ec; - std::vector entries; - for (const auto& entry : - std::filesystem::directory_iterator{path, ec}) { - if (ec) { - break; - } - entries.push_back(entry.path()); - } - if (ec) { - Void::Log::warn("FileSystem", "list_directory: cannot iterate '{}': {}", - path.string(), ec.message()); - return Void::Result::fail( - std::format("FileSystem::list_directory: cannot iterate '{}': {}", - path.string(), ec.message())); - } - Void::Log::debug("FileSystem", "list_directory: '{}' ({} entries)", - path.string(), entries.size()); - return Void::Result::ok(std::move(entries)); + std::error_code ec; + std::vector entries; + for (const auto& entry : std::filesystem::directory_iterator{path, ec}) { + if (ec) { + break; + } + if (entries.size() >= options.max_entries) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::limit_exceeded, + std::format( + "FileSystem::list_directory: '{}' exceeded max_entries ({})", + path.string(), + options.max_entries))}; + } + entries.push_back(entry.path()); + } + if (ec) { + Void::Log::warn("FileSystem", + "list_directory: cannot iterate '{}': {}", + path.string(), + ec.message()); + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(ec.value()), + std::format("FileSystem::list_directory: cannot iterate '{}': {}", + path.string(), + ec.message()))}; + } + Void::Log::debug("FileSystem", + "list_directory: '{}' ({} entries)", + path.string(), + entries.size()); + return Void::Result::ok(std::move(entries)); +} + +/// List all entries in a directory (bounded at 65,536 default). +[[nodiscard]] inline Void::Result:: + Result, Void::Result::Error> + list_directory(const std::filesystem::path& path) +{ + return list_directory_bounded(path, ListDirectoryOptions{}); } /// Copy a single file. Set overwrite=true to allow replacing an existing dst. [[nodiscard]] inline Void::Result::Result - copy_file(const std::filesystem::path& src, - const std::filesystem::path& dst, - bool overwrite = false) + copy_file(const std::filesystem::path& src, + const std::filesystem::path& dst, + bool overwrite = false) { - std::error_code ec; - auto opts = overwrite ? std::filesystem::copy_options::overwrite_existing - : std::filesystem::copy_options::none; - std::filesystem::copy_file(src, dst, opts, ec); - if (ec) { - Void::Log::warn("FileSystem", "copy_file: '{}' -> '{}': {}", src.string(), - dst.string(), ec.message()); - return Void::Result::fail( - std::format("FileSystem::copy_file: '{}' -> '{}': {}", - src.string(), dst.string(), ec.message())); - } - Void::Log::debug("FileSystem", "copy_file: '{}' -> '{}'", src.string(), - dst.string()); - return {}; + std::error_code ec; + auto opts = overwrite ? std::filesystem::copy_options::overwrite_existing + : std::filesystem::copy_options::none; + std::filesystem::copy_file(src, dst, opts, ec); + if (ec) { + Void::Log::warn("FileSystem", + "copy_file: '{}' -> '{}': {}", + src.string(), + dst.string(), + ec.message()); + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(ec.value()), + std::format("FileSystem::copy_file: '{}' -> '{}': {}", + src.string(), + dst.string(), + ec.message()))}; + } + Void::Log::debug("FileSystem", + "copy_file: '{}' -> '{}'", + src.string(), + dst.string()); + return {}; } /// Recursively copy a directory tree from src to dst. -/// dst must not already exist; its parent must be accessible. [[nodiscard]] inline Void::Result::Result - copy_dir(const std::filesystem::path& src, - const std::filesystem::path& dst) + copy_dir(const std::filesystem::path& src, const std::filesystem::path& dst) { - std::error_code ec; - std::filesystem::copy(src, dst, std::filesystem::copy_options::recursive, - ec); - if (ec) { - Void::Log::warn("FileSystem", "copy_dir: '{}' -> '{}': {}", src.string(), - dst.string(), ec.message()); - return Void::Result::fail( - std::format("FileSystem::copy_dir: '{}' -> '{}': {}", - src.string(), dst.string(), ec.message())); - } - Void::Log::debug("FileSystem", "copy_dir: '{}' -> '{}'", src.string(), - dst.string()); - return {}; + std::error_code ec; + std::filesystem::copy( + src, dst, std::filesystem::copy_options::recursive, ec); + if (ec) { + Void::Log::warn("FileSystem", + "copy_dir: '{}' -> '{}': {}", + src.string(), + dst.string(), + ec.message()); + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(ec.value()), + std::format("FileSystem::copy_dir: '{}' -> '{}': {}", + src.string(), + dst.string(), + ec.message()))}; + } + Void::Log::debug("FileSystem", + "copy_dir: '{}' -> '{}'", + src.string(), + dst.string()); + return {}; } } // namespace Void::FileSystem diff --git a/include/Void/System/TempDir.hpp b/include/Void/System/TempDir.hpp index 424f651..c00b656 100644 --- a/include/Void/System/TempDir.hpp +++ b/include/Void/System/TempDir.hpp @@ -1,126 +1,251 @@ #pragma once -#include #include +#include +#include -#include -#include #include +#include #include #include #include #include #include -#include #include +#include + +#ifndef _WIN32 +#include +#include +#include +#include +#endif namespace Void::FileSystem { - /// RAII scoped directory under `std::filesystem::temp_directory_path()`. - /// - /// The directory is created with a unique name on construction and - /// recursively removed on destruction. Useful in tests that need a - /// scratch area without manual cleanup. - /// - /// Construction throws `std::system_error` if the directory cannot - /// be created. Use `TempDir::open(prefix)` for a non-throwing - /// `Result`-returning factory. - class TempDir - { - public: - explicit TempDir(std::string_view prefix = "void_test_") - : m_path(make_unique_dir(prefix)) - { - } +/// RAII scoped directory created with private `0700` permissions and removed +/// safely without following symlinks or deleting replaced directories. +class TempDir +{ +public: + explicit TempDir(std::string_view prefix = "void_test_") + { + auto created = create_unique_dir( + std::filesystem::temp_directory_path(), prefix); + if (!created.has_value()) { + throw std::system_error( + std::make_error_code(std::errc::file_exists), + created.error().message()); + } + *this = std::move(*created); + } - ~TempDir() noexcept - { - if (!m_path.empty()) { - Void::Log::debug("FileSystem", "TempDir: removed '{}'", m_path.string()); - std::error_code ignore; - std::filesystem::remove_all(m_path, ignore); - } - } + ~TempDir() noexcept { remove_if_owned(); } - TempDir(const TempDir&) = delete; - TempDir& operator=(const TempDir&) = delete; + TempDir(const TempDir&) = delete; + TempDir& operator=(const TempDir&) = delete; - TempDir(TempDir&& other) noexcept - : m_path(std::exchange(other.m_path, {})) - { - } + TempDir(TempDir&& other) noexcept + : m_path(std::exchange(other.m_path, {})), + m_dev(std::exchange(other.m_dev, 0)), + m_ino(std::exchange(other.m_ino, 0)) + { + } - TempDir& operator=(TempDir&& other) noexcept - { - if (this != &other) { - if (!m_path.empty()) { - std::error_code ignore; - std::filesystem::remove_all(m_path, ignore); - } - m_path = std::exchange(other.m_path, {}); - } - return *this; - } + TempDir& operator=(TempDir&& other) noexcept + { + if (this != &other) { + remove_if_owned(); + m_path = std::exchange(other.m_path, {}); + m_dev = std::exchange(other.m_dev, 0); + m_ino = std::exchange(other.m_ino, 0); + } + return *this; + } - [[nodiscard]] const std::filesystem::path& path() const noexcept - { - return m_path; - } + [[nodiscard]] const std::filesystem::path& path() const noexcept + { + return m_path; + } - /// Build a path inside the temp dir. - /// Example: `auto log_path = tmp / "test.log";` - [[nodiscard]] std::filesystem::path - operator/(std::string_view relative) const - { - return m_path / relative; - } + [[nodiscard]] std::filesystem::path + operator/(std::string_view relative) const + { + return m_path / relative; + } - /// Non-throwing factory. - [[nodiscard]] static Void::Result::Result - open(std::string_view prefix = "void_test_") - { - try { - return Void::Result::ok(TempDir{prefix}); - } catch (const std::exception& e) { - return Void::Result::fail(std::string{e.what()}); - } - } + [[nodiscard]] static Void::Result::Result + open(std::string_view prefix = "void_test_") + { + return open_in(std::filesystem::temp_directory_path(), prefix); + } - private: + [[nodiscard]] static Void::Result::Result + open_in(const std::filesystem::path& directory, + std::string_view prefix = "void_test_") + { + return create_unique_dir(directory, prefix); + } - std::filesystem::path m_path; +private: + struct InternalEmpty {}; + explicit TempDir(InternalEmpty) noexcept {} - static std::filesystem::path - make_unique_dir(std::string_view prefix) - { - static std::atomic counter{0}; - const auto base = std::filesystem::temp_directory_path(); - for (int attempt = 0; attempt < 16; ++attempt) { - const auto seed = - static_cast( - std::chrono::steady_clock::now() - .time_since_epoch() - .count()) ^ - (counter.fetch_add(1, std::memory_order_relaxed) - << 16) ^ - static_cast(std::hash{}( - std::this_thread::get_id())); - auto candidate = - base / std::format("{}{:016x}", prefix, seed); - std::error_code ec; - if (std::filesystem::create_directory(candidate, ec)) { - Void::Log::debug("FileSystem", "TempDir: created '{}'", - candidate.string()); - return candidate; - } - } - throw std::system_error( - std::make_error_code(std::errc::file_exists), - "TempDir: failed to create unique directory after 16 " - "attempts"); - } - }; + std::filesystem::path m_path; + std::uint64_t m_dev = 0; + std::uint64_t m_ino = 0; + +#ifndef _WIN32 + static void clear_dir_contents_nofollow(int dir_fd) noexcept + { + const int dup_fd = ::dup(dir_fd); + if (dup_fd < 0) { + return; + } + DIR* dir = ::fdopendir(dup_fd); + if (dir == nullptr) { + (void)::close(dup_fd); + return; + } + std::vector subdirs; + std::vector files; + while (const struct dirent* ent = ::readdir(dir)) { + const std::string_view name{ent->d_name}; + if (name == "." || name == "..") { + continue; + } + struct stat st {}; + if (::fstatat(dir_fd, ent->d_name, &st, AT_SYMLINK_NOFOLLOW) != 0) { + continue; + } + if (S_ISDIR(st.st_mode)) { + subdirs.emplace_back(name); + } else { + files.emplace_back(name); + } + } + (void)::closedir(dir); + + for (const auto& f : files) { + (void)::unlinkat(dir_fd, f.c_str(), 0); + } + for (const auto& d : subdirs) { + const int sub_fd = ::openat( + dir_fd, + d.c_str(), + O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC); + if (sub_fd >= 0) { + clear_dir_contents_nofollow(sub_fd); + (void)::close(sub_fd); + (void)::unlinkat(dir_fd, d.c_str(), AT_REMOVEDIR); + } + } + } +#endif + + void remove_if_owned() noexcept + { + if (m_path.empty()) { + return; + } +#ifndef _WIN32 + struct stat st {}; + if (::lstat(m_path.c_str(), &st) != 0 || S_ISLNK(st.st_mode) || + !S_ISDIR(st.st_mode)) { + return; + } + if (static_cast(st.st_dev) != m_dev || + static_cast(st.st_ino) != m_ino || + st.st_uid != ::geteuid()) { + return; + } + const int dir_fd = ::open( + m_path.c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC); + if (dir_fd < 0) { + return; + } + struct stat fd_st {}; + if (::fstat(dir_fd, &fd_st) == 0 && + static_cast(fd_st.st_dev) == m_dev && + static_cast(fd_st.st_ino) == m_ino) { + clear_dir_contents_nofollow(dir_fd); + } + (void)::close(dir_fd); + (void)::rmdir(m_path.c_str()); + Void::Log::debug( + "FileSystem", "TempDir: removed '{}'", m_path.string()); +#endif + } + + [[nodiscard]] static Void::Result::Result + create_unique_dir(const std::filesystem::path& base, + std::string_view prefix) + { +#ifndef _WIN32 + if (prefix.find('/') != std::string_view::npos || + prefix.find('\0') != std::string_view::npos) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "TempDir: prefix must not contain '/' or NUL")}; + } + + int last_err = 0; + for (int attempt = 0; attempt < 32; ++attempt) { + const auto seed = detail::next_temp_entropy(); + auto candidate = base / std::format("{}{:016x}", prefix, seed); + if (::mkdir(candidate.c_str(), 0700) == 0) { + const int fd = ::open( + candidate.c_str(), + O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC); + if (fd < 0) { + const int err = errno; + (void)::rmdir(candidate.c_str()); + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + "TempDir: open failed after mkdir", + err)}; + } + Void::System::OwnedFd guard{fd}; + struct stat st {}; + if (::fstat(fd, &st) != 0) { + const int err = errno; + guard.reset(); + (void)::rmdir(candidate.c_str()); + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + "TempDir: fstat failed", + err)}; + } + TempDir out{InternalEmpty{}}; + out.m_path = std::move(candidate); + out.m_dev = static_cast(st.st_dev); + out.m_ino = static_cast(st.st_ino); + Void::Log::debug( + "FileSystem", "TempDir: created '{}'", out.m_path.string()); + return out; + } + last_err = errno; + if (last_err != EEXIST) { + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(last_err), + std::format( + "TempDir: failed creating '{}'", candidate.string()), + last_err)}; + } + } + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::already_exists, + "TempDir: failed to create unique directory after 32 attempts", + last_err)}; +#else + (void)base; + (void)prefix; + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::unsupported, + "TempDir: unsupported platform")}; +#endif + } +}; } // namespace Void::FileSystem diff --git a/include/Void/System/TempFile.hpp b/include/Void/System/TempFile.hpp index 3b0599a..21d6faf 100644 --- a/include/Void/System/TempFile.hpp +++ b/include/Void/System/TempFile.hpp @@ -2,135 +2,193 @@ #include #include +#include +#include #include #include #include +#include #include #include -#include #include #include #include #include #include +#ifndef _WIN32 +#include +#include +#include +#endif + namespace Void::FileSystem { - /// RAII scoped *file* under `std::filesystem::temp_directory_path()`. - /// - /// A uniquely-named empty file is created on construction and removed on - /// destruction, unless `keep()` was called. Move-only. Useful for staging - /// downloads, copying a shared library to a fresh inode, etc. - /// - /// Construction throws `std::system_error` if the file cannot be created; - /// use `TempFile::open(prefix, ext)` for a non-throwing factory. - class TempFile - { - public: - explicit TempFile(std::string_view prefix = "void_", - std::string_view extension = "") - : m_path(make_unique_file(prefix, extension)) - { - } +/// RAII scoped regular file created atomically (`O_CREAT|O_EXCL|O_NOFOLLOW`, `0600`). +class TempFile +{ +public: + explicit TempFile(std::string_view prefix = "void_", + std::string_view extension = "") + { + auto created = create_unique_file( + std::filesystem::temp_directory_path(), prefix, extension); + if (!created.has_value()) { + throw std::system_error( + std::make_error_code(std::errc::file_exists), + created.error().message()); + } + *this = std::move(*created); + } - ~TempFile() noexcept - { - if (!m_path.empty() && !m_keep) { - std::error_code ignore; - std::filesystem::remove(m_path, ignore); - Void::Log::debug("FileSystem", "TempFile: removed '{}'", - m_path.string()); - } - } + ~TempFile() noexcept { remove_if_owned(); } - TempFile(const TempFile&) = delete; - TempFile& operator=(const TempFile&) = delete; + TempFile(const TempFile&) = delete; + TempFile& operator=(const TempFile&) = delete; - TempFile(TempFile&& other) noexcept - : m_path(std::exchange(other.m_path, {})), - m_keep(std::exchange(other.m_keep, true)) - { - } + TempFile(TempFile&& other) noexcept + : m_path(std::exchange(other.m_path, {})), + m_keep(std::exchange(other.m_keep, true)), + m_dev(std::exchange(other.m_dev, 0)), + m_ino(std::exchange(other.m_ino, 0)) + { + } - TempFile& operator=(TempFile&& other) noexcept - { - if (this != &other) { - if (!m_path.empty() && !m_keep) { - std::error_code ignore; - std::filesystem::remove(m_path, ignore); - } - m_path = std::exchange(other.m_path, {}); - m_keep = std::exchange(other.m_keep, true); - } - return *this; - } + TempFile& operator=(TempFile&& other) noexcept + { + if (this != &other) { + remove_if_owned(); + m_path = std::exchange(other.m_path, {}); + m_keep = std::exchange(other.m_keep, true); + m_dev = std::exchange(other.m_dev, 0); + m_ino = std::exchange(other.m_ino, 0); + } + return *this; + } - [[nodiscard]] const std::filesystem::path& path() const noexcept - { - return m_path; - } + [[nodiscard]] const std::filesystem::path& path() const noexcept + { + return m_path; + } - /// Persist the file beyond this object's lifetime (no removal on - /// destruction). Returns the path for convenience. - std::filesystem::path keep() noexcept - { - m_keep = true; - return m_path; - } + std::filesystem::path keep() noexcept + { + m_keep = true; + return m_path; + } - /// Non-throwing factory. - [[nodiscard]] static Void::Result::Result - open(std::string_view prefix = "void_", - std::string_view extension = "") - { - try { - return Void::Result::ok(TempFile{prefix, extension}); - } catch (const std::exception& e) { - return Void::Result::fail(std::string{e.what()}); - } - } + [[nodiscard]] static Void::Result::Result + open(std::string_view prefix = "void_", + std::string_view extension = "") + { + return open_in( + std::filesystem::temp_directory_path(), prefix, extension); + } - private: + [[nodiscard]] static Void::Result::Result + open_in(const std::filesystem::path& directory, + std::string_view prefix = "void_", + std::string_view extension = "") + { + return create_unique_file(directory, prefix, extension); + } - std::filesystem::path m_path; - bool m_keep = false; +private: + struct InternalEmpty {}; + explicit TempFile(InternalEmpty) noexcept {} - static std::filesystem::path - make_unique_file(std::string_view prefix, - std::string_view extension) - { - static std::atomic counter{0}; - const auto base = std::filesystem::temp_directory_path(); - for (int attempt = 0; attempt < 16; ++attempt) { - const auto seed = - static_cast( - std::chrono::steady_clock::now() - .time_since_epoch() - .count()) ^ - (counter.fetch_add(1, std::memory_order_relaxed) << 16) ^ - static_cast( - std::hash{}( - std::this_thread::get_id())); - auto candidate = - base / std::format("{}{:016x}{}", prefix, seed, extension); - std::error_code ec; - if (!std::filesystem::exists(candidate, ec)) { - std::ofstream f(candidate); - if (f) { - Void::Log::debug("FileSystem", - "TempFile: created '{}'", - candidate.string()); - return candidate; - } - } - } - throw std::system_error( - std::make_error_code(std::errc::file_exists), - "TempFile: failed to create unique file after 16 attempts"); - } - }; + std::filesystem::path m_path; + bool m_keep = true; + std::uint64_t m_dev = 0; + std::uint64_t m_ino = 0; + + void remove_if_owned() noexcept + { + if (m_path.empty() || m_keep) { + return; + } +#ifndef _WIN32 + struct stat st {}; + if (::lstat(m_path.c_str(), &st) == 0 && !S_ISLNK(st.st_mode) && + S_ISREG(st.st_mode) && + static_cast(st.st_dev) == m_dev && + static_cast(st.st_ino) == m_ino) { + (void)::unlink(m_path.c_str()); + Void::Log::debug( + "FileSystem", "TempFile: removed '{}'", m_path.string()); + } +#endif + } + + [[nodiscard]] static Void::Result::Result + create_unique_file(const std::filesystem::path& base, + std::string_view prefix, + std::string_view extension) + { +#ifndef _WIN32 + if (prefix.find('/') != std::string_view::npos || + prefix.find('\0') != std::string_view::npos || + extension.find('/') != std::string_view::npos || + extension.find('\0') != std::string_view::npos) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "TempFile: prefix/extension must not contain '/' or NUL")}; + } + + int last_err = 0; + for (int attempt = 0; attempt < 32; ++attempt) { + const auto seed = detail::next_temp_entropy(); + auto candidate = + base / std::format("{}{:016x}{}", prefix, seed, extension); + const int fd = ::open(candidate.c_str(), + O_CREAT | O_EXCL | O_RDWR | O_NOFOLLOW | + O_CLOEXEC, + 0600); + if (fd >= 0) { + Void::System::OwnedFd guard{fd}; + struct stat st {}; + if (::fstat(fd, &st) != 0) { + const int err = errno; + guard.reset(); + (void)::unlink(candidate.c_str()); + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + "TempFile: fstat failed", + err)}; + } + TempFile out{InternalEmpty{}}; + out.m_path = std::move(candidate); + out.m_keep = false; + out.m_dev = static_cast(st.st_dev); + out.m_ino = static_cast(st.st_ino); + Void::Log::debug( + "FileSystem", "TempFile: created '{}'", out.m_path.string()); + return out; + } + last_err = errno; + if (last_err != EEXIST) { + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(last_err), + std::format("TempFile: failed creating '{}'", + candidate.string()), + last_err)}; + } + } + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::already_exists, + "TempFile: failed to create unique file after 32 attempts", + last_err)}; +#else + (void)base; + (void)prefix; + (void)extension; + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::unsupported, + "TempFile: unsupported platform")}; +#endif + } +}; } // namespace Void::FileSystem diff --git a/include/Void/System/Types.hpp b/include/Void/System/Types.hpp new file mode 100644 index 0000000..0f2505b --- /dev/null +++ b/include/Void/System/Types.hpp @@ -0,0 +1,207 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef _WIN32 +#include +#endif + +namespace Void::System +{ + +enum class SystemErrorCode : std::int32_t { + invalid_argument = 1, + not_found = 2, + permission_denied = 3, + already_exists = 4, + spawn_failed = 5, + exec_failed = 6, + timed_out = 7, + cancelled = 8, + output_limit = 9, + line_limit = 10, + io_error = 11, + sync_failed = 12, + durability_unknown = 13, + limit_exceeded = 14, + busy = 15, + self_join = 16, + unsupported = 17, + unavailable = 18, + internal = 19, +}; + +[[nodiscard]] constexpr Void::Result::ErrorKind + classify_system_error(SystemErrorCode code) noexcept +{ + switch (code) { + case SystemErrorCode::invalid_argument: + return Void::Result::ErrorKind::invalid_argument; + case SystemErrorCode::not_found: + return Void::Result::ErrorKind::not_found; + case SystemErrorCode::already_exists: + case SystemErrorCode::busy: + case SystemErrorCode::self_join: + return Void::Result::ErrorKind::conflict; + case SystemErrorCode::timed_out: + return Void::Result::ErrorKind::timeout; + case SystemErrorCode::cancelled: + return Void::Result::ErrorKind::cancelled; + case SystemErrorCode::output_limit: + case SystemErrorCode::line_limit: + case SystemErrorCode::limit_exceeded: + return Void::Result::ErrorKind::exhausted; + case SystemErrorCode::unsupported: + return Void::Result::ErrorKind::unsupported; + case SystemErrorCode::unavailable: + return Void::Result::ErrorKind::overloaded; + case SystemErrorCode::permission_denied: + case SystemErrorCode::spawn_failed: + case SystemErrorCode::exec_failed: + case SystemErrorCode::io_error: + case SystemErrorCode::sync_failed: + case SystemErrorCode::durability_unknown: + return Void::Result::ErrorKind::io; + case SystemErrorCode::internal: + return Void::Result::ErrorKind::internal; + } + return Void::Result::ErrorKind::internal; +} + +[[nodiscard]] inline SystemErrorCode + map_errno_to_system_code(int sys_errno) noexcept +{ + switch (sys_errno) { + case ENOENT: + return SystemErrorCode::not_found; + case EACCES: + case EPERM: + case EROFS: + return SystemErrorCode::permission_denied; + case EEXIST: + return SystemErrorCode::already_exists; + case ETIMEDOUT: + return SystemErrorCode::timed_out; + case ECANCELED: + return SystemErrorCode::cancelled; + case EBUSY: + return SystemErrorCode::busy; + case EINVAL: + case ENAMETOOLONG: + case EISDIR: + case ENOTDIR: + return SystemErrorCode::invalid_argument; + case ENOSYS: + case EOPNOTSUPP: +#if defined(ENOTSUP) && (!defined(EOPNOTSUPP) || ENOTSUP != EOPNOTSUPP) + case ENOTSUP: +#endif + return SystemErrorCode::unsupported; + case EAGAIN: +#if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN) + case EWOULDBLOCK: +#endif + return SystemErrorCode::unavailable; + default: + return SystemErrorCode::io_error; + } +} + +[[nodiscard]] inline Void::Result::Error make_system_error( + SystemErrorCode code, std::string_view message, int sys_errno = 0) +{ + std::string detail; + if (sys_errno != 0) { + detail = std::format("{} (errno={}: {})", + message, + sys_errno, + std::strerror(sys_errno)); + } else { + detail.assign(message); + } + std::error_code sys_ec{}; + if (sys_errno != 0) { + sys_ec = std::error_code{sys_errno, std::generic_category()}; + } + return Void::Result::Error{ + classify_system_error(code), + std::move(detail), + Void::Result::ErrorCode{Void::Result::kSystemErrorDomain, + static_cast(code)}, + sys_ec}; +} + +class OwnedFd +{ +public: + OwnedFd() noexcept = default; + explicit OwnedFd(int fd) noexcept : fd_(fd) {} + + ~OwnedFd() noexcept { reset(); } + + OwnedFd(const OwnedFd&) = delete; + OwnedFd& operator=(const OwnedFd&) = delete; + + OwnedFd(OwnedFd&& other) noexcept + : fd_(std::exchange(other.fd_, -1)) + { + } + + OwnedFd& operator=(OwnedFd&& other) noexcept + { + if (this != &other) { + reset(); + fd_ = std::exchange(other.fd_, -1); + } + return *this; + } + + [[nodiscard]] bool valid() const noexcept { return fd_ >= 0; } + [[nodiscard]] explicit operator bool() const noexcept { return valid(); } + [[nodiscard]] int get() const noexcept { return fd_; } + + [[nodiscard]] int release() noexcept { return std::exchange(fd_, -1); } + + void reset(int new_fd = -1) noexcept + { + const int old = std::exchange(fd_, new_fd); +#ifndef _WIN32 + if (old >= 0) { + (void)::close(old); + } +#else + (void)old; +#endif + } + + [[nodiscard]] Void::Result::Result close() noexcept + { + const int old = std::exchange(fd_, -1); + if (old < 0) { + return {}; + } +#ifndef _WIN32 + if (::close(old) != 0) { + const int err = errno; + return std::unexpected{make_system_error( + map_errno_to_system_code(err), "OwnedFd::close failed", err)}; + } +#endif + return {}; + } + +private: + int fd_{-1}; +}; + +} // namespace Void::System diff --git a/src/IO/EpollDriver.cpp b/src/IO/EpollDriver.cpp index 38638ab..c6c982b 100644 --- a/src/IO/EpollDriver.cpp +++ b/src/IO/EpollDriver.cpp @@ -14,6 +14,7 @@ #ifdef __linux__ #include +#include #include #include #include @@ -30,6 +31,55 @@ namespace return std::error_code{err, std::generic_category()}; } +#ifdef __linux__ +[[nodiscard]] ssize_t write_pipe_nosigpipe( + int fd, const void* buf, std::size_t len, int& out_errno) noexcept +{ + sigset_t pending{}; + ::sigemptyset(&pending); + ::sigpending(&pending); + const bool was_pending = (::sigismember(&pending, SIGPIPE) == 1); + + sigset_t block{}; + ::sigemptyset(&block); + ::sigaddset(&block, SIGPIPE); + sigset_t old_mask{}; + const int mask_rc = ::pthread_sigmask(SIG_BLOCK, &block, &old_mask); + const bool was_blocked = + (mask_rc == 0) && (::sigismember(&old_mask, SIGPIPE) == 1); + + ssize_t n = -1; + out_errno = 0; + for (;;) { + n = ::write(fd, buf, len); + if (n < 0) { + out_errno = errno; + if (out_errno == EINTR) { + continue; + } + } + break; + } + + if (n < 0 && out_errno == EPIPE && !was_pending && !was_blocked) { + const struct timespec zero_wait{0, 0}; + for (;;) { + if (::sigtimedwait(&block, nullptr, &zero_wait) >= 0) { + break; + } + if (errno != EINTR) { + break; + } + } + } + + if (mask_rc == 0 && !was_blocked) { + (void)::pthread_sigmask(SIG_SETMASK, &old_mask, nullptr); + } + return n; +} +#endif + void dispatch_tickets(std::vector& tickets) { for (auto& t : tickets) { @@ -1503,6 +1553,10 @@ private: continue; } if (saved_errno == ENOTSOCK) { +#ifdef __linux__ + n = write_pipe_nosigpipe( + fd, op->write_ptr, to_write, saved_errno); +#else n = ::write(fd, op->write_ptr, to_write); if (n < 0) { saved_errno = errno; @@ -1510,6 +1564,7 @@ private: continue; } } +#endif } } break; diff --git a/src/IPC/Codec.cpp b/src/IPC/Codec.cpp new file mode 100644 index 0000000..0b4d3a8 --- /dev/null +++ b/src/IPC/Codec.cpp @@ -0,0 +1,602 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::IPC +{ + +namespace +{ + +constexpr std::array kMagicBytes{ + std::byte{'V'}, std::byte{'D'}, std::byte{'I'}, std::byte{'P'}}; + +[[nodiscard]] bool is_valid_frame_type(std::uint8_t raw) noexcept +{ + return raw >= static_cast(FrameType::hello) && + raw <= static_cast(FrameType::goaway); +} + +[[nodiscard]] bool is_valid_error_code(std::int32_t raw) noexcept +{ + return raw >= static_cast(IpcErrorCode::invalid_argument) && + raw <= static_cast(IpcErrorCode::internal); +} + +} // namespace + +QuotaPermit::~QuotaPermit() noexcept { reset(); } + +QuotaPermit::QuotaPermit(QuotaPermit&& other) noexcept + : quota_(std::move(other.quota_)), + bytes_(std::exchange(other.bytes_, 0)) +{ +} + +QuotaPermit& QuotaPermit::operator=(QuotaPermit&& other) noexcept +{ + if (this != &other) { + reset(); + quota_ = std::move(other.quota_); + bytes_ = std::exchange(other.bytes_, 0); + } + return *this; +} + +void QuotaPermit::reset() noexcept +{ + const std::size_t rel = std::exchange(bytes_, 0); + if (rel > 0) { + if (auto q = quota_.lock()) { + q->release(rel); + } + } + quota_.reset(); +} + +BufferQuota::BufferQuota(std::size_t capacity_bytes) : capacity_(capacity_bytes) +{ +} + +std::shared_ptr BufferQuota::create(std::size_t capacity_bytes) +{ + return std::make_shared(capacity_bytes); +} + +Void::Result::Result + BufferQuota::reserve(std::size_t bytes) +{ + std::lock_guard lk{mu_}; + if (bytes > capacity_ || used_ > capacity_ - bytes) { + return std::unexpected{make_ipc_error( + IpcErrorCode::quota_exceeded, + std::format( + "IPC buffer quota exceeded (requested {}, used {}/{})", + bytes, + used_, + capacity_))}; + } + used_ += bytes; + QuotaPermit permit; + permit.quota_ = weak_from_this(); + permit.bytes_ = bytes; + return permit; +} + +void BufferQuota::release(std::size_t bytes) noexcept +{ + std::lock_guard lk{mu_}; + used_ = (used_ >= bytes) ? (used_ - bytes) : 0; +} + +std::size_t BufferQuota::used() const noexcept +{ + std::lock_guard lk{mu_}; + return used_; +} + +Void::Result::Result + validate_frame_header(const FrameHeader& header, const IpcLimits& limits) +{ + if (header.version != kWireVersion) { + return std::unexpected{make_ipc_error( + IpcErrorCode::unsupported_version, + std::format("Unsupported IPC wire version {}", header.version))}; + } + if (header.flags != 0) { + return std::unexpected{make_ipc_error( + IpcErrorCode::corrupt_frame, + std::format("Unsupported non-zero IPC flags {:#x}", header.flags))}; + } + if (!is_valid_frame_type(static_cast(header.type))) { + return std::unexpected{make_ipc_error( + IpcErrorCode::corrupt_frame, + std::format( + "Unknown IPC frame type {}", + static_cast(header.type)))}; + } + if (header.stream_id != 0) { + return std::unexpected{make_ipc_error( + IpcErrorCode::corrupt_frame, + std::format( + "IPC V1 requires stream_id == 0 (got {})", header.stream_id))}; + } + if (header.payload_len > limits.max_frame_payload) { + return std::unexpected{make_ipc_error( + IpcErrorCode::frame_too_large, + std::format( + "IPC frame payload_len {} exceeds max_frame_payload {}", + header.payload_len, + limits.max_frame_payload))}; + } + if (header.type == FrameType::hello && + header.payload_len > limits.max_hello_bytes) { + return std::unexpected{make_ipc_error( + IpcErrorCode::frame_too_large, + std::format( + "IPC hello payload_len {} exceeds max_hello_bytes {}", + header.payload_len, + limits.max_hello_bytes))}; + } + + switch (header.type) { + case FrameType::request: + case FrameType::response: + case FrameType::cancel: + if (header.request_id == 0) { + return std::unexpected{make_ipc_error( + IpcErrorCode::corrupt_frame, + "IPC request/response/cancel frame requires nonzero request_id")}; + } + break; + case FrameType::hello: + case FrameType::one_way: + case FrameType::goaway: + if (header.request_id != 0) { + return std::unexpected{make_ipc_error( + IpcErrorCode::corrupt_frame, + "IPC hello/one_way/goaway frame requires request_id == 0")}; + } + break; + case FrameType::error: + break; + } + return {}; +} + +Void::Result::Result encode_frame_header( + const FrameHeader& header, std::span out) +{ + Void::Binary::Writer w{out}; + if (auto r = w.writeBytes(kMagicBytes); !r) { + return std::unexpected{std::move(r.error())}; + } + if (auto r = w.writeBig(header.version); !r) { + return std::unexpected{std::move(r.error())}; + } + const std::uint16_t flags_type = + static_cast((static_cast(header.flags) << 8) | + static_cast(header.type)); + if (auto r = w.writeBig(flags_type); !r) { + return std::unexpected{std::move(r.error())}; + } + if (auto r = w.writeBig(header.payload_len); !r) { + return std::unexpected{std::move(r.error())}; + } + if (auto r = w.writeBig(header.stream_id); !r) { + return std::unexpected{std::move(r.error())}; + } + if (auto r = w.writeBig(header.request_id); !r) { + return std::unexpected{std::move(r.error())}; + } + return {}; +} + +Void::Result::Result + decode_frame_header(std::span in) +{ + Void::Binary::Reader r{in}; + auto magic = r.readBytes(4); + if (!magic || !std::equal(magic->begin(), magic->end(), kMagicBytes.begin())) { + return std::unexpected{make_ipc_error( + IpcErrorCode::corrupt_frame, "Invalid IPC wire magic (expected VDIP)")}; + } + + auto ver = r.read(std::endian::big); + auto flags_type = r.read(std::endian::big); + auto plen = r.read(std::endian::big); + auto sid = r.read(std::endian::big); + auto rid = r.read(std::endian::big); + if (!ver || !flags_type || !plen || !sid || !rid) { + return std::unexpected{make_ipc_error( + IpcErrorCode::corrupt_frame, "Truncated IPC frame header")}; + } + + const auto raw_flags = static_cast((*flags_type >> 8) & 0xffu); + const auto raw_type = static_cast(*flags_type & 0xffu); + if (!is_valid_frame_type(raw_type)) { + return std::unexpected{make_ipc_error( + IpcErrorCode::corrupt_frame, + std::format("Invalid IPC frame type byte {}", raw_type))}; + } + + FrameHeader hdr; + hdr.version = *ver; + hdr.flags = raw_flags; + hdr.type = static_cast(raw_type); + hdr.payload_len = *plen; + hdr.stream_id = *sid; + hdr.request_id = *rid; + return hdr; +} + +Void::Result::Result encode_frame( + const FrameHeader& header, + std::span payload, + const IpcLimits& limits, + std::pmr::memory_resource* mr) +{ + if (payload.size() > std::numeric_limits::max()) { + return std::unexpected{make_ipc_error( + IpcErrorCode::frame_too_large, + "IPC payload exceeds uint32_t length field")}; + } + FrameHeader effective = header; + effective.payload_len = static_cast(payload.size()); + if (auto v = validate_frame_header(effective, limits); !v) { + return std::unexpected{std::move(v.error())}; + } + + std::array hdr_bytes{}; + if (auto e = encode_frame_header(effective, hdr_bytes); !e) { + return std::unexpected{std::move(e.error())}; + } + + Void::Binary::ByteBuffer buf{kFrameHeaderSize + payload.size(), mr}; + if (auto r = buf.reserve(kFrameHeaderSize + payload.size()); !r) { + return std::unexpected{make_ipc_error( + IpcErrorCode::quota_exceeded, r.error().message())}; + } + if (auto r = buf.append(hdr_bytes); !r) { + return std::unexpected{std::move(r.error())}; + } + if (auto r = buf.append(payload); !r) { + return std::unexpected{std::move(r.error())}; + } + return buf.freeze(); +} + +Void::Result::Result + encode_hello(const HelloInfo& info, std::pmr::memory_resource* mr) +{ + if (info.protocol_id.empty() || info.protocol_id.size() > 256) { + return std::unexpected{make_ipc_error( + IpcErrorCode::invalid_argument, + "HelloInfo protocol_id must be 1..256 bytes")}; + } + const std::size_t total = 4 + info.protocol_id.size() + 20; + Void::Binary::ByteBuffer buf{total, mr}; + if (auto r = buf.reserve(total); !r) { + return std::unexpected{std::move(r.error())}; + } + if (auto r = buf.writeBig( + static_cast(info.protocol_id.size())); + !r) { + return std::unexpected{std::move(r.error())}; + } + if (auto r = buf.writeString(info.protocol_id); !r) { + return std::unexpected{std::move(r.error())}; + } + if (auto r = buf.writeBig(info.protocol_version); !r) { + return std::unexpected{std::move(r.error())}; + } + if (auto r = buf.writeBig(info.capabilities); !r) { + return std::unexpected{std::move(r.error())}; + } + if (auto r = buf.writeBig(info.max_frame_payload); !r) { + return std::unexpected{std::move(r.error())}; + } + if (auto r = buf.writeBig(info.max_inflight_requests); !r) { + return std::unexpected{std::move(r.error())}; + } + if (auto r = buf.writeBig(info.max_active_handlers); !r) { + return std::unexpected{std::move(r.error())}; + } + return buf.freeze(); +} + +Void::Result::Result decode_hello( + std::span payload, std::size_t max_bytes) +{ + if (payload.size() > max_bytes) { + return std::unexpected{make_ipc_error( + IpcErrorCode::frame_too_large, + "Hello payload exceeds max_hello_bytes")}; + } + Void::Binary::Reader r{payload}; + auto pid_len = r.read(std::endian::big); + if (!pid_len || *pid_len == 0 || *pid_len > 256) { + return std::unexpected{make_ipc_error( + IpcErrorCode::handshake_failed, "Invalid hello protocol_id length")}; + } + auto pid_bytes = r.readBytes(*pid_len); + auto pver = r.read(std::endian::big); + auto caps = r.read(std::endian::big); + auto max_frame = r.read(std::endian::big); + auto max_inf = r.read(std::endian::big); + auto max_hdl = r.read(std::endian::big); + if (!pid_bytes || !pver || !caps || !max_frame || !max_inf || !max_hdl || + !r.empty()) { + return std::unexpected{make_ipc_error( + IpcErrorCode::handshake_failed, "Malformed IPC hello payload")}; + } + if (*max_frame == 0 || *max_inf == 0 || *max_hdl == 0) { + return std::unexpected{make_ipc_error( + IpcErrorCode::handshake_failed, + "Hello limits must be strictly positive")}; + } + + HelloInfo out; + out.protocol_id.assign( + reinterpret_cast(pid_bytes->data()), pid_bytes->size()); + out.protocol_version = *pver; + out.capabilities = *caps; + out.max_frame_payload = *max_frame; + out.max_inflight_requests = *max_inf; + out.max_active_handlers = *max_hdl; + return out; +} + +Void::Result::Result + encode_error_payload(IpcErrorCode code, + std::string_view message, + std::pmr::memory_resource* mr) +{ + const std::string_view bounded = + message.substr(0, std::min(message.size(), 512)); + const std::size_t total = 8 + bounded.size(); + Void::Binary::ByteBuffer buf{total, mr}; + if (auto r = buf.reserve(total); !r) { + return std::unexpected{std::move(r.error())}; + } + (void)buf.writeBig(static_cast(code)); + (void)buf.writeBig( + static_cast(bounded.size())); + (void)buf.writeString(bounded); + return buf.freeze(); +} + +Void::Result::Result, Void::Result::Error> + decode_error_payload(std::span payload) +{ + Void::Binary::Reader r{payload}; + auto raw_code = r.read(std::endian::big); + auto mlen = r.read(std::endian::big); + if (!raw_code || !mlen || *mlen > r.remaining()) { + return std::unexpected{make_ipc_error( + IpcErrorCode::corrupt_frame, "Malformed IPC error payload")}; + } + auto msg_bytes = r.readBytes(*mlen); + if (!msg_bytes || !r.empty()) { + return std::unexpected{make_ipc_error( + IpcErrorCode::corrupt_frame, "Truncated IPC error payload")}; + } + const auto code = is_valid_error_code(*raw_code) + ? static_cast(*raw_code) + : IpcErrorCode::peer_error; + std::string msg{reinterpret_cast(msg_bytes->data()), + msg_bytes->size()}; + return std::pair{code, std::move(msg)}; +} + +Void::Result::Result + encode_goaway_payload(IpcErrorCode code, + std::uint64_t last_request_id, + std::string_view reason, + std::pmr::memory_resource* mr) +{ + const std::string_view bounded = + reason.substr(0, std::min(reason.size(), 512)); + const std::size_t total = 16 + bounded.size(); + Void::Binary::ByteBuffer buf{total, mr}; + if (auto r = buf.reserve(total); !r) { + return std::unexpected{std::move(r.error())}; + } + (void)buf.writeBig(static_cast(code)); + (void)buf.writeBig(last_request_id); + (void)buf.writeBig( + static_cast(bounded.size())); + (void)buf.writeString(bounded); + return buf.freeze(); +} + +Void::Result::Result< + std::tuple, + Void::Result::Error> + decode_goaway_payload(std::span payload) +{ + Void::Binary::Reader r{payload}; + auto raw_code = r.read(std::endian::big); + auto last_id = r.read(std::endian::big); + auto rlen = r.read(std::endian::big); + if (!raw_code || !last_id || !rlen || *rlen > r.remaining()) { + return std::unexpected{make_ipc_error( + IpcErrorCode::corrupt_frame, "Malformed IPC goaway payload")}; + } + auto msg_bytes = r.readBytes(*rlen); + if (!msg_bytes || !r.empty()) { + return std::unexpected{make_ipc_error( + IpcErrorCode::corrupt_frame, "Truncated IPC goaway payload")}; + } + const auto code = is_valid_error_code(*raw_code) + ? static_cast(*raw_code) + : IpcErrorCode::closed; + std::string reason{reinterpret_cast(msg_bytes->data()), + msg_bytes->size()}; + return std::tuple{ + code, *last_id, std::move(reason)}; +} + +FrameDecoder::FrameDecoder(IpcLimits limits, + std::shared_ptr global_quota, + std::shared_ptr session_quota, + std::pmr::memory_resource* mr) + : limits_(limits), + global_quota_(std::move(global_quota)), + session_quota_(std::move(session_quota)), + mr_(mr ? mr : std::pmr::get_default_resource()) +{ +} + +void FrameDecoder::reset_frame_state() noexcept +{ + header_len_ = 0; + has_header_ = false; + current_header_ = FrameHeader{}; + current_global_permit_.reset(); + current_session_permit_.reset(); + payload_buf_.reset(); + payload_written_ = 0; + state_ = State::reading_header; +} + +Void::Result::Result, Void::Result::Error> + FrameDecoder::feed(std::span chunk) +{ + if (state_ == State::failed) { + return std::unexpected{make_ipc_error( + IpcErrorCode::corrupt_frame, + "FrameDecoder is poisoned after prior frame error")}; + } + + std::vector frames; + std::size_t off = 0; + + while (off < chunk.size()) { + if (state_ == State::reading_header) { + const std::size_t need = kFrameHeaderSize - header_len_; + const std::size_t take = std::min(need, chunk.size() - off); + std::memcpy(header_buf_.data() + header_len_, + chunk.data() + off, + take); + header_len_ += take; + off += take; + + if (header_len_ < kFrameHeaderSize) { + break; + } + + auto hdr_res = decode_frame_header(header_buf_); + if (!hdr_res.has_value()) { + state_ = State::failed; + reset_frame_state(); + state_ = State::failed; + return std::unexpected{std::move(hdr_res.error())}; + } + if (auto v = validate_frame_header(*hdr_res, limits_); !v.has_value()) { + state_ = State::failed; + reset_frame_state(); + state_ = State::failed; + return std::unexpected{std::move(v.error())}; + } + + const std::size_t quota_cost = frame_quota_cost(hdr_res->payload_len); + if (quota_cost > limits_.max_recv_buffer_bytes) { + reset_frame_state(); + state_ = State::failed; + return std::unexpected{make_ipc_error( + IpcErrorCode::quota_exceeded, + "IPC frame exceeds max_recv_buffer_bytes")}; + } + + // Reserve global + per-session permits BEFORE allocating payload buffer! + QuotaPermit g_perm; + QuotaPermit s_perm; + if (global_quota_) { + auto gr = global_quota_->reserve(quota_cost); + if (!gr.has_value()) { + reset_frame_state(); + state_ = State::failed; + return std::unexpected{std::move(gr.error())}; + } + g_perm = std::move(*gr); + } + if (session_quota_) { + auto sr = session_quota_->reserve(quota_cost); + if (!sr.has_value()) { + g_perm.reset(); + reset_frame_state(); + state_ = State::failed; + return std::unexpected{std::move(sr.error())}; + } + s_perm = std::move(*sr); + } + + current_header_ = *hdr_res; + current_global_permit_ = std::move(g_perm); + current_session_permit_ = std::move(s_perm); + has_header_ = true; + + if (current_header_.payload_len == 0) { + DecodedFrame df; + df.header = current_header_; + df.global_permit = std::move(current_global_permit_); + df.session_permit = std::move(current_session_permit_); + frames.push_back(std::move(df)); + reset_frame_state(); + continue; + } + + payload_buf_.emplace(current_header_.payload_len, mr_); + if (auto rr = payload_buf_->reserve(current_header_.payload_len); + !rr.has_value()) { + reset_frame_state(); + state_ = State::failed; + return std::unexpected{make_ipc_error( + IpcErrorCode::quota_exceeded, rr.error().message())}; + } + payload_written_ = 0; + state_ = State::reading_payload; + } + + if (state_ == State::reading_payload) { + const std::size_t rem_payload = + current_header_.payload_len - payload_written_; + const std::size_t take = std::min(rem_payload, chunk.size() - off); + if (auto ar = payload_buf_->append(chunk.subspan(off, take)); + !ar.has_value()) { + reset_frame_state(); + state_ = State::failed; + return std::unexpected{std::move(ar.error())}; + } + payload_written_ += take; + off += take; + + if (payload_written_ == current_header_.payload_len) { + DecodedFrame df; + df.header = current_header_; + df.payload = payload_buf_->freeze(); + df.global_permit = std::move(current_global_permit_); + df.session_permit = std::move(current_session_permit_); + frames.push_back(std::move(df)); + reset_frame_state(); + } + } + } + + return frames; +} + +} // namespace Void::IPC diff --git a/src/IPC/Session.cpp b/src/IPC/Session.cpp new file mode 100644 index 0000000..ae59e7c --- /dev/null +++ b/src/IPC/Session.cpp @@ -0,0 +1,1550 @@ +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::IPC +{ + +namespace +{ + +thread_local const void* t_active_session_state = nullptr; + +struct SessionCallbackGuard { + const void* prev{nullptr}; + explicit SessionCallbackGuard(const void* cur) noexcept + : prev(t_active_session_state) + { + t_active_session_state = cur; + } + ~SessionCallbackGuard() noexcept { t_active_session_state = prev; } +}; + +struct ControlItem { + FrameType type{FrameType::cancel}; + std::uint64_t request_id{0}; + Void::Binary::FrozenBytes encoded{}; +}; + +struct OutboundItem { + FrameType type{FrameType::request}; + std::uint64_t request_id{0}; + Void::Binary::FrozenBytes encoded{}; +}; + +struct CallEntry; + +struct CallStopForwarder { + std::weak_ptr state{}; + std::uint64_t request_id{0}; + void operator()() const noexcept; +}; + +struct CallEntry { + std::uint64_t request_id{0}; + std::shared_ptr> op{}; + std::optional deadline{}; + bool queued{false}; + bool sent_to_wire{false}; + CallFailure failure{}; + // Last member: guarantees stop callback finishes before CallEntry tears down. + std::optional> stop_cb{}; +}; + +} // namespace + +struct Session::State : public std::enable_shared_from_this { + Void::IO::Driver& driver; + Void::Async::Executor& executor; + DuplexTransport transport; + IpcLimits limits; + const Void::Time::MonotonicClock& clock; + std::shared_ptr global_quota; + std::shared_ptr session_quota; + FrameDecoder decoder; + Void::Resilience::TokenBucket rate_limiter; + + Void::Async::TaskScope io_scope; + Void::Async::TaskScope handler_scope; + + mutable std::mutex mu{}; + std::condition_variable timer_cv{}; + bool stop_timer_thread{false}; + std::thread timer_thread{}; + + bool loops_started{false}; + bool closing{false}; + bool closed{false}; + bool transport_closed{false}; + bool peer_goaway{false}; + bool id_exhausted{false}; + + bool handshake_started{false}; + bool handshake_done{false}; + bool peer_hello_received{false}; + HelloInfo local_hello{}; + HelloInfo peer_hello{}; + HelloInfo negotiated{}; + std::optional handshake_deadline{}; + std::shared_ptr> handshake_op{}; + + RequestHandler on_request{}; + OneWayHandler on_one_way{}; + + std::deque control_queue{}; + std::size_t control_queued_bytes{0}; + std::deque data_queue{}; + std::size_t outbound_queued_bytes{0}; + + std::shared_ptr> writer_wake_op{}; + std::vector>> + drain_waiters{}; + + std::uint64_t next_request_id{1}; + std::unordered_map> inflight_calls{}; + std::unordered_map active_handlers{}; + + std::deque tombstone_fifo{}; + std::unordered_set tombstone_set{}; + + SessionStats stats{}; + + State(Void::IO::Driver& d, + Void::Async::Executor& ex, + DuplexTransport tr, + IpcLimits lim, + const Void::Time::MonotonicClock& clk, + std::shared_ptr gq, + std::shared_ptr sq, + Void::Resilience::TokenBucket rl) + : driver(d), + executor(ex), + transport(std::move(tr)), + limits(lim), + clock(clk), + global_quota(std::move(gq)), + session_quota(std::move(sq)), + decoder(lim, global_quota, session_quota), + rate_limiter(std::move(rl)), + io_scope(ex, Void::Async::TaskScopeOptions::unlimited(), clk), + handler_scope(ex, Void::Async::TaskScopeOptions::unlimited(), clk) + { + negotiated.max_frame_payload = static_cast( + std::min(limits.max_frame_payload, + std::numeric_limits::max())); + negotiated.max_inflight_requests = static_cast( + std::min(limits.max_inflight_requests, + std::numeric_limits::max())); + negotiated.max_active_handlers = static_cast( + std::min(limits.max_active_handlers, + std::numeric_limits::max())); + } + + ~State() noexcept { shutdown_sync(); } + + void start_timer_thread_locked() + { + if (timer_thread.joinable()) { + return; + } + timer_thread = std::thread([this] { run_timer_loop(); }); + } + + void shutdown_sync() noexcept + { + std::thread tt; + std::vector tickets; + { + std::lock_guard lk{mu}; + closing = true; + closed = true; + stop_timer_thread = true; + timer_cv.notify_all(); + tt = std::move(timer_thread); + collect_fault_all_locked( + IpcErrorCode::closed, "IPC session destroyed", tickets); + if (writer_wake_op) { + auto wake = std::exchange(writer_wake_op, nullptr); + if (auto t = wake->try_commit_value(); t.has_value()) { + tickets.push_back(std::move(*t)); + } + if (auto r = wake->release_backend_ref(); r.has_value()) { + tickets.push_back(std::move(*r)); + } + } + } + for (auto& t : tickets) { + t.dispatch(); + } + if (tt.joinable()) { + tt.join(); + } + io_scope.request_stop(); + handler_scope.request_stop(); + } + + void record_tombstone_locked(std::uint64_t req_id) + { + if (req_id == 0 || limits.max_tombstones == 0) { + return; + } + if (tombstone_set.contains(req_id)) { + return; + } + while (tombstone_fifo.size() >= limits.max_tombstones) { + const auto old = tombstone_fifo.front(); + tombstone_fifo.pop_front(); + tombstone_set.erase(old); + } + tombstone_fifo.push_back(req_id); + tombstone_set.insert(req_id); + } + + void wake_writer_locked(std::vector& tickets) + { + if (writer_wake_op) { + auto wake = std::exchange(writer_wake_op, nullptr); + if (auto t = wake->try_commit_value(); t.has_value()) { + tickets.push_back(std::move(*t)); + } + if (auto r = wake->release_backend_ref(); r.has_value()) { + tickets.push_back(std::move(*r)); + } + } + } + + void check_drain_locked(std::vector& tickets) + { + if (closing && !drain_waiters.empty() && inflight_calls.empty() && + control_queue.empty() && data_queue.empty()) { + auto waiters = std::move(drain_waiters); + drain_waiters.clear(); + for (auto& w : waiters) { + if (auto t = w->try_commit_value(); t.has_value()) { + tickets.push_back(std::move(*t)); + } + if (auto r = w->release_backend_ref(); r.has_value()) { + tickets.push_back(std::move(*r)); + } + } + } + } + + [[nodiscard]] bool enqueue_control_locked( + FrameType type, + std::uint64_t request_id, + Void::Binary::FrozenBytes encoded, + std::vector& tickets) + { + if (type == FrameType::cancel && request_id != 0) { + for (const auto& existing : control_queue) { + if (existing.type == FrameType::cancel && + existing.request_id == request_id) { + ++stats.cancels_coalesced; + return true; + } + } + } + + const std::size_t sz = encoded.size(); + if (control_queue.size() >= limits.control_lane_max_frames || + sz > limits.control_lane_max_bytes || + control_queued_bytes > limits.control_lane_max_bytes - sz) { + return false; + } + control_queued_bytes += sz; + control_queue.push_back(ControlItem{type, request_id, std::move(encoded)}); + wake_writer_locked(tickets); + return true; + } + + [[nodiscard]] Void::Result::Result + enqueue_data_locked(FrameType type, + std::uint64_t request_id, + Void::Binary::FrozenBytes encoded, + std::vector& tickets) + { + const std::size_t sz = encoded.size(); + if (data_queue.size() >= limits.max_outbound_frames || + sz > limits.max_outbound_bytes || + outbound_queued_bytes > limits.max_outbound_bytes - sz) { + return std::unexpected{make_ipc_error( + IpcErrorCode::overloaded, + "IPC session outbound data queue capacity reached")}; + } + outbound_queued_bytes += sz; + data_queue.push_back(OutboundItem{type, request_id, std::move(encoded)}); + wake_writer_locked(tickets); + return {}; + } + + void collect_fault_all_locked( + IpcErrorCode code, + std::string_view reason, + std::vector& tickets) + { + transport_closed = true; + if (handshake_op) { + auto hop = std::exchange(handshake_op, nullptr); + if (auto t = hop->try_commit_error(make_ipc_error(code, reason)); + t.has_value()) { + tickets.push_back(std::move(*t)); + } + if (auto r = hop->release_backend_ref(); r.has_value()) { + tickets.push_back(std::move(*r)); + } + } + auto calls = std::move(inflight_calls); + inflight_calls.clear(); + data_queue.clear(); + outbound_queued_bytes = 0; + control_queue.clear(); + control_queued_bytes = 0; + + for (auto& [id, entry] : calls) { + const bool unknown = entry->sent_to_wire; + entry->failure = CallFailure{ + make_ipc_error(code, reason), + unknown ? EffectStatus::unknown : EffectStatus::not_sent, + unknown}; + record_tombstone_locked(id); + if (auto t = entry->op->try_commit_error(entry->failure.error); + t.has_value()) { + tickets.push_back(std::move(*t)); + } + if (auto r = entry->op->release_backend_ref(); r.has_value()) { + tickets.push_back(std::move(*r)); + } + } + + for (auto& [id, ss] : active_handlers) { + (void)id; + ss.request_stop(); + } + wake_writer_locked(tickets); + check_drain_locked(tickets); + } + + void cancel_or_timeout_call(std::uint64_t request_id, + IpcErrorCode code, + std::string_view msg) + { + std::vector tickets; + Void::Binary::FrozenBytes cancel_frame; + bool send_cancel = false; + { + std::lock_guard lk{mu}; + auto it = inflight_calls.find(request_id); + if (it == inflight_calls.end()) { + return; + } + auto entry = std::move(it->second); + inflight_calls.erase(it); + + // If still queued in data_queue and not sent yet, try erasing before send. + bool removed_unsent = false; + if (!entry->sent_to_wire) { + for (auto dit = data_queue.begin(); dit != data_queue.end(); + ++dit) { + if (dit->type == FrameType::request && + dit->request_id == request_id) { + outbound_queued_bytes = + (outbound_queued_bytes >= dit->encoded.size()) + ? (outbound_queued_bytes - dit->encoded.size()) + : 0; + data_queue.erase(dit); + removed_unsent = true; + break; + } + } + } + + const bool may_have_exec = entry->sent_to_wire || !removed_unsent; + entry->failure = CallFailure{ + make_ipc_error(code, msg), + may_have_exec ? EffectStatus::unknown : EffectStatus::not_sent, + may_have_exec}; + record_tombstone_locked(request_id); + + if (may_have_exec && !transport_closed && !closed) { + auto enc = encode_frame( + FrameHeader{.version = kWireVersion, + .flags = 0, + .type = FrameType::cancel, + .payload_len = 0, + .stream_id = 0, + .request_id = request_id}, + {}, + limits); + if (enc.has_value()) { + cancel_frame = std::move(*enc); + send_cancel = true; + } + } + if (send_cancel) { + (void)enqueue_control_locked( + FrameType::cancel, + request_id, + std::move(cancel_frame), + tickets); + } + + if (auto t = entry->op->try_commit_error(entry->failure.error); + t.has_value()) { + tickets.push_back(std::move(*t)); + } + if (auto r = entry->op->release_backend_ref(); r.has_value()) { + tickets.push_back(std::move(*r)); + } + check_drain_locked(tickets); + } + for (auto& t : tickets) { + t.dispatch(); + } + } + + void run_timer_loop() + { + for (;;) { + std::vector expired_ids; + std::shared_ptr> expired_hs; + std::vector tickets; + { + std::unique_lock lk{mu}; + auto has_deadlines = [this]() -> bool { + if (handshake_op && handshake_deadline.has_value()) { + return true; + } + for (const auto& [id, e] : inflight_calls) { + (void)id; + if (e->deadline.has_value()) { + return true; + } + } + return false; + }; + + while (!stop_timer_thread && !has_deadlines()) { + timer_cv.wait(lk, [this, &has_deadlines] { + return stop_timer_thread || has_deadlines(); + }); + } + if (stop_timer_thread) { + return; + } + + const auto now = clock.now(); + if (handshake_op && handshake_deadline.has_value() && + now >= *handshake_deadline) { + expired_hs = std::exchange(handshake_op, nullptr); + } + for (const auto& [id, e] : inflight_calls) { + if (e->deadline.has_value() && now >= *e->deadline) { + expired_ids.push_back(id); + } + } + if (expired_hs) { + if (auto t = expired_hs->try_commit_error(make_ipc_error( + IpcErrorCode::timed_out, + "IPC handshake timed out")); + t.has_value()) { + tickets.push_back(std::move(*t)); + } + if (auto r = expired_hs->release_backend_ref(); + r.has_value()) { + tickets.push_back(std::move(*r)); + } + } + } + for (auto& t : tickets) { + t.dispatch(); + } + for (const auto id : expired_ids) { + cancel_or_timeout_call( + id, IpcErrorCode::timed_out, "IPC request deadline expired"); + } + + std::unique_lock lk{mu}; + if (stop_timer_thread) { + return; + } + timer_cv.wait_for(lk, std::chrono::milliseconds{5}, [this] { + return stop_timer_thread; + }); + } + } + + static void ensure_loops_started(const std::shared_ptr& self); +}; + +void CallStopForwarder::operator()() const noexcept +{ + if (auto p = state.lock()) { + p->cancel_or_timeout_call( + request_id, IpcErrorCode::cancelled, "IPC request cancelled"); + } +} + +namespace +{ + +[[nodiscard]] Void::Coro::Task + run_request_handler_task(std::shared_ptr st, + std::uint64_t request_id, + Void::Binary::FrozenBytes payload, + std::stop_token cancel, + RequestHandler handler) +{ + Void::Result::Result res{ + std::unexpected{make_ipc_error(IpcErrorCode::internal, "unset")}}; + try { + std::optional>> + inner; + { + SessionCallbackGuard guard{st.get()}; + inner.emplace(handler(std::move(payload), cancel)); + } + res = co_await std::move(*inner); + } catch (const std::exception& ex) { + res = std::unexpected{make_ipc_error( + IpcErrorCode::internal, + std::format("IPC request handler threw: {}", ex.what()))}; + } catch (...) { + res = std::unexpected{make_ipc_error( + IpcErrorCode::internal, "IPC request handler threw unknown exception")}; + } + + std::vector tickets; + { + std::lock_guard lk{st->mu}; + st->active_handlers.erase(request_id); + if (!st->transport_closed && !st->closed) { + if (res.has_value()) { + auto enc = encode_frame( + FrameHeader{.version = kWireVersion, + .flags = 0, + .type = FrameType::response, + .payload_len = 0, + .stream_id = 0, + .request_id = request_id}, + res->view(), + st->limits); + if (enc.has_value()) { + (void)st->enqueue_data_locked( + FrameType::response, + request_id, + std::move(*enc), + tickets); + } + } else { + const auto ipc_code = + (res.error().code().domain == Void::Result::kIpcErrorDomain) + ? static_cast(res.error().code().value) + : IpcErrorCode::peer_error; + auto err_pay = + encode_error_payload(ipc_code, res.error().message()); + if (err_pay.has_value()) { + auto enc = encode_frame( + FrameHeader{.version = kWireVersion, + .flags = 0, + .type = FrameType::error, + .payload_len = 0, + .stream_id = 0, + .request_id = request_id}, + err_pay->view(), + st->limits); + if (enc.has_value()) { + (void)st->enqueue_data_locked( + FrameType::error, + request_id, + std::move(*enc), + tickets); + } + } + } + } + st->check_drain_locked(tickets); + } + for (auto& t : tickets) { + t.dispatch(); + } +} + +[[nodiscard]] Void::Coro::Task + session_writer_loop(std::shared_ptr st) +{ + for (;;) { + Void::Binary::FrozenBytes frame_to_send; + bool found = false; + std::shared_ptr> wait_op; + { + std::lock_guard lk{st->mu}; + if (!st->control_queue.empty()) { + auto item = std::move(st->control_queue.front()); + st->control_queue.pop_front(); + st->control_queued_bytes = + (st->control_queued_bytes >= item.encoded.size()) + ? (st->control_queued_bytes - item.encoded.size()) + : 0; + frame_to_send = std::move(item.encoded); + found = true; + } else if (!st->data_queue.empty()) { + auto item = std::move(st->data_queue.front()); + st->data_queue.pop_front(); + st->outbound_queued_bytes = + (st->outbound_queued_bytes >= item.encoded.size()) + ? (st->outbound_queued_bytes - item.encoded.size()) + : 0; + if (item.type == FrameType::request && item.request_id != 0) { + auto cit = st->inflight_calls.find(item.request_id); + if (cit != st->inflight_calls.end()) { + cit->second->sent_to_wire = true; + } + } + frame_to_send = std::move(item.encoded); + found = true; + } else { + if (st->closed || st->transport_closed) { + co_return; + } + wait_op = Void::Async::OperationState::create( + Void::Async::OperationOptions{}, + &st->executor, + Void::Async::StopBehavior::notify_only); + wait_op->acquire_backend_ref(); + st->writer_wake_op = wait_op; + } + } + + if (!found) { + (void)co_await wait_op->awaitable(&st->executor); + continue; + } + + Void::Async::OperationOptions write_opts{ + .stop = st->io_scope.stop_token(), + .deadline = st->clock.now() + st->limits.progress_timeout}; + auto wr = co_await Void::IO::write_all( + st->transport.writer_stream(), frame_to_send.view(), write_opts); + if (!wr.has_value()) { + std::vector tickets; + { + std::lock_guard lk{st->mu}; + st->collect_fault_all_locked( + IpcErrorCode::transport_lost, + wr.error().error.message(), + tickets); + } + for (auto& t : tickets) { + t.dispatch(); + } + co_return; + } + + std::vector drain_tickets; + { + std::lock_guard lk{st->mu}; + ++st->stats.frames_sent; + st->check_drain_locked(drain_tickets); + } + for (auto& t : drain_tickets) { + t.dispatch(); + } + } +} + +void handle_decoded_frame(std::shared_ptr& st, + DecodedFrame frame) +{ + std::vector tickets; + OneWayHandler one_way_cb; + Void::Binary::FrozenBytes one_way_payload; + + RequestHandler req_cb; + std::uint64_t req_id_for_handler = 0; + Void::Binary::FrozenBytes req_payload; + std::stop_token handler_stop; + + { + std::lock_guard lk{st->mu}; + ++st->stats.frames_received; + + switch (frame.header.type) { + case FrameType::hello: { + auto hres = + decode_hello(frame.payload.view(), st->limits.max_hello_bytes); + if (!hres.has_value()) { + if (st->handshake_op) { + auto hop = std::exchange(st->handshake_op, nullptr); + if (auto t = hop->try_commit_error(std::move(hres.error())); + t.has_value()) { + tickets.push_back(std::move(*t)); + } + if (auto r = hop->release_backend_ref(); r.has_value()) { + tickets.push_back(std::move(*r)); + } + } + break; + } + + if (st->handshake_started && + (hres->protocol_id != st->local_hello.protocol_id || + hres->protocol_version != st->local_hello.protocol_version)) { + if (st->handshake_op) { + auto hop = std::exchange(st->handshake_op, nullptr); + if (auto t = hop->try_commit_error(make_ipc_error( + IpcErrorCode::handshake_failed, + "IPC hello protocol mismatch")); + t.has_value()) { + tickets.push_back(std::move(*t)); + } + if (auto r = hop->release_backend_ref(); r.has_value()) { + tickets.push_back(std::move(*r)); + } + } + break; + } + + HelloInfo neg = *hres; + if (st->handshake_started) { + neg.max_frame_payload = std::min( + st->local_hello.max_frame_payload, hres->max_frame_payload); + neg.max_inflight_requests = std::min( + st->local_hello.max_inflight_requests, + hres->max_inflight_requests); + neg.max_active_handlers = std::min( + st->local_hello.max_active_handlers, + hres->max_active_handlers); + neg.capabilities = + st->local_hello.capabilities & hres->capabilities; + } + st->limits.max_frame_payload = std::min( + st->limits.max_frame_payload, neg.max_frame_payload); + st->limits.max_inflight_requests = std::min( + st->limits.max_inflight_requests, neg.max_inflight_requests); + st->limits.max_active_handlers = std::min( + st->limits.max_active_handlers, neg.max_active_handlers); + st->peer_hello = *hres; + st->peer_hello_received = true; + st->negotiated = neg; + if (st->handshake_started) { + st->handshake_done = true; + } + + if (st->handshake_op) { + auto hop = std::exchange(st->handshake_op, nullptr); + if (auto t = hop->try_commit_value(neg); t.has_value()) { + tickets.push_back(std::move(*t)); + } + if (auto r = hop->release_backend_ref(); r.has_value()) { + tickets.push_back(std::move(*r)); + } + } + break; + } + + case FrameType::request: { + ++st->stats.requests_received; + const std::uint64_t rid = frame.header.request_id; + if (st->closing || st->closed || st->peer_goaway || !st->on_request) { + auto ep = encode_error_payload( + IpcErrorCode::closed, "Session not accepting requests"); + if (ep.has_value()) { + auto ef = encode_frame( + FrameHeader{.version = kWireVersion, + .flags = 0, + .type = FrameType::error, + .payload_len = 0, + .stream_id = 0, + .request_id = rid}, + ep->view(), + st->limits); + if (ef.has_value()) { + (void)st->enqueue_control_locked( + FrameType::error, rid, std::move(*ef), tickets); + } + } + break; + } + + const auto rate_adm = + st->rate_limiter.try_acquire_at_checked(st->clock.now(), 1.0); + if (!rate_adm.has_value() || !rate_adm->allowed) { + auto ep = encode_error_payload( + IpcErrorCode::rate_limited, "Per-peer rate limit exceeded"); + if (ep.has_value()) { + auto ef = encode_frame( + FrameHeader{.version = kWireVersion, + .flags = 0, + .type = FrameType::error, + .payload_len = 0, + .stream_id = 0, + .request_id = rid}, + ep->view(), + st->limits); + if (ef.has_value()) { + (void)st->enqueue_control_locked( + FrameType::error, rid, std::move(*ef), tickets); + } + } + break; + } + + if (st->active_handlers.size() >= st->limits.max_active_handlers || + st->active_handlers.contains(rid)) { + auto ep = encode_error_payload( + IpcErrorCode::overloaded, + "Session active handler limit reached"); + if (ep.has_value()) { + auto ef = encode_frame( + FrameHeader{.version = kWireVersion, + .flags = 0, + .type = FrameType::error, + .payload_len = 0, + .stream_id = 0, + .request_id = rid}, + ep->view(), + st->limits); + if (ef.has_value()) { + (void)st->enqueue_control_locked( + FrameType::error, rid, std::move(*ef), tickets); + } + } + break; + } + + std::stop_source handler_src; + handler_stop = handler_src.get_token(); + st->active_handlers.emplace(rid, std::move(handler_src)); + req_cb = st->on_request; + req_id_for_handler = rid; + req_payload = std::move(frame.payload); + break; + } + + case FrameType::response: { + const std::uint64_t rid = frame.header.request_id; + auto it = st->inflight_calls.find(rid); + if (it == st->inflight_calls.end()) { + if (st->tombstone_set.contains(rid)) { + ++st->stats.late_responses_dropped; + } + break; + } + auto entry = std::move(it->second); + st->inflight_calls.erase(it); + st->record_tombstone_locked(rid); + if (auto t = entry->op->try_commit_value(std::move(frame.payload)); + t.has_value()) { + tickets.push_back(std::move(*t)); + } + if (auto r = entry->op->release_backend_ref(); r.has_value()) { + tickets.push_back(std::move(*r)); + } + st->check_drain_locked(tickets); + break; + } + + case FrameType::error: { + const std::uint64_t rid = frame.header.request_id; + if (rid == 0) { + break; + } + auto it = st->inflight_calls.find(rid); + if (it == st->inflight_calls.end()) { + if (st->tombstone_set.contains(rid)) { + ++st->stats.late_responses_dropped; + } + break; + } + auto entry = std::move(it->second); + st->inflight_calls.erase(it); + st->record_tombstone_locked(rid); + + IpcErrorCode ecode = IpcErrorCode::peer_error; + std::string emsg = "Peer returned IPC error"; + if (auto dec = decode_error_payload(frame.payload.view()); + dec.has_value()) { + ecode = dec->first; + emsg = std::move(dec->second); + } + const bool may_have = + !(ecode == IpcErrorCode::overloaded || + ecode == IpcErrorCode::rate_limited); + entry->failure = CallFailure{ + make_ipc_error(ecode, emsg), + may_have ? EffectStatus::unknown : EffectStatus::not_sent, + may_have}; + if (auto t = entry->op->try_commit_error(entry->failure.error); + t.has_value()) { + tickets.push_back(std::move(*t)); + } + if (auto r = entry->op->release_backend_ref(); r.has_value()) { + tickets.push_back(std::move(*r)); + } + st->check_drain_locked(tickets); + break; + } + + case FrameType::cancel: { + const std::uint64_t rid = frame.header.request_id; + if (auto it = st->active_handlers.find(rid); + it != st->active_handlers.end()) { + it->second.request_stop(); + } + break; + } + + case FrameType::one_way: { + if (!st->closing && !st->closed && st->on_one_way) { + one_way_cb = st->on_one_way; + one_way_payload = std::move(frame.payload); + } + break; + } + + case FrameType::goaway: { + st->peer_goaway = true; + break; + } + } + } + + for (auto& t : tickets) { + t.dispatch(); + } + + if (one_way_cb) { + SessionCallbackGuard guard{st.get()}; + one_way_cb(std::move(one_way_payload)); + } + + if (req_cb) { + (void)st->handler_scope.spawn(run_request_handler_task( + st, + req_id_for_handler, + std::move(req_payload), + handler_stop, + std::move(req_cb))); + } +} + +[[nodiscard]] Void::Coro::Task + session_reader_loop(std::shared_ptr st) +{ + auto lease_res = st->driver.allocate_buffer(64ULL * 1024ULL); + if (!lease_res.has_value()) { + std::vector tickets; + { + std::lock_guard lk{st->mu}; + st->collect_fault_all_locked( + IpcErrorCode::quota_exceeded, + lease_res.error().message(), + tickets); + } + for (auto& t : tickets) { + t.dispatch(); + } + co_return; + } + auto lease = std::move(*lease_res); + + for (;;) { + Void::Async::OperationOptions read_opts; + read_opts.stop = st->io_scope.stop_token(); + { + std::lock_guard lk{st->mu}; + if (st->closed || st->transport_closed) { + co_return; + } + if (!st->handshake_done && st->handshake_deadline.has_value()) { + read_opts.deadline = st->handshake_deadline; + } else if (st->decoder.in_mid_frame()) { + read_opts.deadline = + st->clock.now() + st->limits.progress_timeout; + } else { + read_opts.deadline = + st->clock.now() + st->limits.idle_timeout; + } + } + + auto rd = co_await st->transport.reader_stream().read_some_owned( + lease, read_opts); + if (!rd.has_value()) { + std::vector tickets; + { + std::lock_guard lk{st->mu}; + const auto ipc_code = + (rd.error().kind() == Void::Result::ErrorKind::timeout) + ? IpcErrorCode::timed_out + : IpcErrorCode::transport_lost; + st->collect_fault_all_locked( + ipc_code, rd.error().message(), tickets); + } + for (auto& t : tickets) { + t.dispatch(); + } + co_return; + } + + if (rd->bytes > 0) { + auto fed = st->decoder.feed(lease.readable().subspan(0, rd->bytes)); + if (!fed.has_value()) { + std::vector tickets; + { + std::lock_guard lk{st->mu}; + st->collect_fault_all_locked( + IpcErrorCode::corrupt_frame, + fed.error().message(), + tickets); + } + for (auto& t : tickets) { + t.dispatch(); + } + co_return; + } + for (auto& f : *fed) { + handle_decoded_frame(st, std::move(f)); + } + } + + if (rd->eof) { + std::vector tickets; + { + std::lock_guard lk{st->mu}; + st->collect_fault_all_locked( + IpcErrorCode::transport_lost, + "IPC peer closed transport stream (EOF)", + tickets); + } + for (auto& t : tickets) { + t.dispatch(); + } + co_return; + } + } +} + +} // namespace + +void Session::State::ensure_loops_started(const std::shared_ptr& self) +{ + bool need_spawn = false; + { + std::lock_guard lk{self->mu}; + if (!self->loops_started && !self->closed && !self->transport_closed) { + self->loops_started = true; + self->start_timer_thread_locked(); + need_spawn = true; + } + } + if (need_spawn) { + (void)self->io_scope.spawn(session_writer_loop(self)); + (void)self->io_scope.spawn(session_reader_loop(self)); + } +} + +namespace +{ + +[[nodiscard]] Void::Resilience::TokenBucket + make_rate_limiter(const IpcLimits& limits, + const Void::Time::MonotonicClock& clock) +{ + auto res = Void::Resilience::TokenBucket::create( + Void::Resilience::BucketConfig{ + .capacity = std::max(1.0, limits.rate_limit_burst), + .refill_per_second = std::max(1e-6, limits.rate_limit_per_sec), + .metric_name = "ipc_peer_rate", + }, + clock); + if (res.has_value()) { + return std::move(*res); + } + return Void::Resilience::TokenBucket{128.0, 1000.0}; +} + +} // namespace + +Session::Session(Void::IO::Driver& driver, + Void::Async::Executor& executor, + DuplexTransport transport, + IpcLimits limits, + const Void::Time::MonotonicClock& clock, + std::shared_ptr global_quota) + : state_(std::make_shared( + driver, + executor, + std::move(transport), + limits, + clock, + global_quota ? std::move(global_quota) + : BufferQuota::create(limits.global_buffer_budget_bytes), + BufferQuota::create(limits.max_recv_buffer_bytes), + make_rate_limiter(limits, clock))) +{ +} + +Session::~Session() noexcept +{ + if (!state_) { + return; + } + state_->shutdown_sync(); + if (!state_->executor.has_background_workers()) { + if (auto* manual = + dynamic_cast(&state_->executor)) { + for (int i = 0; + i < 1000 && (state_->io_scope.active_count() > 0 || + state_->handler_scope.active_count() > 0); + ++i) { + (void)manual->drain(); + (void)state_->driver.poll_once(std::chrono::milliseconds{0}); + (void)manual->drain(); + } + } + } else if (!state_->executor.is_executor_thread()) { + (void)state_->handler_scope.join_blocking(); + (void)state_->io_scope.join_blocking(); + } +} + +Void::Coro::Task> + Session::handshake(HelloInfo local_hello, + Void::Async::OperationOptions options) +{ + if (Void::Async::is_deadline_expired(options, state_->clock)) { + co_return std::unexpected{make_ipc_error( + IpcErrorCode::timed_out, "IPC handshake deadline already expired")}; + } + if (options.stop.stop_requested()) { + co_return std::unexpected{make_ipc_error( + IpcErrorCode::cancelled, "IPC handshake cancelled before start")}; + } + + auto hello_payload = encode_hello(local_hello); + if (!hello_payload.has_value()) { + co_return std::unexpected{std::move(hello_payload.error())}; + } + auto hello_frame = encode_frame( + FrameHeader{.version = kWireVersion, + .flags = 0, + .type = FrameType::hello, + .payload_len = 0, + .stream_id = 0, + .request_id = 0}, + hello_payload->view(), + state_->limits); + if (!hello_frame.has_value()) { + co_return std::unexpected{std::move(hello_frame.error())}; + } + + const auto timeout_tp = state_->clock.now() + state_->limits.handshake_timeout; + const auto effective_deadline = + options.deadline.has_value() + ? std::min(*options.deadline, timeout_tp) + : timeout_tp; + + std::shared_ptr> op; + std::vector tickets; + std::optional immediate_neg; + { + std::lock_guard lk{state_->mu}; + if (state_->closed || state_->transport_closed) { + co_return std::unexpected{make_ipc_error( + IpcErrorCode::closed, "IPC session closed before handshake")}; + } + if (state_->handshake_done) { + co_return state_->negotiated; + } + if (state_->handshake_started) { + co_return std::unexpected{make_ipc_error( + IpcErrorCode::handshake_failed, + "IPC handshake already in progress")}; + } + + state_->handshake_started = true; + state_->local_hello = local_hello; + state_->handshake_deadline = effective_deadline; + + auto qres = state_->enqueue_data_locked( + FrameType::hello, 0, std::move(*hello_frame), tickets); + if (!qres.has_value()) { + co_return std::unexpected{std::move(qres.error())}; + } + + if (state_->peer_hello_received) { + if (state_->peer_hello.protocol_id != local_hello.protocol_id || + state_->peer_hello.protocol_version != + local_hello.protocol_version) { + co_return std::unexpected{make_ipc_error( + IpcErrorCode::handshake_failed, + "IPC hello protocol mismatch")}; + } + HelloInfo neg = state_->peer_hello; + neg.max_frame_payload = std::min( + local_hello.max_frame_payload, neg.max_frame_payload); + neg.max_inflight_requests = std::min( + local_hello.max_inflight_requests, neg.max_inflight_requests); + neg.max_active_handlers = std::min( + local_hello.max_active_handlers, neg.max_active_handlers); + neg.capabilities &= local_hello.capabilities; + state_->limits.max_frame_payload = std::min( + state_->limits.max_frame_payload, neg.max_frame_payload); + state_->limits.max_inflight_requests = std::min( + state_->limits.max_inflight_requests, neg.max_inflight_requests); + state_->limits.max_active_handlers = std::min( + state_->limits.max_active_handlers, neg.max_active_handlers); + state_->negotiated = neg; + state_->handshake_done = true; + immediate_neg = std::move(neg); + } else { + op = Void::Async::OperationState::create( + options, + &state_->executor, + Void::Async::StopBehavior::settle_cancelled); + op->acquire_backend_ref(); + state_->handshake_op = op; + state_->timer_cv.notify_all(); + } + } + + for (auto& t : tickets) { + t.dispatch(); + } + + State::ensure_loops_started(state_); + if (immediate_neg.has_value()) { + co_return std::move(*immediate_neg); + } + co_return co_await op->awaitable(&state_->executor); +} + +Void::Result::Result + Session::start(RequestHandler on_request, OneWayHandler on_one_way) +{ + { + std::lock_guard lk{state_->mu}; + if (state_->closed) { + return std::unexpected{make_ipc_error( + IpcErrorCode::closed, "IPC session already closed")}; + } + state_->on_request = std::move(on_request); + state_->on_one_way = std::move(on_one_way); + } + State::ensure_loops_started(state_); + return {}; +} + +Void::Coro::Task> + Session::request(Void::Binary::FrozenBytes payload, + Void::Async::OperationOptions options) +{ + if (options.stop.stop_requested()) { + co_return std::unexpected{CallFailure{ + make_ipc_error(IpcErrorCode::cancelled, + "IPC request cancelled before send"), + EffectStatus::not_sent, + false}}; + } + if (Void::Async::is_deadline_expired(options, state_->clock)) { + co_return std::unexpected{CallFailure{ + make_ipc_error(IpcErrorCode::timed_out, + "IPC request deadline expired before send"), + EffectStatus::not_sent, + false}}; + } + + std::shared_ptr entry; + std::uint64_t req_id = 0; + std::vector tickets; + bool trigger_id_exhausted_goaway = false; + { + std::lock_guard lk{state_->mu}; + if (state_->closing || state_->closed || state_->peer_goaway || + state_->transport_closed) { + co_return std::unexpected{CallFailure{ + make_ipc_error(IpcErrorCode::closed, + "IPC session is closing or transport is closed"), + EffectStatus::not_sent, + false}}; + } + if (state_->id_exhausted || + state_->next_request_id == std::numeric_limits::max()) { + state_->id_exhausted = true; + trigger_id_exhausted_goaway = true; + } else if (state_->inflight_calls.size() >= + state_->limits.max_inflight_requests) { + co_return std::unexpected{CallFailure{ + make_ipc_error(IpcErrorCode::overloaded, + "IPC max_inflight_requests reached"), + EffectStatus::not_sent, + false}}; + } else { + req_id = state_->next_request_id++; + if (state_->next_request_id == 0) { + state_->id_exhausted = true; + } + auto enc = encode_frame( + FrameHeader{.version = kWireVersion, + .flags = 0, + .type = FrameType::request, + .payload_len = 0, + .stream_id = 0, + .request_id = req_id}, + payload.view(), + state_->limits); + if (!enc.has_value()) { + co_return std::unexpected{CallFailure{ + std::move(enc.error()), EffectStatus::not_sent, false}}; + } + + entry = std::make_shared(); + entry->request_id = req_id; + entry->deadline = options.deadline; + entry->op = + Void::Async::OperationState::create( + Void::Async::OperationOptions{}, + &state_->executor, + Void::Async::StopBehavior::notify_only); + entry->op->acquire_backend_ref(); + + auto qres = state_->enqueue_data_locked( + FrameType::request, req_id, std::move(*enc), tickets); + if (!qres.has_value()) { + co_return std::unexpected{CallFailure{ + std::move(qres.error()), EffectStatus::not_sent, false}}; + } + entry->queued = true; + state_->inflight_calls.emplace(req_id, entry); + ++state_->stats.requests_sent; + if (options.deadline.has_value()) { + state_->timer_cv.notify_all(); + } + } + } + + if (trigger_id_exhausted_goaway) { + (void)send_goaway(IpcErrorCode::id_exhausted, "Request ID space exhausted"); + co_return std::unexpected{CallFailure{ + make_ipc_error(IpcErrorCode::id_exhausted, + "IPC request ID space exhausted; sent goaway"), + EffectStatus::not_sent, + false}}; + } + + if (options.stop.stop_possible()) { + entry->stop_cb.emplace( + options.stop, CallStopForwarder{state_, req_id}); + } + + for (auto& t : tickets) { + t.dispatch(); + } + State::ensure_loops_started(state_); + + auto outcome = co_await entry->op->awaitable(&state_->executor); + if (!outcome.has_value()) { + std::lock_guard lk{state_->mu}; + if (entry->failure.error.message().empty()) { + co_return std::unexpected{CallFailure{ + std::move(outcome.error()), + entry->sent_to_wire ? EffectStatus::unknown + : EffectStatus::not_sent, + entry->sent_to_wire}}; + } + co_return std::unexpected{entry->failure}; + } + co_return std::move(*outcome); +} + +Void::Result::Result + Session::send_one_way(Void::Binary::FrozenBytes payload) +{ + auto enc = encode_frame( + FrameHeader{.version = kWireVersion, + .flags = 0, + .type = FrameType::one_way, + .payload_len = 0, + .stream_id = 0, + .request_id = 0}, + payload.view(), + state_->limits); + if (!enc.has_value()) { + return std::unexpected{std::move(enc.error())}; + } + + std::vector tickets; + { + std::lock_guard lk{state_->mu}; + if (state_->closing || state_->closed || state_->peer_goaway || + state_->transport_closed) { + return std::unexpected{make_ipc_error( + IpcErrorCode::closed, "IPC session closed")}; + } + if (auto q = state_->enqueue_data_locked( + FrameType::one_way, 0, std::move(*enc), tickets); + !q.has_value()) { + return q; + } + } + for (auto& t : tickets) { + t.dispatch(); + } + State::ensure_loops_started(state_); + return {}; +} + +Void::Result::Result + Session::send_goaway(IpcErrorCode code, std::string_view reason) +{ + std::vector tickets; + { + std::lock_guard lk{state_->mu}; + if (state_->closed || state_->transport_closed) { + return {}; + } + const std::uint64_t last_id = + (state_->next_request_id > 1) ? (state_->next_request_id - 1) : 0; + auto gp = encode_goaway_payload(code, last_id, reason); + if (!gp.has_value()) { + return std::unexpected{std::move(gp.error())}; + } + auto gf = encode_frame( + FrameHeader{.version = kWireVersion, + .flags = 0, + .type = FrameType::goaway, + .payload_len = 0, + .stream_id = 0, + .request_id = 0}, + gp->view(), + state_->limits); + if (!gf.has_value()) { + return std::unexpected{std::move(gf.error())}; + } + if (!state_->enqueue_control_locked( + FrameType::goaway, 0, std::move(*gf), tickets)) { + return std::unexpected{make_ipc_error( + IpcErrorCode::overloaded, + "IPC control lane full when sending goaway")}; + } + } + for (auto& t : tickets) { + t.dispatch(); + } + State::ensure_loops_started(state_); + return {}; +} + +Void::Coro::Task> + Session::close_and_join(Void::Async::OperationOptions options) +{ + if (t_active_session_state == state_.get()) { + co_return std::unexpected{make_ipc_error( + IpcErrorCode::self_join, + "Session::close_and_join cannot be called from session handler")}; + } + + (void)send_goaway(IpcErrorCode::closed, "close_and_join"); + + std::shared_ptr> drain_op; + { + std::lock_guard lk{state_->mu}; + state_->closing = true; + if (!state_->inflight_calls.empty() || !state_->control_queue.empty() || + !state_->data_queue.empty()) { + drain_op = Void::Async::OperationState::create( + options, + &state_->executor, + Void::Async::StopBehavior::settle_cancelled); + drain_op->acquire_backend_ref(); + state_->drain_waiters.push_back(drain_op); + } + } + + if (drain_op) { + (void)co_await drain_op->awaitable(&state_->executor); + } + + std::thread tt; + std::vector close_tickets; + { + std::lock_guard lk{state_->mu}; + state_->closed = true; + state_->stop_timer_thread = true; + tt = std::move(state_->timer_thread); + state_->collect_fault_all_locked( + IpcErrorCode::closed, "IPC session closed", close_tickets); + state_->timer_cv.notify_all(); + } + for (auto& t : close_tickets) { + t.dispatch(); + } + if (tt.joinable()) { + tt.join(); + } + + state_->handler_scope.request_stop(); + state_->io_scope.request_stop(); + (void)co_await state_->transport.close_and_join(options); + (void)co_await state_->handler_scope.join(); + (void)co_await state_->io_scope.join(); + co_return {}; +} + +SessionStats Session::stats() const noexcept +{ + std::lock_guard lk{state_->mu}; + SessionStats s = state_->stats; + s.active_inflight = state_->inflight_calls.size(); + s.active_handlers = state_->active_handlers.size(); + s.outbound_queued_bytes = state_->outbound_queued_bytes; + s.control_queued_frames = state_->control_queue.size(); + s.next_request_id = state_->next_request_id; + return s; +} + +HelloInfo Session::negotiated_hello() const +{ + std::lock_guard lk{state_->mu}; + return state_->negotiated; +} + +const PeerCredentials& Session::peer_credentials() const noexcept +{ + return state_->transport.credentials(); +} + +void Session::set_next_request_id_for_test(std::uint64_t next_id) noexcept +{ + std::lock_guard lk{state_->mu}; + state_->next_request_id = next_id; +} + +} // namespace Void::IPC diff --git a/src/IPC/Transport.cpp b/src/IPC/Transport.cpp new file mode 100644 index 0000000..9603b0b --- /dev/null +++ b/src/IPC/Transport.cpp @@ -0,0 +1,673 @@ +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::IPC +{ + +namespace +{ + +[[nodiscard]] IpcErrorCode map_errno_to_ipc(int err) noexcept +{ + switch (err) { + case ENOENT: + return IpcErrorCode::not_found; + case EACCES: + case EPERM: + case ELOOP: + return IpcErrorCode::permission_denied; + case EEXIST: + return IpcErrorCode::already_exists; + case EINVAL: + case ENAMETOOLONG: + case ENOTDIR: + case EISDIR: + return IpcErrorCode::invalid_argument; + case ETIMEDOUT: + return IpcErrorCode::timed_out; + case ECONNREFUSED: + case ECONNRESET: + case EPIPE: + case ENOTCONN: + return IpcErrorCode::transport_lost; + case EAGAIN: +#if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN) + case EWOULDBLOCK: +#endif + return IpcErrorCode::overloaded; + default: + return IpcErrorCode::transport_lost; + } +} + +[[nodiscard]] Void::Result::Result + query_peer_credentials(int fd) +{ + struct ucred cred{}; + socklen_t len = sizeof(cred); + if (::getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &len) != 0) { + const int err = errno; + return std::unexpected{make_ipc_error( + map_errno_to_ipc(err), "Failed to query SO_PEERCRED", err)}; + } + PeerCredentials out; + out.available = true; + out.pid = static_cast(cred.pid); + out.uid = static_cast(cred.uid); + out.gid = static_cast(cred.gid); + return out; +} + +[[nodiscard]] Void::Result::Result + check_peer_policy(const PeerCredentials& creds, const PeerPolicy& policy) +{ + if (!creds.available) { + return std::unexpected{make_ipc_error( + IpcErrorCode::permission_denied, + "Peer credentials unavailable for SO_PEERCRED check")}; + } + if (policy.require_uid_match) { + const unsigned long expected_uid = + policy.set_allowed_uid_to_current_user + ? static_cast(::geteuid()) + : policy.allowed_uid; + if (creds.uid != expected_uid) { + return std::unexpected{make_ipc_error( + IpcErrorCode::permission_denied, + std::format("Peer UID {} denied (expected {})", + creds.uid, + expected_uid))}; + } + } + if (policy.required_gid.has_value() && creds.gid != *policy.required_gid) { + return std::unexpected{make_ipc_error( + IpcErrorCode::permission_denied, + std::format("Peer GID {} denied (expected {})", + creds.gid, + *policy.required_gid))}; + } + return {}; +} + +[[nodiscard]] Void::Result::Result + build_sockaddr(const std::filesystem::path& socket_path, + socklen_t& out_len) +{ + const std::string& raw = socket_path.native(); + if (raw.empty() || raw.find('\0') != std::string::npos) { + return std::unexpected{make_ipc_error( + IpcErrorCode::invalid_argument, + "IPC socket path must be non-empty without NUL bytes")}; + } + sockaddr_un addr{}; + if (raw.size() >= sizeof(addr.sun_path)) { + return std::unexpected{make_ipc_error( + IpcErrorCode::invalid_argument, + std::format("IPC socket path length {} >= sun_path limit ({})", + raw.size(), + sizeof(addr.sun_path)))}; + } + addr.sun_family = AF_UNIX; + std::memcpy(addr.sun_path, raw.data(), raw.size()); + addr.sun_path[raw.size()] = '\0'; + out_len = static_cast( + offsetof(sockaddr_un, sun_path) + raw.size() + 1); + return addr; +} + +[[nodiscard]] bool probe_socket_alive(const sockaddr_un& addr, + socklen_t addr_len, + int& out_errno) noexcept +{ + const int probe = + ::socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); + if (probe < 0) { + out_errno = errno; + return false; + } + const int rc = + ::connect(probe, reinterpret_cast(&addr), addr_len); + out_errno = (rc == 0) ? 0 : errno; + (void)::close(probe); + return rc == 0 || out_errno == EINPROGRESS || out_errno == EAGAIN; +} + +} // namespace + +struct LocalListener::SlotState { + std::size_t max_sessions{128}; + mutable std::mutex mu{}; + std::size_t active{0}; +}; + +namespace +{ +struct ListenerSlotGuard { + std::weak_ptr state; + ~ListenerSlotGuard() noexcept + { + if (auto p = state.lock()) { + std::lock_guard lk{p->mu}; + if (p->active > 0) { + --p->active; + } + } + } +}; +} // namespace + +DuplexTransport::DuplexTransport(Void::IO::ByteStream unified_stream, + PeerCredentials creds) noexcept + : split_(false), + read_stream_(std::move(unified_stream)), + credentials_(creds) +{ +} + +DuplexTransport::DuplexTransport(Void::IO::ByteStream read_stream, + Void::IO::ByteStream write_stream, + PeerCredentials creds) noexcept + : split_(true), + read_stream_(std::move(read_stream)), + write_stream_(std::move(write_stream)), + credentials_(creds) +{ +} + +bool DuplexTransport::valid() const noexcept +{ + return split_ ? (read_stream_.valid() && write_stream_.valid()) + : read_stream_.valid(); +} + +Void::Coro::Task> + DuplexTransport::close_and_join(Void::Async::OperationOptions options) +{ + if (!split_) { + if (read_stream_.valid()) { + auto r = co_await read_stream_.close_and_join(options); + listener_slot_.reset(); + co_return r; + } + listener_slot_.reset(); + co_return {}; + } + + Void::Result::Result first_err; + if (write_stream_.valid()) { + auto w = co_await write_stream_.close_and_join(options); + if (!w.has_value()) { + first_err = std::move(w); + } + } + if (read_stream_.valid()) { + auto r = co_await read_stream_.close_and_join(options); + if (!r.has_value() && first_err.has_value()) { + first_err = std::move(r); + } + } + listener_slot_.reset(); + co_return first_err; +} + +LocalListener::~LocalListener() noexcept { close(); } + +LocalListener::LocalListener(LocalListener&& other) noexcept + : listen_fd_(std::exchange(other.listen_fd_, -1)), + dir_fd_(std::exchange(other.dir_fd_, -1)), + lock_fd_(std::exchange(other.lock_fd_, -1)), + socket_path_(std::move(other.socket_path_)), + socket_name_(std::move(other.socket_name_)), + socket_dev_(std::exchange(other.socket_dev_, 0)), + socket_ino_(std::exchange(other.socket_ino_, 0)), + limits_(other.limits_), + policy_(other.policy_), + slot_state_(std::move(other.slot_state_)) +{ +} + +LocalListener& LocalListener::operator=(LocalListener&& other) noexcept +{ + if (this != &other) { + close(); + listen_fd_ = std::exchange(other.listen_fd_, -1); + dir_fd_ = std::exchange(other.dir_fd_, -1); + lock_fd_ = std::exchange(other.lock_fd_, -1); + socket_path_ = std::move(other.socket_path_); + socket_name_ = std::move(other.socket_name_); + socket_dev_ = std::exchange(other.socket_dev_, 0); + socket_ino_ = std::exchange(other.socket_ino_, 0); + limits_ = other.limits_; + policy_ = other.policy_; + slot_state_ = std::move(other.slot_state_); + } + return *this; +} + +void LocalListener::close() noexcept +{ + if (listen_fd_ >= 0) { + (void)::close(listen_fd_); + listen_fd_ = -1; + } + if (dir_fd_ >= 0 && !socket_name_.empty() && socket_ino_ != 0) { + struct stat st {}; + if (::fstatat(dir_fd_, + socket_name_.c_str(), + &st, + AT_SYMLINK_NOFOLLOW) == 0 && + S_ISSOCK(st.st_mode) && + static_cast(st.st_dev) == socket_dev_ && + static_cast(st.st_ino) == socket_ino_) { + (void)::unlinkat(dir_fd_, socket_name_.c_str(), 0); + } + } + if (dir_fd_ >= 0 && !socket_name_.empty() && lock_fd_ >= 0) { + const std::string lock_name = socket_name_ + ".lock"; + (void)::unlinkat(dir_fd_, lock_name.c_str(), 0); + } + if (lock_fd_ >= 0) { + (void)::close(lock_fd_); + lock_fd_ = -1; + } + if (dir_fd_ >= 0) { + (void)::close(dir_fd_); + dir_fd_ = -1; + } + socket_name_.clear(); + socket_dev_ = 0; + socket_ino_ = 0; +} + +std::size_t LocalListener::active_sessions() const noexcept +{ + if (!slot_state_) { + return 0; + } + std::lock_guard lk{slot_state_->mu}; + return slot_state_->active; +} + +Void::Result::Result LocalListener::listen( + const std::filesystem::path& socket_path, + IpcLimits limits, + PeerPolicy policy) +{ + if (limits.max_sessions == 0 || limits.max_frame_payload == 0) { + return std::unexpected{make_ipc_error( + IpcErrorCode::invalid_argument, + "IpcLimits max_sessions and max_frame_payload must be non-zero")}; + } + + socklen_t addr_len = 0; + auto addr_res = build_sockaddr(socket_path, addr_len); + if (!addr_res.has_value()) { + return std::unexpected{std::move(addr_res.error())}; + } + + const std::string fname = socket_path.filename().string(); + if (fname.empty() || fname == "." || fname == "..") { + return std::unexpected{make_ipc_error( + IpcErrorCode::invalid_argument, + "LocalListener socket path must have a valid filename")}; + } + const std::filesystem::path parent = + socket_path.parent_path().empty() ? std::filesystem::path{"."} + : socket_path.parent_path(); + + const int raw_dir_fd = ::open( + parent.c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC); + if (raw_dir_fd < 0) { + const int err = errno; + return std::unexpected{make_ipc_error( + map_errno_to_ipc(err), + std::format("Cannot safely open IPC socket parent dir '{}'", + parent.string()), + err)}; + } + + LocalListener listener; + listener.dir_fd_ = raw_dir_fd; + listener.socket_path_ = socket_path; + listener.socket_name_ = fname; + listener.limits_ = limits; + listener.policy_ = policy; + + struct stat dir_st {}; + if (::fstat(listener.dir_fd_, &dir_st) != 0) { + const int err = errno; + return std::unexpected{make_ipc_error( + map_errno_to_ipc(err), "Failed to stat IPC socket parent dir", err)}; + } + if (dir_st.st_uid != ::geteuid() || (dir_st.st_mode & 0077) != 0) { + return std::unexpected{make_ipc_error( + IpcErrorCode::permission_denied, + std::format( + "IPC socket parent dir '{}' must be owned by current user with 0700 permissions", + parent.string()))}; + } + + const std::string lock_name = fname + ".lock"; + listener.lock_fd_ = ::openat(listener.dir_fd_, + lock_name.c_str(), + O_CREAT | O_RDWR | O_NOFOLLOW | O_CLOEXEC, + 0600); + if (listener.lock_fd_ < 0) { + const int err = errno; + return std::unexpected{make_ipc_error( + map_errno_to_ipc(err), + "Failed to open IPC startup lock file", + err)}; + } + if (::flock(listener.lock_fd_, LOCK_EX | LOCK_NB) != 0) { + const int err = errno; + (void)::close(listener.lock_fd_); + listener.lock_fd_ = -1; + return std::unexpected{make_ipc_error( + IpcErrorCode::already_exists, + "Another listener holds the startup lock for this socket", + err)}; + } + + struct stat existing_st {}; + if (::fstatat(listener.dir_fd_, + fname.c_str(), + &existing_st, + AT_SYMLINK_NOFOLLOW) == 0) { + if (!S_ISSOCK(existing_st.st_mode) || + existing_st.st_uid != ::geteuid()) { + return std::unexpected{make_ipc_error( + IpcErrorCode::permission_denied, + "Refusing to remove non-socket, symlink, or foreign path at IPC endpoint")}; + } + int probe_err = 0; + if (probe_socket_alive(*addr_res, addr_len, probe_err)) { + return std::unexpected{make_ipc_error( + IpcErrorCode::already_exists, + "IPC socket endpoint is already active")}; + } + if (probe_err != ECONNREFUSED) { + return std::unexpected{make_ipc_error( + IpcErrorCode::permission_denied, + "Failed to confirm stale state before unlinking existing socket", + probe_err)}; + } + if (::unlinkat(listener.dir_fd_, fname.c_str(), 0) != 0) { + const int err = errno; + return std::unexpected{make_ipc_error( + map_errno_to_ipc(err), "Failed to remove stale IPC socket", err)}; + } + } else if (errno != ENOENT) { + const int err = errno; + return std::unexpected{make_ipc_error( + map_errno_to_ipc(err), "Failed to inspect IPC socket path", err)}; + } + + listener.listen_fd_ = + ::socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); + if (listener.listen_fd_ < 0) { + const int err = errno; + return std::unexpected{make_ipc_error( + map_errno_to_ipc(err), "Failed to create AF_UNIX socket", err)}; + } + + if (::bind(listener.listen_fd_, + reinterpret_cast(&*addr_res), + addr_len) != 0) { + const int err = errno; + return std::unexpected{make_ipc_error( + map_errno_to_ipc(err), + std::format("Failed to bind AF_UNIX socket '{}'", + socket_path.string()), + err)}; + } + + struct stat bound_st {}; + if (::fstatat(listener.dir_fd_, + fname.c_str(), + &bound_st, + AT_SYMLINK_NOFOLLOW) != 0 || + !S_ISSOCK(bound_st.st_mode)) { + return std::unexpected{make_ipc_error( + IpcErrorCode::permission_denied, + "Bound IPC endpoint missing or replaced unexpectedly")}; + } + listener.socket_dev_ = static_cast(bound_st.st_dev); + listener.socket_ino_ = static_cast(bound_st.st_ino); + + if (::chmod(socket_path.c_str(), 0600) != 0) { + const int err = errno; + return std::unexpected{make_ipc_error( + map_errno_to_ipc(err), "Failed to set 0600 mode on IPC socket", err)}; + } + + if (::listen(listener.listen_fd_, 128) != 0) { + const int err = errno; + return std::unexpected{make_ipc_error( + map_errno_to_ipc(err), "Failed to listen on AF_UNIX socket", err)}; + } + + listener.slot_state_ = std::make_shared(); + listener.slot_state_->max_sessions = limits.max_sessions; + return listener; +} + +Void::Result::Result, Void::Result::Error> + LocalListener::try_accept(Void::IO::Driver& driver) +{ + if (listen_fd_ < 0 || !slot_state_) { + return std::unexpected{make_ipc_error( + IpcErrorCode::closed, "LocalListener is closed")}; + } + + for (;;) { + const int client_fd = + ::accept4(listen_fd_, nullptr, nullptr, SOCK_NONBLOCK | SOCK_CLOEXEC); + if (client_fd < 0) { + const int err = errno; + if (err == EINTR) { + continue; + } + if (err == EAGAIN || err == EWOULDBLOCK) { + return std::optional{std::nullopt}; + } + return std::unexpected{make_ipc_error( + map_errno_to_ipc(err), "accept4 failed on IPC listener", err)}; + } + + std::shared_ptr slot_guard; + { + std::lock_guard lk{slot_state_->mu}; + if (slot_state_->active >= slot_state_->max_sessions) { + (void)::close(client_fd); + return std::unexpected{make_ipc_error( + IpcErrorCode::overloaded, + std::format("LocalListener max_sessions ({}) reached", + slot_state_->max_sessions))}; + } + ++slot_state_->active; + slot_guard = std::make_shared(slot_state_); + } + + auto creds = query_peer_credentials(client_fd); + if (!creds.has_value()) { + (void)::close(client_fd); + return std::unexpected{std::move(creds.error())}; + } + if (auto auth = check_peer_policy(*creds, policy_); !auth.has_value()) { + (void)::close(client_fd); + return std::unexpected{std::move(auth.error())}; + } + + auto stream = driver.adopt_fd(client_fd); + if (!stream.has_value()) { + (void)::close(client_fd); + return std::unexpected{std::move(stream.error())}; + } + + DuplexTransport transport{std::move(*stream), *creds}; + transport.listener_slot_ = std::move(slot_guard); + return std::optional{std::move(transport)}; + } +} + +Void::Result::Result connect_local( + Void::IO::Driver& driver, + const std::filesystem::path& socket_path, + PeerPolicy policy) +{ + socklen_t addr_len = 0; + auto addr_res = build_sockaddr(socket_path, addr_len); + if (!addr_res.has_value()) { + return std::unexpected{std::move(addr_res.error())}; + } + + struct stat st {}; + if (::lstat(socket_path.c_str(), &st) != 0) { + const int err = errno; + return std::unexpected{make_ipc_error( + map_errno_to_ipc(err), + std::format("Cannot stat IPC socket '{}'", socket_path.string()), + err)}; + } + if (S_ISLNK(st.st_mode) || !S_ISSOCK(st.st_mode)) { + return std::unexpected{make_ipc_error( + IpcErrorCode::permission_denied, + "IPC connect target must be a real AF_UNIX socket, not a symlink")}; + } + + const int fd = + ::socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); + if (fd < 0) { + const int err = errno; + return std::unexpected{make_ipc_error( + map_errno_to_ipc(err), "Failed to create AF_UNIX client socket", err)}; + } + + for (;;) { + if (::connect(fd, reinterpret_cast(&*addr_res), addr_len) == + 0) { + break; + } + const int err = errno; + if (err == EINTR) { + continue; + } + if (err == EINPROGRESS) { + struct pollfd pfd{fd, POLLOUT, 0}; + const int prc = ::poll(&pfd, 1, 5000); + if (prc <= 0) { + (void)::close(fd); + return std::unexpected{make_ipc_error( + IpcErrorCode::timed_out, + "Timed out connecting to AF_UNIX socket")}; + } + int so_err = 0; + socklen_t slen = sizeof(so_err); + if (::getsockopt(fd, SOL_SOCKET, SO_ERROR, &so_err, &slen) != 0 || + so_err != 0) { + (void)::close(fd); + return std::unexpected{make_ipc_error( + map_errno_to_ipc(so_err != 0 ? so_err : errno), + "AF_UNIX connect failed", + so_err != 0 ? so_err : errno)}; + } + break; + } + (void)::close(fd); + return std::unexpected{make_ipc_error( + map_errno_to_ipc(err), + std::format("Failed connecting to '{}'", socket_path.string()), + err)}; + } + + auto creds = query_peer_credentials(fd); + if (!creds.has_value()) { + (void)::close(fd); + return std::unexpected{std::move(creds.error())}; + } + if (auto auth = check_peer_policy(*creds, policy); !auth.has_value()) { + (void)::close(fd); + return std::unexpected{std::move(auth.error())}; + } + + auto stream = driver.adopt_fd(fd); + if (!stream.has_value()) { + (void)::close(fd); + return std::unexpected{std::move(stream.error())}; + } + return DuplexTransport{std::move(*stream), *creds}; +} + +Void::Result::Result + adopt_pipe_pair(Void::IO::Driver& driver, int read_fd, int write_fd) +{ + if (read_fd < 0 || write_fd < 0 || read_fd == write_fd) { + return std::unexpected{make_ipc_error( + IpcErrorCode::invalid_argument, + "adopt_pipe_pair requires distinct valid read_fd and write_fd")}; + } + if (::fcntl(read_fd, F_GETFD) == -1 || ::fcntl(write_fd, F_GETFD) == -1) { + const int err = errno; + return std::unexpected{make_ipc_error( + IpcErrorCode::invalid_argument, + "adopt_pipe_pair received closed or invalid descriptor", + err)}; + } + + auto rstream = driver.adopt_fd(read_fd); + if (!rstream.has_value()) { + return std::unexpected{std::move(rstream.error())}; + } + auto wstream = driver.adopt_fd(write_fd); + if (!wstream.has_value()) { + // read_fd already owned by rstream (EpollDriver closes on destroy). + return std::unexpected{std::move(wstream.error())}; + } + + return DuplexTransport{std::move(*rstream), + std::move(*wstream), + PeerCredentials{.available = false}}; +} + +Void::Result::Result, + Void::Result::Error> + create_socket_pair_transports(Void::IO::Driver& driver) +{ + auto pair = driver.create_socket_pair(); + if (!pair.has_value()) { + return std::unexpected{std::move(pair.error())}; + } + PeerCredentials self_creds; + self_creds.available = true; + self_creds.pid = static_cast(::getpid()); + self_creds.uid = static_cast(::geteuid()); + self_creds.gid = static_cast(::getegid()); + + return std::pair{ + DuplexTransport{std::move(pair->first), self_creds}, + DuplexTransport{std::move(pair->second), self_creds}}; +} + +} // namespace Void::IPC diff --git a/src/IPC/module.cmake b/src/IPC/module.cmake new file mode 100644 index 0000000..1211b24 --- /dev/null +++ b/src/IPC/module.cmake @@ -0,0 +1,3 @@ +void_add_module(IPC + INTERNAL_DEPS Core Functional Memory Time Binary Async IO Resilience +) diff --git a/src/System/Process.cpp b/src/System/Process.cpp index d367714..5136fbd 100644 --- a/src/System/Process.cpp +++ b/src/System/Process.cpp @@ -1,350 +1,1647 @@ -#include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include +#include +#include +#include +#include +#include +#include +#include +#include #ifdef _WIN32 namespace Void::Process { - Void::Result::Result - run(const std::filesystem::path&, - std::vector, - std::string_view, - std::chrono::milliseconds) - { - return Void::Result::fail("Process::run: not implemented on Windows"); + +Child::Child(long long, + long long, + bool, + Void::System::OwnedFd, + Void::System::OwnedFd, + Void::System::OwnedFd, + std::chrono::milliseconds) noexcept +{ } - Void::Result::Result - run_streaming(const std::filesystem::path&, - std::vector, - const StreamCallbacks&, - std::string_view, - std::chrono::milliseconds) - { - return Void::Result::fail( - "Process::run_streaming: not implemented on Windows"); - } +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; } +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 - shell(std::string_view, std::chrono::milliseconds) - { - return Void::Result::fail("Process::shell: not implemented on Windows"); - } +Void::Result::Result 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 + 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, 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 + 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 spawn(const SpawnOptions&) +{ + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::unsupported, + "Process::spawn: not implemented on Windows")}; +} + +Void::Result::Result + 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 run( + const std::filesystem::path&, + std::vector, + std::string_view, + std::chrono::milliseconds) +{ + return Void::Result::fail("Process::run: not implemented on Windows"); +} + +Void::Result::Result run_streaming( + const std::filesystem::path&, + std::vector, + const StreamCallbacks&, + std::string_view, + std::chrono::milliseconds) +{ + return Void::Result::fail( + "Process::run_streaming: not implemented on Windows"); +} + +Void::Result::Result + shell(std::string_view, std::chrono::milliseconds) +{ + return Void::Result::fail("Process::shell: not implemented on Windows"); +} + +Void::Result::Result + reexec(const std::filesystem::path&, const std::vector&) +{ + return Void::Result::fail("Process::reexec: not implemented on Windows"); +} + +Void::Result::Result reexec( + const std::filesystem::path&, const std::vector&, bool) +{ + return Void::Result::fail("Process::reexec: not implemented on Windows"); +} - Void::Result::Result - reexec(const std::filesystem::path&, - const std::vector&) - { - return Void::Result::fail("Process::reexec: not implemented on Windows"); - } } // namespace Void::Process #else // POSIX -#include -#include -#include -#include - +#include #include #include +#include +#include +#include #include #include +extern char** environ; + namespace Void::Process { - namespace - { - // Read into buf until EAGAIN (no more data right now) or EOF. - // Returns true on EOF, false on EAGAIN. - bool drain(int fd, std::string& buf) - { - char tmp[4096]; - for (;;) { - ssize_t n = ::read(fd, tmp, sizeof(tmp)); - if (n > 0) { - buf.append(tmp, static_cast(n)); - } else if (n == 0) { - return true; // EOF - } else { - if (errno == EINTR) { - continue; - } - // EAGAIN / EWOULDBLOCK: no data right now - return false; - } - } - } +namespace +{ - void set_nonblock(int fd) - { - int flags = ::fcntl(fd, F_GETFL, 0); - if (flags >= 0) { - ::fcntl(fd, F_SETFL, flags | O_NONBLOCK); - } - } +struct ChildFailureMsg { + int phase{0}; + int err{0}; +}; - // Close an fd if it is >= 0, then set it to -1. - void safe_close(int& fd) - { - if (fd >= 0) { - ::close(fd); - fd = -1; - } - } +[[nodiscard]] bool checked_add_size(std::size_t a, + std::size_t b, + std::size_t& out) noexcept +{ + if (a > std::numeric_limits::max() - b) { + return false; + } + out = a + b; + return true; +} - // Emit newly-completed lines from `buf` (from offset `off`), advancing - // `off`. When `flush` is set, any trailing partial line is emitted too. - void emit_lines(const std::string& buf, std::size_t& off, - const std::function& fn, - bool flush) - { - if (!fn) { - off = buf.size(); - return; - } - std::size_t nl; - while ((nl = buf.find('\n', off)) != std::string::npos) { - std::size_t len = nl - off; - if (len > 0 && buf[off + len - 1] == '\r') { - --len; // strip CR of a CRLF - } - fn(std::string_view{buf.data() + off, len}); - off = nl + 1; - } - if (flush && off < buf.size()) { - fn(std::string_view{buf.data() + off, buf.size() - off}); - off = buf.size(); - } - } - } // namespace +[[nodiscard]] std::string sanitize_diag(std::string_view text) +{ + std::string out; + out.reserve(std::min(text.size(), 256)); + for (char ch : text) { + if (out.size() >= 256) { + break; + } + const auto uc = static_cast(ch); + if (uc < 0x20 || uc == 0x7f) { + out.push_back(' '); + } else { + out.push_back(ch); + } + } + return out; +} - namespace - { - Void::Result::Result - run_impl(const std::filesystem::path& executable, - std::vector args, std::string_view stdin_data, - std::chrono::milliseconds timeout, - const StreamCallbacks* cb) - { - // [0] = read end, [1] = write end - int stdin_pipe[2] = {-1, -1}; - int stdout_pipe[2] = {-1, -1}; - int stderr_pipe[2] = {-1, -1}; +[[nodiscard]] bool create_cloexec_pipe(int fds[2]) noexcept +{ + fds[0] = -1; + fds[1] = -1; +#if defined(__linux__) + return ::pipe2(fds, O_CLOEXEC) == 0; +#else + if (::pipe(fds) != 0) { + return false; + } + for (int i = 0; i < 2; ++i) { + const int fl = ::fcntl(fds[i], F_GETFD, 0); + if (fl < 0 || ::fcntl(fds[i], F_SETFD, fl | FD_CLOEXEC) != 0) { + const int err = errno; + (void)::close(fds[0]); + (void)::close(fds[1]); + fds[0] = -1; + fds[1] = -1; + errno = err; + return false; + } + } + return true; +#endif +} - if (::pipe(stdin_pipe) != 0 || ::pipe(stdout_pipe) != 0 || - ::pipe(stderr_pipe) != 0) { - safe_close(stdin_pipe[0]); - safe_close(stdin_pipe[1]); - safe_close(stdout_pipe[0]); - safe_close(stdout_pipe[1]); - safe_close(stderr_pipe[0]); - safe_close(stderr_pipe[1]); - return Void::Result::fail(std::format( - "Process::run: pipe() failed: {}", std::strerror(errno))); - } +[[nodiscard]] bool set_nonblock(int fd) noexcept +{ + const int flags = ::fcntl(fd, F_GETFL, 0); + if (flags < 0) { + return false; + } + return ::fcntl(fd, F_SETFL, flags | O_NONBLOCK) == 0; +} - Void::Log::debug("Process", "run: '{}'", executable.string()); +[[nodiscard]] ssize_t write_pipe_nosigpipe(int fd, + const void* buf, + std::size_t len, + int& out_errno) noexcept +{ + sigset_t pending{}; + ::sigemptyset(&pending); + ::sigpending(&pending); + const bool was_pending = (::sigismember(&pending, SIGPIPE) == 1); - std::vector argv; - argv.push_back(executable.c_str()); - for (const auto& a : args) { - argv.push_back(a.c_str()); - } - argv.push_back(nullptr); + sigset_t block{}; + ::sigemptyset(&block); + ::sigaddset(&block, SIGPIPE); + sigset_t old_mask{}; + const int mask_rc = ::pthread_sigmask(SIG_BLOCK, &block, &old_mask); + const bool was_blocked = + (mask_rc == 0) && (::sigismember(&old_mask, SIGPIPE) == 1); - pid_t pid = ::fork(); - if (pid < 0) { - safe_close(stdin_pipe[0]); - safe_close(stdin_pipe[1]); - safe_close(stdout_pipe[0]); - safe_close(stdout_pipe[1]); - safe_close(stderr_pipe[0]); - safe_close(stderr_pipe[1]); - return Void::Result::fail(std::format( - "Process::run: fork() failed: {}", std::strerror(errno))); - } + ssize_t n = -1; + out_errno = 0; + for (;;) { + n = ::write(fd, buf, len); + if (n < 0) { + out_errno = errno; + if (out_errno == EINTR) { + continue; + } + } + break; + } - if (pid == 0) { - // Child process - ::dup2(stdin_pipe[0], STDIN_FILENO); - ::dup2(stdout_pipe[1], STDOUT_FILENO); - ::dup2(stderr_pipe[1], STDERR_FILENO); - ::close(stdin_pipe[0]); - ::close(stdin_pipe[1]); - ::close(stdout_pipe[0]); - ::close(stdout_pipe[1]); - ::close(stderr_pipe[0]); - ::close(stderr_pipe[1]); - ::execvp( - executable.c_str(), - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) - const_cast(argv.data())); - // execvp only returns on error; 127 is the POSIX convention - ::_exit(127); - } + if (n < 0 && out_errno == EPIPE && !was_pending && !was_blocked) { + const struct timespec zero_wait{0, 0}; + for (;;) { + if (::sigtimedwait(&block, nullptr, &zero_wait) >= 0) { + break; + } + if (errno != EINTR) { + break; + } + } + } - // Parent: close child-side ends - safe_close(stdin_pipe[0]); - safe_close(stdout_pipe[1]); - safe_close(stderr_pipe[1]); + if (mask_rc == 0 && !was_blocked) { + (void)::pthread_sigmask(SIG_SETMASK, &old_mask, nullptr); + } + return n; +} - // Write stdin and close immediately so the child sees EOF - if (!stdin_data.empty()) { - const char* p = stdin_data.data(); - std::size_t remaining = stdin_data.size(); - while (remaining > 0) { - ssize_t n = ::write(stdin_pipe[1], p, remaining); - if (n < 0) { - if (errno == EINTR) { - continue; - } - break; // child likely closed stdin; ignore - } - p += static_cast(n); - remaining -= static_cast(n); - } - } - safe_close(stdin_pipe[1]); +[[nodiscard]] bool parse_decimal_fd(const char* name, int& out_fd) noexcept +{ + if (name == nullptr || name[0] == '\0') { + return false; + } + long long v = 0; + for (const char* p = name; *p != '\0'; ++p) { + if (*p < '0' || *p > '9') { + return false; + } + if (v > (std::numeric_limits::max() - (*p - '0')) / 10) { + return false; + } + v = v * 10 + (*p - '0'); + } + out_fd = static_cast(v); + return true; +} - set_nonblock(stdout_pipe[0]); - set_nonblock(stderr_pipe[0]); +#if defined(__linux__) +struct LinuxDirent64 { + std::uint64_t d_ino; + std::int64_t d_off; + std::uint16_t d_reclen; + std::uint8_t d_type; + char d_name[1]; +}; +#endif - Output output; - bool out_done = false; - bool err_done = false; - std::size_t out_emitted = 0; - std::size_t err_emitted = 0; +// Strictly async-signal-safe close of inherited fds >= 3 except keep_fd (-1 if none). +void close_fds_from_except(int keep_fd) noexcept +{ +#if defined(__linux__) && defined(SYS_close_range) + if (keep_fd < 3) { + if (::syscall(SYS_close_range, 3U, ~0U, 0U) == 0) { + return; + } + } else { + const long r1 = (keep_fd == 3) + ? 0 + : ::syscall(SYS_close_range, + 3U, + static_cast(keep_fd - 1), + 0U); + const long r2 = ::syscall(SYS_close_range, + static_cast(keep_fd + 1), + ~0U, + 0U); + if (r1 == 0 && r2 == 0) { + return; + } + } +#endif - const bool has_timeout = timeout.count() > 0; - const auto deadline = - std::chrono::steady_clock::now() + - (has_timeout ? timeout : std::chrono::milliseconds{30'000}); +#if defined(__linux__) && defined(SYS_getdents64) + for (int pass = 0; pass < 32; ++pass) { + const int dir_fd = + ::open("/proc/self/fd", O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (dir_fd < 0) { + break; + } + bool closed_any = false; + std::array buf{}; + for (;;) { + const long nread = + ::syscall(SYS_getdents64, dir_fd, buf.data(), buf.size()); + if (nread <= 0) { + break; + } + std::array to_close{}; + std::size_t count = 0; + for (long pos = 0; pos < nread;) { + const auto* ent = + reinterpret_cast(buf.data() + pos); + int fd_num = -1; + if (parse_decimal_fd(ent->d_name, fd_num) && fd_num >= 3 && + fd_num != dir_fd && fd_num != keep_fd) { + if (count < to_close.size()) { + to_close[count++] = fd_num; + } + } + pos += ent->d_reclen; + } + for (std::size_t i = 0; i < count; ++i) { + (void)::close(to_close[i]); + closed_any = true; + } + } + (void)::close(dir_fd); + if (!closed_any) { + return; + } + } +#endif - while (!out_done || !err_done) { - struct pollfd pfds[2]; - int nfds = 0; - if (!out_done) { - pfds[nfds++] = {stdout_pipe[0], POLLIN, 0}; - } - if (!err_done) { - pfds[nfds++] = {stderr_pipe[0], POLLIN, 0}; - } + long max_fd = ::sysconf(_SC_OPEN_MAX); + if (max_fd <= 0 || max_fd > 4096) { + max_fd = 1024; + } + for (int fd = 3; fd < static_cast(max_fd); ++fd) { + if (fd != keep_fd) { + (void)::close(fd); + } + } +} - auto left_ms = - std::chrono::duration_cast( - deadline - std::chrono::steady_clock::now()) - .count(); - if (left_ms <= 0) { - ::kill(pid, SIGTERM); - break; - } +void reset_child_signals() noexcept +{ + sigset_t empty{}; + ::sigemptyset(&empty); + (void)::pthread_sigmask(SIG_SETMASK, &empty, nullptr); - int ret = ::poll(pfds, static_cast(nfds), - static_cast(left_ms)); - if (ret < 0) { - if (errno == EINTR) { - continue; - } - break; - } - if (ret == 0) { - // Wall-clock timeout expired - ::kill(pid, SIGTERM); - break; - } + struct sigaction sa{}; + sa.sa_handler = SIG_DFL; + ::sigemptyset(&sa.sa_mask); + sa.sa_flags = 0; + const int limit = std::min(NSIG, 32); + for (int sig = 1; sig < limit; ++sig) { + if (sig == SIGKILL || sig == SIGSTOP) { + continue; + } + (void)::sigaction(sig, &sa, nullptr); + } +} - for (int i = 0; i < nfds; ++i) { - if ((pfds[i].revents & (POLLIN | POLLHUP | POLLERR)) == 0) { - continue; - } - const bool is_out = (pfds[i].fd == stdout_pipe[0]); - bool& done = is_out ? out_done : err_done; - std::string& buf = is_out ? output.out : output.err; - bool eof = drain(pfds[i].fd, buf); - if (cb) { - emit_lines(buf, is_out ? out_emitted : err_emitted, - is_out ? cb->on_stdout : cb->on_stderr, - /*flush=*/false); - } - // POLLHUP means the write end was closed; no more data will - // arrive - if (eof || (pfds[i].revents & (POLLHUP | POLLERR))) { - done = true; - } - } - } +[[nodiscard]] bool redirect_child_fd(int& src_fd, int target_fd) noexcept +{ + if (src_fd < 0) { + return true; + } + if (src_fd == target_fd) { + const int fl = ::fcntl(target_fd, F_GETFD, 0); + if (fl < 0) { + return false; + } + if ((fl & FD_CLOEXEC) != 0 && + ::fcntl(target_fd, F_SETFD, fl & ~FD_CLOEXEC) != 0) { + return false; + } + return true; + } + while (::dup2(src_fd, target_fd) < 0) { + if (errno == EINTR) { + continue; + } + return false; + } + (void)::close(src_fd); + src_fd = -1; + return true; +} - if (cb) { - emit_lines(output.out, out_emitted, cb->on_stdout, - /*flush=*/true); - emit_lines(output.err, err_emitted, cb->on_stderr, - /*flush=*/true); - } +void write_child_failure(int err_fd, int phase, int err) noexcept +{ + ChildFailureMsg msg{phase, err}; + const auto* ptr = reinterpret_cast(&msg); + std::size_t off = 0; + while (off < sizeof(msg)) { + const ssize_t n = ::write(err_fd, ptr + off, sizeof(msg) - off); + if (n < 0) { + if (errno == EINTR) { + continue; + } + break; + } + if (n == 0) { + break; + } + off += static_cast(n); + } +} - safe_close(stdout_pipe[0]); - safe_close(stderr_pipe[0]); +[[nodiscard]] ExitStatus decode_wait_status(int raw) noexcept +{ + ExitStatus st; + st.raw_status = raw; + if (WIFEXITED(raw)) { + st.exited = true; + st.code = WEXITSTATUS(raw); + } else if (WIFSIGNALED(raw)) { + st.exited = false; + st.signal = WTERMSIG(raw); + st.code = -1; + } + return st; +} - int status = 0; - ::waitpid(pid, &status, 0); - output.exit_code = WIFEXITED(status) ? WEXITSTATUS(status) : -1; +[[nodiscard]] bool signal_target(pid_t pid, + pid_t pgid, + bool owns_group, + int sig, + int& out_errno) noexcept +{ + if (owns_group && pgid > 0) { + if (::kill(-pgid, sig) == 0) { + return true; + } + out_errno = errno; + if (out_errno != ESRCH && out_errno != EPERM) { + return false; + } + } + if (::kill(pid, sig) == 0) { + return true; + } + out_errno = errno; + return false; +} - Void::Log::debug("Process", "run: '{}' exited {}", - executable.string(), output.exit_code); +[[nodiscard]] std::optional + find_env_value(const std::vector& env_strings, + std::string_view key) +{ + for (const auto& entry : env_strings) { + const auto eq = entry.find('='); + if (eq == key.size() && + std::string_view{entry}.substr(0, eq) == key) { + return entry.substr(eq + 1); + } + } + return std::nullopt; +} - return Void::Result::ok(std::move(output)); - } - } // namespace +[[nodiscard]] Void::Result::Result, Void::Result::Error> + build_environment_strings(const EnvironmentPolicy& policy) +{ + std::vector base; + auto validate_key = [](std::string_view k) -> bool { + return !k.empty() && k.find('=') == std::string_view::npos && + k.find('\0') == std::string_view::npos; + }; - Void::Result::Result - run(const std::filesystem::path& executable, - std::vector args, std::string_view stdin_data, - std::chrono::milliseconds timeout) - { - return run_impl(executable, std::move(args), stdin_data, timeout, - nullptr); - } + std::set> unset_set; + for (const auto& k : policy.unset_keys) { + if (!validate_key(k)) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "SpawnOptions: invalid unset environment variable key")}; + } + unset_set.insert(k); + } - Void::Result::Result run_streaming( - const std::filesystem::path& executable, std::vector args, - const StreamCallbacks& callbacks, std::string_view stdin_data, - std::chrono::milliseconds timeout) - { - return run_impl(executable, std::move(args), stdin_data, timeout, - &callbacks); - } + std::set> allow_set; + if (policy.mode == EnvMode::allowlist) { + for (const auto& k : policy.allowlist) { + if (!validate_key(k)) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "SpawnOptions: invalid allowlist environment key")}; + } + allow_set.insert(k); + } + } - Void::Result::Result - shell(std::string_view command, std::chrono::milliseconds timeout) - { - return run("/bin/sh", {"-c", std::string{command}}, {}, timeout); - } + std::unordered_map env_map; + std::vector key_order; - Void::Result::Result - reexec(const std::filesystem::path& executable, - const std::vector& arguments) - { - if (executable.empty()) { - return Void::Result::fail("Process::reexec: executable is empty"); - } - std::vector owned; - owned.reserve(arguments.size() + 1); - owned.push_back(executable.string()); - owned.insert(owned.end(), arguments.begin(), arguments.end()); - std::vector argv; - argv.reserve(owned.size() + 1); - for (auto& argument : owned) { - argv.push_back(argument.data()); - } - argv.push_back(nullptr); - ::execv(executable.c_str(), argv.data()); - return Void::Result::fail(std::format( - "Process::reexec: execv '{}' failed: {}", executable.string(), - std::strerror(errno))); - } + auto put_var = [&](std::string key, std::string val) { + if (!env_map.contains(key)) { + key_order.push_back(key); + } + env_map.insert_or_assign(std::move(key), std::move(val)); + }; + + if (policy.mode != EnvMode::explicit_only && environ != nullptr) { + for (char** p = environ; *p != nullptr; ++p) { + const std::string_view entry{*p}; + const auto eq = entry.find('='); + if (eq == std::string_view::npos) { + continue; + } + const std::string_view k = entry.substr(0, eq); + const std::string_view v = entry.substr(eq + 1); + if (unset_set.contains(k)) { + continue; + } + if (policy.mode == EnvMode::allowlist && !allow_set.contains(k)) { + continue; + } + put_var(std::string{k}, std::string{v}); + } + } + + for (const auto& [k, v] : policy.set_vars) { + if (!validate_key(k) || v.find('\0') != std::string_view::npos) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "SpawnOptions: invalid environment key/value in set_vars")}; + } + put_var(k, v); + } + + base.reserve(key_order.size()); + for (const auto& k : key_order) { + const auto it = env_map.find(k); + if (it != env_map.end()) { + base.push_back(k + "=" + it->second); + } + } + return base; +} + +[[nodiscard]] std::string resolve_executable_path( + const std::filesystem::path& exe, + bool search_path, + const std::vector& env_strings) +{ + const std::string raw = exe.string(); + if (!search_path || raw.find('/') != std::string::npos) { + return raw; + } + + std::optional path_val = find_env_value(env_strings, "PATH"); + if (!path_val.has_value()) { + if (const char* host_path = std::getenv("PATH")) { + path_val = std::string{host_path}; + } + } + if (!path_val.has_value() || path_val->empty()) { + return raw; + } + + std::size_t pos = 0; + while (pos <= path_val->size()) { + const auto colon = path_val->find(':', pos); + const std::string_view dir = + (colon == std::string::npos) + ? std::string_view{*path_val}.substr(pos) + : std::string_view{*path_val}.substr(pos, colon - pos); + const std::filesystem::path cand = + (dir.empty() ? std::filesystem::path{"."} + : std::filesystem::path{dir}) / + raw; + struct stat st {}; + if (::stat(cand.c_str(), &st) == 0 && !S_ISDIR(st.st_mode) && + ::access(cand.c_str(), X_OK) == 0) { + return cand.string(); + } + if (colon == std::string::npos) { + break; + } + pos = colon + 1; + } + return raw; +} + +void emit_lines_from_offset(const std::string& buf, + std::size_t& off, + const std::function& fn, + bool flush) +{ + if (!fn) { + off = buf.size(); + return; + } + std::size_t nl = 0; + while ((nl = buf.find('\n', off)) != std::string::npos) { + std::size_t len = nl - off; + if (len > 0 && buf[off + len - 1] == '\r') { + --len; + } + fn(std::string_view{buf.data() + off, len}); + off = nl + 1; + } + if (flush && off < buf.size()) { + fn(std::string_view{buf.data() + off, buf.size() - off}); + off = buf.size(); + } +} + +} // namespace + +Child::Child(long long pid, + long long pgid, + bool owns_process_group, + Void::System::OwnedFd stdin_fd, + Void::System::OwnedFd stdout_fd, + Void::System::OwnedFd stderr_fd, + std::chrono::milliseconds kill_grace) noexcept + : pid_(pid), + pgid_(pgid), + owns_group_(owns_process_group), + reaped_(pid <= 0), + stdin_(std::move(stdin_fd)), + stdout_(std::move(stdout_fd)), + stderr_(std::move(stderr_fd)), + kill_grace_(kill_grace.count() >= 0 ? kill_grace + : std::chrono::milliseconds{2000}) +{ +} + +Child::~Child() noexcept { reset_and_reap(); } + +Child::Child(Child&& other) noexcept + : pid_(std::exchange(other.pid_, -1)), + pgid_(std::exchange(other.pgid_, -1)), + owns_group_(std::exchange(other.owns_group_, false)), + reaped_(std::exchange(other.reaped_, true)), + cached_status_(other.cached_status_), + stdin_(std::move(other.stdin_)), + stdout_(std::move(other.stdout_)), + stderr_(std::move(other.stderr_)), + kill_grace_(other.kill_grace_) +{ +} + +Child& Child::operator=(Child&& other) noexcept +{ + if (this != &other) { + reset_and_reap(); + pid_ = std::exchange(other.pid_, -1); + pgid_ = std::exchange(other.pgid_, -1); + owns_group_ = std::exchange(other.owns_group_, false); + reaped_ = std::exchange(other.reaped_, true); + cached_status_ = other.cached_status_; + stdin_ = std::move(other.stdin_); + stdout_ = std::move(other.stdout_); + stderr_ = std::move(other.stderr_); + kill_grace_ = other.kill_grace_; + } + return *this; +} + +bool Child::valid() const noexcept { return pid_ > 0; } +bool Child::running() const noexcept { return pid_ > 0 && !reaped_; } +long long Child::pid() const noexcept { return pid_; } +long long Child::pgid() const noexcept { return pgid_; } +bool Child::owns_process_group() const noexcept { return owns_group_; } + +int Child::stdin_fd() const noexcept { return stdin_.get(); } +int Child::stdout_fd() const noexcept { return stdout_.get(); } +int Child::stderr_fd() const noexcept { return stderr_.get(); } + +Void::System::OwnedFd Child::take_stdin_fd() noexcept +{ + return std::move(stdin_); +} + +Void::System::OwnedFd Child::take_stdout_fd() noexcept +{ + return std::move(stdout_); +} + +Void::System::OwnedFd Child::take_stderr_fd() noexcept +{ + return std::move(stderr_); +} + +void Child::close_stdin() noexcept { stdin_.reset(); } + +Void::Result::Result Child::send_signal(int sig) noexcept +{ + if (pid_ <= 0) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "Process::Child::send_signal: invalid child")}; + } + if (reaped_) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::busy, + "Process::Child::send_signal: child already reaped")}; + } + int err = 0; + if (!signal_target(static_cast(pid_), + static_cast(pgid_), + owns_group_, + sig, + err)) { + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + "Process::Child::send_signal failed", + err)}; + } + return {}; +} + +Void::Result::Result, Void::Result::Error> + Child::try_wait() +{ + if (pid_ <= 0) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "Process::Child::try_wait: invalid child")}; + } + if (reaped_) { + return std::optional{cached_status_}; + } + int raw = 0; + for (;;) { + const pid_t w = ::waitpid(static_cast(pid_), &raw, WNOHANG); + if (w == static_cast(pid_)) { + cached_status_ = decode_wait_status(raw); + reaped_ = true; + return std::optional{cached_status_}; + } + if (w == 0) { + return std::optional{std::nullopt}; + } + if (errno == EINTR) { + continue; + } + const int err = errno; + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + "Process::Child::try_wait: waitpid failed", + err)}; + } +} + +Void::Result::Result + Child::terminate(std::chrono::milliseconds grace) +{ + if (pid_ <= 0) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "Process::Child::terminate: invalid child")}; + } + if (reaped_) { + return cached_status_; + } + + const auto effective_grace = + (grace.count() >= 0) ? grace : kill_grace_; + + if (auto polled = try_wait(); !polled.has_value()) { + return std::unexpected{polled.error()}; + } else if (polled->has_value()) { + return **polled; + } + + int sig_err = 0; + (void)signal_target(static_cast(pid_), + static_cast(pgid_), + owns_group_, + SIGTERM, + sig_err); + + const auto grace_deadline = + std::chrono::steady_clock::now() + effective_grace; + while (std::chrono::steady_clock::now() < grace_deadline) { + auto polled = try_wait(); + if (!polled.has_value()) { + return std::unexpected{polled.error()}; + } + if (polled->has_value()) { + return **polled; + } + const auto rem = std::chrono::duration_cast( + grace_deadline - std::chrono::steady_clock::now()); + if (rem.count() <= 0) { + break; + } + std::this_thread::sleep_for( + std::min(rem, std::chrono::milliseconds{10})); + } + + if (auto polled = try_wait(); !polled.has_value()) { + return std::unexpected{polled.error()}; + } else if (polled->has_value()) { + return **polled; + } + + (void)signal_target(static_cast(pid_), + static_cast(pgid_), + owns_group_, + SIGKILL, + sig_err); + + int raw = 0; + for (;;) { + const pid_t w = ::waitpid(static_cast(pid_), &raw, 0); + if (w == static_cast(pid_)) { + cached_status_ = decode_wait_status(raw); + reaped_ = true; + return cached_status_; + } + if (errno == EINTR) { + continue; + } + const int err = errno; + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + "Process::Child::terminate: final waitpid failed", + err)}; + } +} + +Void::Result::Result Child::wait_blocking( + std::chrono::milliseconds timeout, + std::stop_token stop, + std::chrono::milliseconds kill_grace) +{ + if (pid_ <= 0) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "Process::Child::wait_blocking: invalid child")}; + } + if (reaped_) { + return cached_status_; + } + + const bool has_timeout = timeout.count() > 0; + const auto deadline = std::chrono::steady_clock::now() + timeout; + + if (!has_timeout && !stop.stop_possible()) { + int raw = 0; + for (;;) { + const pid_t w = ::waitpid(static_cast(pid_), &raw, 0); + if (w == static_cast(pid_)) { + cached_status_ = decode_wait_status(raw); + reaped_ = true; + return cached_status_; + } + if (errno == EINTR) { + continue; + } + const int err = errno; + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + "Process::Child::wait_blocking: waitpid failed", + err)}; + } + } + + for (;;) { + auto polled = try_wait(); + if (!polled.has_value()) { + return std::unexpected{polled.error()}; + } + if (polled->has_value()) { + return **polled; + } + if (stop.stop_requested()) { + auto term = terminate(kill_grace); + if (!term.has_value()) { + return std::unexpected{term.error()}; + } + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::cancelled, + "Process wait cancelled; child terminated")}; + } + if (has_timeout && std::chrono::steady_clock::now() >= deadline) { + auto term = terminate(kill_grace); + if (!term.has_value()) { + return std::unexpected{term.error()}; + } + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::timed_out, + "Process timed out; child terminated")}; + } + auto sleep_dur = std::chrono::milliseconds{10}; + if (has_timeout) { + const auto rem = + std::chrono::duration_cast( + deadline - std::chrono::steady_clock::now()); + if (rem.count() <= 0) { + continue; + } + sleep_dur = std::min(sleep_dur, rem); + } + std::this_thread::sleep_for(sleep_dur); + } +} + +void Child::reset_and_reap() noexcept +{ + stdin_.reset(); + stdout_.reset(); + stderr_.reset(); + if (pid_ > 0 && !reaped_) { + (void)terminate(kill_grace_); + } + pid_ = -1; + pgid_ = -1; + owns_group_ = false; + reaped_ = true; +} + +Void::Result::Result + spawn(const SpawnOptions& options) +{ + if (options.executable.empty()) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "Process::spawn: executable path cannot be empty")}; + } + + auto env_res = build_environment_strings(options.environment); + if (!env_res.has_value()) { + return std::unexpected{std::move(env_res.error())}; + } + std::vector env_strings = std::move(*env_res); + + const std::string resolved_exe = resolve_executable_path( + options.executable, options.search_path, env_strings); + if (resolved_exe.find('\0') != std::string::npos) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "Process::spawn: executable path contains NUL byte")}; + } + + // Check total argv + env bytes against kMaxSpawnInputBytes before fork(). + std::size_t total_input_bytes = resolved_exe.size() + 1; + for (const auto& arg : options.arguments) { + if (arg.find('\0') != std::string::npos) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "Process::spawn: argument contains NUL byte")}; + } + if (!checked_add_size( + total_input_bytes, arg.size() + 1, total_input_bytes)) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::limit_exceeded, + "Process::spawn: argument size overflow")}; + } + } + for (const auto& e : env_strings) { + if (!checked_add_size( + total_input_bytes, e.size() + 1, total_input_bytes)) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::limit_exceeded, + "Process::spawn: environment size overflow")}; + } + } + if (total_input_bytes > kMaxSpawnInputBytes) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::limit_exceeded, + std::format( + "Process::spawn: argv+env payload ({} bytes) exceeds limit ({})", + total_input_bytes, + kMaxSpawnInputBytes))}; + } + + std::string cwd_str; + if (options.working_directory.has_value()) { + cwd_str = options.working_directory->string(); + if (cwd_str.empty() || cwd_str.find('\0') != std::string::npos) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "Process::spawn: invalid working_directory")}; + } + } + + // Prepare contiguous C pointer arrays prior to fork(). + std::vector argv_storage; + argv_storage.reserve(options.arguments.size() + 1); + argv_storage.push_back(options.executable.string()); + for (const auto& arg : options.arguments) { + argv_storage.push_back(arg); + } + + std::vector argv_ptrs; + argv_ptrs.reserve(argv_storage.size() + 1); + for (auto& a : argv_storage) { + argv_ptrs.push_back(a.data()); + } + argv_ptrs.push_back(nullptr); + + std::vector env_ptrs; + env_ptrs.reserve(env_strings.size() + 1); + for (auto& e : env_strings) { + env_ptrs.push_back(e.data()); + } + env_ptrs.push_back(nullptr); + + int stdin_p[2]{-1, -1}; + int stdout_p[2]{-1, -1}; + int stderr_p[2]{-1, -1}; + int err_p[2]{-1, -1}; + + auto close_all_pipes = [&]() noexcept { + for (int* pair : {stdin_p, stdout_p, stderr_p, err_p}) { + if (pair[0] >= 0) { + (void)::close(pair[0]); + pair[0] = -1; + } + if (pair[1] >= 0) { + (void)::close(pair[1]); + pair[1] = -1; + } + } + }; + + if ((options.stdin_pipe && !create_cloexec_pipe(stdin_p)) || + (options.stdout_pipe && !create_cloexec_pipe(stdout_p)) || + (options.stderr_pipe && !create_cloexec_pipe(stderr_p)) || + !create_cloexec_pipe(err_p)) { + const int err = errno; + close_all_pipes(); + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::spawn_failed, + "Process::spawn: pipe2 failed", + err)}; + } + + const pid_t pid = ::fork(); + if (pid < 0) { + const int err = errno; + close_all_pipes(); + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::spawn_failed, + "Process::spawn: fork failed", + err)}; + } + + if (pid == 0) { + // Strictly async-signal-safe path: no heap allocs, locks, or logging. + if (err_p[0] >= 0) { + (void)::close(err_p[0]); + } + if (stdin_p[1] >= 0) { + (void)::close(stdin_p[1]); + } + if (stdout_p[0] >= 0) { + (void)::close(stdout_p[0]); + } + if (stderr_p[0] >= 0) { + (void)::close(stderr_p[0]); + } + + int err_write = err_p[1]; + if (err_write >= 0 && err_write <= 2) { + const int moved = ::fcntl(err_write, F_DUPFD_CLOEXEC, 3); + if (moved >= 0) { + (void)::close(err_write); + err_write = moved; + } + } + + if (options.new_process_group && ::setpgid(0, 0) != 0) { + const int err = errno; + write_child_failure(err_write, 1, err); + ::_exit(127); + } + + reset_child_signals(); + + if (!redirect_child_fd(stdin_p[0], STDIN_FILENO) || + !redirect_child_fd(stdout_p[1], STDOUT_FILENO) || + !redirect_child_fd(stderr_p[1], STDERR_FILENO)) { + const int err = errno; + write_child_failure(err_write, 3, err); + ::_exit(127); + } + + close_fds_from_except(err_write); + + if (!cwd_str.empty() && ::chdir(cwd_str.c_str()) != 0) { + const int err = errno; + write_child_failure(err_write, 2, err); + ::_exit(127); + } + + ::execve(resolved_exe.c_str(), argv_ptrs.data(), env_ptrs.data()); + const int exec_err = errno; + write_child_failure(err_write, 4, exec_err); + ::_exit(127); + } + + // Parent: close child-side pipe ends immediately. + for (int fd : {err_p[1], stdin_p[0], stdout_p[1], stderr_p[1]}) { + if (fd >= 0) { + (void)::close(fd); + } + } + + ChildFailureMsg child_fail{}; + auto* fail_bytes = reinterpret_cast(&child_fail); + std::size_t fail_got = 0; + while (fail_got < sizeof(child_fail)) { + const ssize_t n = + ::read(err_p[0], fail_bytes + fail_got, sizeof(child_fail) - fail_got); + if (n < 0) { + if (errno == EINTR) { + continue; + } + break; + } + if (n == 0) { + break; + } + fail_got += static_cast(n); + } + (void)::close(err_p[0]); + + if (fail_got == sizeof(child_fail)) { + if (stdin_p[1] >= 0) { + (void)::close(stdin_p[1]); + } + if (stdout_p[0] >= 0) { + (void)::close(stdout_p[0]); + } + if (stderr_p[0] >= 0) { + (void)::close(stderr_p[0]); + } + int raw_status = 0; + while (::waitpid(pid, &raw_status, 0) < 0 && errno == EINTR) { + } + const auto err_code = (child_fail.phase == 4) + ? Void::System::SystemErrorCode::exec_failed + : Void::System::map_errno_to_system_code( + child_fail.err); + const char* phase_desc = (child_fail.phase == 4) + ? "Process::spawn: exec failed" + : (child_fail.phase == 2) + ? "Process::spawn: chdir failed" + : "Process::spawn: child setup failed"; + return std::unexpected{Void::System::make_system_error( + err_code, + std::format("{} '{}'", phase_desc, sanitize_diag(options.executable.string())), + child_fail.err)}; + } + + const long long pgid = options.new_process_group ? pid : ::getpgid(pid); + Void::Log::debug("Process", "spawn: '{}' pid={}", options.executable.string(), pid); + + return Child{ + static_cast(pid), + pgid, + options.new_process_group, + Void::System::OwnedFd{stdin_p[1]}, + Void::System::OwnedFd{stdout_p[0]}, + Void::System::OwnedFd{stderr_p[0]}, + options.kill_grace}; +} + +Void::Result::Result + communicate_blocking(Child& child, + std::string_view stdin_data, + CaptureLimits limits, + std::chrono::milliseconds timeout, + std::stop_token stop, + const StreamCallbacks* callbacks) +{ + if (!child.valid()) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "Process::communicate_blocking: invalid child")}; + } + if (stdin_data.size() > limits.max_stdin_bytes) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::limit_exceeded, + std::format( + "Process::communicate_blocking: stdin ({} bytes) exceeds limit ({})", + stdin_data.size(), + limits.max_stdin_bytes))}; + } + + if (child.stdin_fd() >= 0) { + if (stdin_data.empty()) { + child.close_stdin(); + } else { + (void)set_nonblock(child.stdin_fd()); + } + } + if (child.stdout_fd() >= 0) { + (void)set_nonblock(child.stdout_fd()); + } + if (child.stderr_fd() >= 0) { + (void)set_nonblock(child.stderr_fd()); + } + + CommunicateResult res; + std::size_t stdin_offset = 0; + bool stdin_done = (child.stdin_fd() < 0) || stdin_data.empty(); + bool out_done = (child.stdout_fd() < 0); + bool err_done = (child.stderr_fd() < 0); + + std::size_t out_emitted = 0; + std::size_t err_emitted = 0; + std::size_t out_cur_line = 0; + std::size_t err_cur_line = 0; + bool out_line_exceeded = false; + bool err_line_exceeded = false; + bool fail_line_error = false; + bool fail_output_error = false; + std::string limit_msg; + + auto handle_read_chunk = [&](const char* data, + std::size_t len, + bool is_out) -> bool { + std::string& dst = is_out ? res.out : res.err; + const std::size_t max_bytes = + is_out ? limits.max_stdout_bytes : limits.max_stderr_bytes; + bool& truncated = is_out ? res.stdout_truncated : res.stderr_truncated; + std::size_t& cur_line = is_out ? out_cur_line : err_cur_line; + bool& line_exceeded = is_out ? out_line_exceeded : err_line_exceeded; + + // Track line length across non-'\n' bytes. + if (limits.max_line_bytes > 0) { + for (std::size_t i = 0; i < len; ++i) { + if (data[i] == '\n') { + cur_line = 0; + } else { + ++cur_line; + if (cur_line > limits.max_line_bytes) { + line_exceeded = true; + res.overflowed = true; + truncated = true; + if (limits.overflow_policy == + OverflowPolicy::fail_and_terminate) { + fail_line_error = true; + limit_msg = std::format( + "Process {} line exceeded max_line_bytes ({})", + is_out ? "stdout" : "stderr", + limits.max_line_bytes); + return false; + } + } + } + } + } + + const std::size_t remaining_cap = + (dst.size() < max_bytes) ? (max_bytes - dst.size()) : 0; + const std::size_t to_store = std::min(len, remaining_cap); + if (to_store > 0) { + dst.append(data, to_store); + } + if (to_store < len) { + truncated = true; + res.overflowed = true; + if (limits.overflow_policy == OverflowPolicy::fail_and_terminate) { + fail_output_error = true; + limit_msg = std::format( + "Process {} output exceeded limit ({} bytes)", + is_out ? "stdout" : "stderr", + max_bytes); + return false; + } + } + return true; + }; + + const bool has_timeout = timeout.count() > 0; + const auto deadline = std::chrono::steady_clock::now() + timeout; + + while (!stdin_done || !out_done || !err_done) { + if (stop.stop_requested()) { + res.cancelled = true; + break; + } + if (has_timeout && std::chrono::steady_clock::now() >= deadline) { + res.timed_out = true; + break; + } + + std::array pfds{}; + nfds_t nfds = 0; + if (!stdin_done && child.stdin_fd() >= 0) { + pfds[nfds++] = {child.stdin_fd(), POLLOUT, 0}; + } + if (!out_done && child.stdout_fd() >= 0) { + pfds[nfds++] = {child.stdout_fd(), POLLIN, 0}; + } + if (!err_done && child.stderr_fd() >= 0) { + pfds[nfds++] = {child.stderr_fd(), POLLIN, 0}; + } + if (nfds == 0) { + break; + } + + int poll_timeout_ms = -1; + if (has_timeout) { + const auto rem = + std::chrono::duration_cast( + deadline - std::chrono::steady_clock::now()) + .count(); + if (rem <= 0) { + res.timed_out = true; + break; + } + poll_timeout_ms = static_cast( + std::min(rem, std::numeric_limits::max())); + } + if (stop.stop_possible()) { + poll_timeout_ms = (poll_timeout_ms < 0) + ? 25 + : std::min(poll_timeout_ms, 25); + } + + const int rc = ::poll(pfds.data(), nfds, poll_timeout_ms); + if (rc < 0) { + if (errno == EINTR) { + continue; + } + const int err = errno; + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + "Process::communicate_blocking: poll failed", + err)}; + } + if (rc == 0) { + continue; + } + + bool abort_loop = false; + for (nfds_t i = 0; i < nfds; ++i) { + const short rev = pfds[i].revents; + if (rev == 0) { + continue; + } + if (pfds[i].fd == child.stdin_fd()) { + if ((rev & (POLLERR | POLLHUP | POLLNVAL)) != 0 && + (rev & POLLOUT) == 0) { + child.close_stdin(); + stdin_done = true; + continue; + } + while (stdin_offset < stdin_data.size()) { + const std::size_t rem = stdin_data.size() - stdin_offset; + int write_err = 0; + const ssize_t n = write_pipe_nosigpipe( + child.stdin_fd(), + stdin_data.data() + stdin_offset, + rem, + write_err); + if (n > 0) { + stdin_offset += static_cast(n); + continue; + } + if (n < 0 && + (write_err == EAGAIN || write_err == EWOULDBLOCK)) { + break; + } + child.close_stdin(); + stdin_done = true; + break; + } + if (stdin_offset >= stdin_data.size()) { + child.close_stdin(); + stdin_done = true; + } + } else { + const bool is_out = (pfds[i].fd == child.stdout_fd()); + std::array buf{}; + bool eof = false; + for (;;) { + const ssize_t n = + ::read(pfds[i].fd, buf.data(), buf.size()); + if (n > 0) { + if (!handle_read_chunk( + buf.data(), + static_cast(n), + is_out)) { + abort_loop = true; + break; + } + if (callbacks != nullptr) { + emit_lines_from_offset( + is_out ? res.out : res.err, + is_out ? out_emitted : err_emitted, + is_out ? callbacks->on_stdout + : callbacks->on_stderr, + false); + } + } else if (n == 0) { + eof = true; + break; + } else { + if (errno == EINTR) { + continue; + } + if (errno == EAGAIN || errno == EWOULDBLOCK) { + break; + } + eof = true; + break; + } + } + if (abort_loop) { + break; + } + if (eof || (rev & (POLLHUP | POLLERR | POLLNVAL)) != 0) { + if (is_out) { + out_done = true; + } else { + err_done = true; + } + } + } + } + if (abort_loop) { + break; + } + } + + if (callbacks != nullptr) { + emit_lines_from_offset( + res.out, out_emitted, callbacks->on_stdout, true); + emit_lines_from_offset( + res.err, err_emitted, callbacks->on_stderr, true); + } + + (void)child.take_stdin_fd(); + (void)child.take_stdout_fd(); + (void)child.take_stderr_fd(); + + if (fail_line_error || fail_output_error) { + (void)child.terminate(); + return std::unexpected{Void::System::make_system_error( + fail_line_error ? Void::System::SystemErrorCode::line_limit + : Void::System::SystemErrorCode::output_limit, + limit_msg)}; + } + + if (res.timed_out || res.cancelled) { + auto term = child.terminate(); + if (!term.has_value()) { + return std::unexpected{term.error()}; + } + res.status = *term; + return res; + } + + auto waited = child.wait_blocking( + has_timeout + ? std::max(std::chrono::milliseconds{1}, + std::chrono::duration_cast( + deadline - std::chrono::steady_clock::now())) + : std::chrono::milliseconds{0}, + stop); + if (!waited.has_value()) { + if (waited.error().kind() == Void::Result::ErrorKind::timeout) { + res.timed_out = true; + if (auto st = child.try_wait(); st.has_value() && st->has_value()) { + res.status = **st; + } + return res; + } + if (waited.error().kind() == Void::Result::ErrorKind::cancelled) { + res.cancelled = true; + if (auto st = child.try_wait(); st.has_value() && st->has_value()) { + res.status = **st; + } + return res; + } + return std::unexpected{waited.error()}; + } + + res.status = *waited; + return res; +} + +namespace +{ + +Void::Result::Result + run_legacy_impl(const std::filesystem::path& executable, + std::vector args, + std::string_view stdin_data, + std::chrono::milliseconds timeout, + const StreamCallbacks* cb) +{ + SpawnOptions opts; + opts.executable = executable; + opts.arguments = std::move(args); + opts.search_path = true; + opts.new_process_group = true; + + auto spawned = spawn(opts); + if (!spawned.has_value()) { + // Preserve legacy 1.x behavior where exec failure returns exit_code 127. + if (spawned.error().code().domain == Void::Result::kSystemErrorDomain && + spawned.error().code().value == + static_cast( + Void::System::SystemErrorCode::exec_failed)) { + Output out; + out.exit_code = 127; + return out; + } + return std::unexpected{std::move(spawned.error())}; + } + + CaptureLimits limits; + limits.max_stdout_bytes = 64ULL * 1024ULL * 1024ULL; + limits.max_stderr_bytes = 64ULL * 1024ULL * 1024ULL; + limits.max_line_bytes = 0; // Do not fail legacy unbounded line reads + limits.max_stdin_bytes = 64ULL * 1024ULL * 1024ULL; + limits.overflow_policy = OverflowPolicy::drain_and_truncate; + + auto comm = communicate_blocking( + *spawned, stdin_data, limits, timeout, {}, cb); + if (!comm.has_value()) { + return std::unexpected{std::move(comm.error())}; + } + Output out; + out.exit_code = comm->status.exited ? comm->status.code : -1; + out.out = std::move(comm->out); + out.err = std::move(comm->err); + return out; +} + +} // namespace + +Void::Result::Result + run(const std::filesystem::path& executable, + std::vector args, + std::string_view stdin_data, + std::chrono::milliseconds timeout) +{ + return run_legacy_impl( + executable, std::move(args), stdin_data, timeout, nullptr); +} + +Void::Result::Result run_streaming( + const std::filesystem::path& executable, + std::vector args, + const StreamCallbacks& callbacks, + std::string_view stdin_data, + std::chrono::milliseconds timeout) +{ + return run_legacy_impl( + executable, std::move(args), stdin_data, timeout, &callbacks); +} + +Void::Result::Result + shell(std::string_view command, std::chrono::milliseconds timeout) +{ + return run("/bin/sh", {"-c", std::string{command}}, {}, timeout); +} + +Void::Result::Result + reexec(const std::filesystem::path& executable, + const std::vector& arguments) +{ + return reexec(executable, arguments, false); +} + +Void::Result::Result + reexec(const std::filesystem::path& executable, + const std::vector& arguments, + bool close_extra_fds) +{ + if (executable.empty()) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "Process::reexec: executable is empty")}; + } + std::vector owned; + owned.reserve(arguments.size() + 1); + owned.push_back(executable.string()); + owned.insert(owned.end(), arguments.begin(), arguments.end()); + std::vector argv; + argv.reserve(owned.size() + 1); + for (auto& argument : owned) { + argv.push_back(argument.data()); + } + argv.push_back(nullptr); + + if (close_extra_fds) { + close_fds_from_except(-1); + } + + ::execv(executable.c_str(), argv.data()); + const int err = errno; + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::exec_failed, + std::format("Process::reexec: execv '{}' failed", executable.string()), + err)}; +} } // namespace Void::Process diff --git a/src/System/module.cmake b/src/System/module.cmake index 0d0815a..d94dd64 100644 --- a/src/System/module.cmake +++ b/src/System/module.cmake @@ -1,4 +1,7 @@ void_add_module(System - INTERNAL_DEPS Functional LogState + INTERNAL_DEPS Functional Time LogState EXTERNAL_DEPS Threads::Threads + EXCLUDE_HEADERS + Void/System/AsyncProcess.hpp + Void/System/AsyncWatcher.hpp ) diff --git a/src/SystemAsync/AsyncProcess.cpp b/src/SystemAsync/AsyncProcess.cpp new file mode 100644 index 0000000..7ff29e0 --- /dev/null +++ b/src/SystemAsync/AsyncProcess.cpp @@ -0,0 +1,781 @@ +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::SystemAsync +{ + +namespace +{ + +struct PipeCommState { + std::mutex mu{}; + Void::Process::CaptureLimits limits{}; + std::stop_source stop_src{}; + std::string out{}; + std::string err{}; + std::size_t out_cur_line{0}; + std::size_t err_cur_line{0}; + bool stdout_truncated{false}; + bool stderr_truncated{false}; + bool timed_out{false}; + bool cancelled{false}; + bool overflowed{false}; + std::optional fatal_error{}; +}; + +void record_fatal(PipeCommState& st, Void::Result::Error err) +{ + std::lock_guard lk{st.mu}; + if (!st.fatal_error.has_value()) { + st.fatal_error = std::move(err); + } + st.stop_src.request_stop(); +} + +void process_pipe_chunk(PipeCommState& st, + const std::byte* data, + std::size_t len, + bool is_stdout) +{ + std::lock_guard lk{st.mu}; + std::string& dst = is_stdout ? st.out : st.err; + const std::size_t max_bytes = + is_stdout ? st.limits.max_stdout_bytes : st.limits.max_stderr_bytes; + bool& truncated = is_stdout ? st.stdout_truncated : st.stderr_truncated; + std::size_t& cur_line = is_stdout ? st.out_cur_line : st.err_cur_line; + const auto* chars = reinterpret_cast(data); + + if (st.limits.max_line_bytes > 0) { + for (std::size_t i = 0; i < len; ++i) { + if (chars[i] == '\n') { + cur_line = 0; + } else { + ++cur_line; + if (cur_line > st.limits.max_line_bytes) { + truncated = true; + st.overflowed = true; + if (st.limits.overflow_policy == + Void::Process::OverflowPolicy::fail_and_terminate) { + if (!st.fatal_error.has_value()) { + st.fatal_error = Void::System::make_system_error( + Void::System::SystemErrorCode::line_limit, + std::format( + "Async process {} line exceeded max_line_bytes ({})", + is_stdout ? "stdout" : "stderr", + st.limits.max_line_bytes)); + } + st.stop_src.request_stop(); + return; + } + } + } + } + } + + const std::size_t rem_cap = + (dst.size() < max_bytes) ? (max_bytes - dst.size()) : 0; + const std::size_t to_store = std::min(len, rem_cap); + if (to_store > 0) { + dst.append(chars, to_store); + } + if (to_store < len) { + truncated = true; + st.overflowed = true; + if (st.limits.overflow_policy == + Void::Process::OverflowPolicy::fail_and_terminate) { + if (!st.fatal_error.has_value()) { + st.fatal_error = Void::System::make_system_error( + Void::System::SystemErrorCode::output_limit, + std::format( + "Async process {} output exceeded limit ({} bytes)", + is_stdout ? "stdout" : "stderr", + max_bytes)); + } + st.stop_src.request_stop(); + } + } +} + +[[nodiscard]] Void::Coro::Task pump_stdin_task( + Void::IO::Driver* driver, + Void::IO::ByteStream stream, + std::shared_ptr st, + std::string stdin_data, + std::stop_token ext_stop, + std::optional deadline) +{ + constexpr std::size_t kChunk = 16ULL * 1024ULL; + std::size_t offset = 0; + while (offset < stdin_data.size() && !st->stop_src.stop_requested()) { + const std::size_t n = std::min(kChunk, stdin_data.size() - offset); + auto lease_res = driver->allocate_buffer(n); + if (!lease_res.has_value()) { + record_fatal(*st, std::move(lease_res.error())); + break; + } + auto lease = std::move(*lease_res); + std::memcpy(lease.writable().data(), stdin_data.data() + offset, n); + lease.set_valid_bytes(n); + + Void::Async::OperationOptions pipe_opts{ + .stop = st->stop_src.get_token(), .deadline = deadline}; + auto wr = co_await stream.write_some_owned(lease, pipe_opts); + if (!wr.has_value()) { + const auto& err = wr.error(); + if (err.kind() == Void::Result::ErrorKind::timeout) { + std::lock_guard lk{st->mu}; + st->timed_out = true; + st->stop_src.request_stop(); + } else if (err.kind() == Void::Result::ErrorKind::cancelled && + ext_stop.stop_requested()) { + std::lock_guard lk{st->mu}; + st->cancelled = true; + st->stop_src.request_stop(); + } + break; + } + offset += wr->bytes; + } + (void)co_await stream.close_and_join(); +} + +[[nodiscard]] Void::Coro::Task pump_read_task( + Void::IO::Driver* driver, + Void::IO::ByteStream stream, + std::shared_ptr st, + bool is_stdout, + std::stop_token ext_stop, + std::optional deadline) +{ + constexpr std::size_t kChunk = 16ULL * 1024ULL; + auto lease_res = driver->allocate_buffer(kChunk); + if (!lease_res.has_value()) { + record_fatal(*st, std::move(lease_res.error())); + (void)co_await stream.close_and_join(); + co_return; + } + auto lease = std::move(*lease_res); + + while (!st->stop_src.stop_requested()) { + Void::Async::OperationOptions pipe_opts{ + .stop = st->stop_src.get_token(), .deadline = deadline}; + auto rd = co_await stream.read_some_owned(lease, pipe_opts); + if (!rd.has_value()) { + const auto& err = rd.error(); + if (err.kind() == Void::Result::ErrorKind::timeout) { + std::lock_guard lk{st->mu}; + st->timed_out = true; + st->stop_src.request_stop(); + } else if (err.kind() == Void::Result::ErrorKind::cancelled) { + if (ext_stop.stop_requested()) { + std::lock_guard lk{st->mu}; + st->cancelled = true; + } + } else { + record_fatal(*st, err); + } + break; + } + if (rd->bytes > 0) { + process_pipe_chunk( + *st, lease.readable().data(), rd->bytes, is_stdout); + if (st->stop_src.stop_requested()) { + break; + } + } + if (rd->eof) { + break; + } + } + (void)co_await stream.close_and_join(); +} + +struct WaitOutcome { + Void::Process::ExitStatus status{}; + bool timed_out{false}; + bool cancelled{false}; +}; + +struct ReaperEntry { + Void::Process::Child* child{nullptr}; + std::shared_ptr> op{}; + bool escalate_immediately{false}; + int phase{0}; // 0 = waiting/running, 1 = SIGTERM sent + std::chrono::milliseconds grace{std::chrono::milliseconds{2000}}; + std::optional deadline{}; + Void::Time::MonotonicClock::time_point kill_deadline{}; + bool done{false}; +}; + +} // namespace + +struct ProcessManager::Impl : public std::enable_shared_from_this { + Void::IO::Driver& driver; + Void::Async::Executor& executor; + ProcessManagerOptions options; + const Void::Time::MonotonicClock& clock; + + mutable std::mutex mu{}; + std::condition_variable cv{}; + std::size_t active_slots{0}; + bool closing{false}; + bool stop_worker{false}; + std::vector waits{}; + std::vector>> close_waiters{}; + std::thread reaper_thread{}; + + Impl(Void::IO::Driver& d, + Void::Async::Executor& ex, + ProcessManagerOptions opts, + const Void::Time::MonotonicClock& clk) + : driver(d), executor(ex), options(opts), clock(clk) + { + reaper_thread = std::thread([this] { run_reaper(); }); + } + + ~Impl() noexcept + { + { + std::lock_guard lk{mu}; + closing = true; + stop_worker = true; + cv.notify_all(); + } + if (reaper_thread.joinable()) { + reaper_thread.join(); + } + } + + void release_slot() noexcept + { + std::lock_guard lk{mu}; + if (active_slots > 0) { + --active_slots; + } + cv.notify_all(); + } + + void run_reaper() + { + for (;;) { + std::vector tickets; + std::vector>> + completed_closes; + { + std::unique_lock lk{mu}; + if (waits.empty() && !stop_worker) { + cv.wait(lk, [this] { + return !waits.empty() || stop_worker; + }); + } + if (stop_worker && waits.empty()) { + for (auto& cw : close_waiters) { + if (auto t = cw->try_commit_value(); t.has_value()) { + tickets.push_back(std::move(*t)); + } + if (auto r = cw->release_backend_ref(); r.has_value()) { + tickets.push_back(std::move(*r)); + } + } + close_waiters.clear(); + lk.unlock(); + for (auto& t : tickets) { + t.dispatch(); + } + return; + } + + const auto now = clock.now(); + for (auto& w : waits) { + if (w.done) { + continue; + } + auto polled = w.child->try_wait(); + if (!polled.has_value()) { + if (auto t = w.op->try_commit_error( + std::move(polled.error())); + t.has_value()) { + tickets.push_back(std::move(*t)); + } + if (auto r = w.op->release_backend_ref(); r.has_value()) { + tickets.push_back(std::move(*r)); + } + w.done = true; + continue; + } + if (polled->has_value()) { + WaitOutcome wo; + wo.status = **polled; + wo.timed_out = + (w.phase > 0 && w.deadline.has_value() && + now >= *w.deadline) || + w.escalate_immediately; + wo.cancelled = w.op->stop_requested() || stop_worker; + if (auto t = w.op->try_commit_value(wo); t.has_value()) { + tickets.push_back(std::move(*t)); + } + if (auto r = w.op->release_backend_ref(); r.has_value()) { + tickets.push_back(std::move(*r)); + } + w.done = true; + continue; + } + + const bool expired = + w.deadline.has_value() && now >= *w.deadline; + const bool stopped = w.op->stop_requested() || stop_worker; + if (w.phase == 0 && + (w.escalate_immediately || expired || stopped)) { + (void)w.child->send_signal(SIGTERM); + w.phase = 1; + w.kill_deadline = now + w.grace; + } else if (w.phase == 1 && now >= w.kill_deadline) { + (void)w.child->send_signal(SIGKILL); + auto term_res = w.child->wait_blocking( + std::chrono::milliseconds{1000}); + if (term_res.has_value()) { + WaitOutcome wo; + wo.status = *term_res; + wo.timed_out = expired; + wo.cancelled = stopped; + if (auto t = w.op->try_commit_value(wo); + t.has_value()) { + tickets.push_back(std::move(*t)); + } + } else { + if (auto t = w.op->try_commit_error( + std::move(term_res.error())); + t.has_value()) { + tickets.push_back(std::move(*t)); + } + } + if (auto r = w.op->release_backend_ref(); r.has_value()) { + tickets.push_back(std::move(*r)); + } + w.done = true; + } + } + + std::erase_if( + waits, [](const ReaperEntry& e) { return e.done; }); + if (closing && waits.empty() && !close_waiters.empty()) { + completed_closes = std::move(close_waiters); + close_waiters.clear(); + } + } + + for (auto& cw : completed_closes) { + if (auto t = cw->try_commit_value(); t.has_value()) { + tickets.push_back(std::move(*t)); + } + if (auto r = cw->release_backend_ref(); r.has_value()) { + tickets.push_back(std::move(*r)); + } + } + for (auto& t : tickets) { + t.dispatch(); + } + + std::unique_lock lk{mu}; + if (!waits.empty()) { + cv.wait_for(lk, std::chrono::milliseconds{5}, [this] { + return stop_worker; + }); + } + } + } +}; + +struct ManagedChild::SlotGuard { + std::weak_ptr mgr; + ~SlotGuard() noexcept + { + if (auto p = mgr.lock()) { + p->release_slot(); + } + } +}; + +ManagedChild::~ManagedChild() noexcept = default; +ManagedChild::ManagedChild(ManagedChild&&) noexcept = default; +ManagedChild& ManagedChild::operator=(ManagedChild&&) noexcept = default; + +bool ManagedChild::valid() const noexcept { return child_.valid(); } + +void ManagedChild::release_slot() noexcept +{ + child_ = Void::Process::Child{}; + slot_token_.reset(); +} + +ProcessManager::ProcessManager(Void::IO::Driver& driver, + Void::Async::Executor& executor, + ProcessManagerOptions options, + const Void::Time::MonotonicClock& clock) + : impl_(std::make_shared(driver, executor, options, clock)) +{ +} + +ProcessManager::~ProcessManager() noexcept = default; + +Void::Result::Result + ProcessManager::spawn(const Void::Process::SpawnOptions& options) +{ + { + std::lock_guard lk{impl_->mu}; + if (impl_->closing) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::busy, + "ProcessManager::spawn: manager is closing")}; + } + if (impl_->active_slots >= impl_->options.max_active_children) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::limit_exceeded, + std::format( + "ProcessManager::spawn: active child limit ({}) reached", + impl_->options.max_active_children))}; + } + ++impl_->active_slots; + } + + auto guard = + std::make_shared(impl_); + auto child = Void::Process::spawn(options); + if (!child.has_value()) { + return std::unexpected{std::move(child.error())}; + } + + ManagedChild out; + out.child_ = std::move(*child); + out.slot_token_ = std::move(guard); + return out; +} + +namespace +{ + +[[nodiscard]] Void::Coro::Task> + wait_for_reap_async( + std::shared_ptr impl, + Void::Process::Child& child, + bool escalate_immediately, + std::chrono::milliseconds grace, + Void::Async::OperationOptions options) +{ + if (!child.valid()) { + co_return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "ProcessManager::wait: invalid child")}; + } + + if (auto polled = child.try_wait(); !polled.has_value()) { + co_return std::unexpected{std::move(polled.error())}; + } else if (polled->has_value()) { + WaitOutcome wo; + wo.status = **polled; + co_return wo; + } + + auto op = Void::Async::OperationState::create( + options, + &impl->executor, + Void::Async::StopBehavior::notify_only); + op->acquire_backend_ref(); + + { + std::lock_guard lk{impl->mu}; + if (impl->closing && !escalate_immediately) { + if (auto r = op->release_backend_ref(); r.has_value()) { + r->dispatch(); + } + co_return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::busy, + "ProcessManager::wait: manager is closing")}; + } + ReaperEntry entry; + entry.child = &child; + entry.op = op; + entry.escalate_immediately = escalate_immediately; + entry.grace = grace; + entry.deadline = options.deadline; + impl->waits.push_back(std::move(entry)); + impl->cv.notify_all(); + } + + co_return co_await op->awaitable(&impl->executor); +} + +} // namespace + +Void::Coro::Task> + ProcessManager::communicate(Void::Process::Child& child, + std::string stdin_data, + Void::Process::CaptureLimits limits, + Void::Async::OperationOptions options) +{ + if (!child.valid()) { + co_return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "ProcessManager::communicate: invalid child")}; + } + if (stdin_data.size() > limits.max_stdin_bytes) { + co_return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::limit_exceeded, + "ProcessManager::communicate: stdin exceeds max_stdin_bytes")}; + } + if (Void::Async::is_deadline_expired(options, impl_->clock)) { + (void)child.terminate(impl_->options.default_kill_grace); + co_return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::timed_out, + "ProcessManager::communicate: deadline already expired")}; + } + + if (stdin_data.empty()) { + child.close_stdin(); + } + + Void::IO::ByteStream in_stream; + Void::IO::ByteStream out_stream; + Void::IO::ByteStream err_stream; + + auto adopt_pipe = + [&](Void::System::OwnedFd owned, + Void::IO::ByteStream& target) -> Void::Result::Result { + if (!owned.valid()) { + return {}; + } + auto adopted = impl_->driver.adopt_fd(owned.get()); + if (!adopted.has_value()) { + return std::unexpected{std::move(adopted.error())}; + } + (void)owned.release(); + target = std::move(*adopted); + return {}; + }; + + if (auto r = adopt_pipe(child.take_stdin_fd(), in_stream); !r.has_value()) { + co_return std::unexpected{std::move(r.error())}; + } + if (auto r = adopt_pipe(child.take_stdout_fd(), out_stream); !r.has_value()) { + if (in_stream.valid()) { + (void)co_await in_stream.close_and_join(); + } + co_return std::unexpected{std::move(r.error())}; + } + if (auto r = adopt_pipe(child.take_stderr_fd(), err_stream); !r.has_value()) { + if (in_stream.valid()) { + (void)co_await in_stream.close_and_join(); + } + if (out_stream.valid()) { + (void)co_await out_stream.close_and_join(); + } + co_return std::unexpected{std::move(r.error())}; + } + + auto st = std::make_shared(); + st->limits = limits; + + struct ForwardStop { + std::shared_ptr state; + void operator()() const noexcept { state->stop_src.request_stop(); } + }; + std::optional> ext_cb; + if (options.stop.stop_possible()) { + ext_cb.emplace(options.stop, ForwardStop{st}); + } + + Void::Async::TaskScope scope{ + impl_->executor, + Void::Async::TaskScopeOptions::unlimited(st->stop_src.get_token(), false), + impl_->clock}; + + if (in_stream.valid()) { + auto sp = scope.spawn(pump_stdin_task(&impl_->driver, + std::move(in_stream), + st, + std::move(stdin_data), + options.stop, + options.deadline)); + if (!sp.has_value()) { + record_fatal(*st, + Void::Async::make_async_error( + sp.error(), "Failed to spawn async stdin pump")); + } + } + if (out_stream.valid()) { + auto sp = scope.spawn(pump_read_task(&impl_->driver, + std::move(out_stream), + st, + true, + options.stop, + options.deadline)); + if (!sp.has_value()) { + record_fatal(*st, + Void::Async::make_async_error( + sp.error(), "Failed to spawn async stdout pump")); + } + } + if (err_stream.valid()) { + auto sp = scope.spawn(pump_read_task(&impl_->driver, + std::move(err_stream), + st, + false, + options.stop, + options.deadline)); + if (!sp.has_value()) { + record_fatal(*st, + Void::Async::make_async_error( + sp.error(), "Failed to spawn async stderr pump")); + } + } + + (void)co_await scope.join(); + + bool need_terminate = false; + bool timed_out_flag = false; + bool cancelled_flag = options.stop.stop_requested(); + std::optional fatal_err; + { + std::lock_guard lk{st->mu}; + timed_out_flag = st->timed_out || + Void::Async::is_deadline_expired(options, impl_->clock); + cancelled_flag = cancelled_flag || st->cancelled; + fatal_err = st->fatal_error; + need_terminate = timed_out_flag || cancelled_flag || fatal_err.has_value(); + } + + auto wait_res = co_await wait_for_reap_async( + impl_, + child, + need_terminate, + impl_->options.default_kill_grace, + need_terminate ? Void::Async::OperationOptions{} : options); + + if (fatal_err.has_value()) { + co_return std::unexpected{std::move(*fatal_err)}; + } + if (!wait_res.has_value()) { + co_return std::unexpected{std::move(wait_res.error())}; + } + + Void::Process::CommunicateResult out; + { + std::lock_guard lk{st->mu}; + out.out = std::move(st->out); + out.err = std::move(st->err); + out.stdout_truncated = st->stdout_truncated; + out.stderr_truncated = st->stderr_truncated; + out.overflowed = st->overflowed; + } + out.status = wait_res->status; + out.timed_out = timed_out_flag || wait_res->timed_out; + out.cancelled = cancelled_flag || wait_res->cancelled; + co_return out; +} + +Void::Coro::Task> + ProcessManager::communicate(ManagedChild& managed, + std::string stdin_data, + Void::Process::CaptureLimits limits, + Void::Async::OperationOptions options) +{ + co_return co_await communicate( + managed.child(), std::move(stdin_data), limits, std::move(options)); +} + +Void::Coro::Task> + ProcessManager::wait(Void::Process::Child& child, + Void::Async::OperationOptions options) +{ + auto wo = co_await wait_for_reap_async( + impl_, + child, + false, + impl_->options.default_kill_grace, + std::move(options)); + if (!wo.has_value()) { + co_return std::unexpected{std::move(wo.error())}; + } + if (wo->cancelled) { + co_return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::cancelled, + "ProcessManager::wait cancelled; child terminated")}; + } + if (wo->timed_out) { + co_return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::timed_out, + "ProcessManager::wait timed out; child terminated")}; + } + co_return wo->status; +} + +Void::Coro::Task> + ProcessManager::wait(ManagedChild& managed, + Void::Async::OperationOptions options) +{ + co_return co_await wait(managed.child(), std::move(options)); +} + +Void::Coro::Task> + ProcessManager::close_and_join(Void::Async::OperationOptions options) +{ + std::shared_ptr> op; + { + std::lock_guard lk{impl_->mu}; + impl_->closing = true; + if (impl_->waits.empty()) { + impl_->stop_worker = true; + impl_->cv.notify_all(); + co_return {}; + } + op = Void::Async::OperationState::create( + options, + &impl_->executor, + Void::Async::StopBehavior::settle_cancelled); + op->acquire_backend_ref(); + impl_->close_waiters.push_back(op); + impl_->cv.notify_all(); + } + auto res = co_await op->awaitable(&impl_->executor); + std::lock_guard lk{impl_->mu}; + impl_->stop_worker = true; + impl_->cv.notify_all(); + co_return res; +} + +std::size_t ProcessManager::active_children() const noexcept +{ + std::lock_guard lk{impl_->mu}; + return impl_->active_slots; +} + +bool ProcessManager::closed() const noexcept +{ + std::lock_guard lk{impl_->mu}; + return impl_->closing; +} + +} // namespace Void::SystemAsync diff --git a/src/SystemAsync/AsyncWatcher.cpp b/src/SystemAsync/AsyncWatcher.cpp new file mode 100644 index 0000000..66a78f5 --- /dev/null +++ b/src/SystemAsync/AsyncWatcher.cpp @@ -0,0 +1,648 @@ +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::SystemAsync +{ + +namespace +{ + +thread_local const void* t_active_subscription_token = nullptr; + +struct DispatchGuard { + const void* prev{nullptr}; + explicit DispatchGuard(const void* cur) noexcept + : prev(t_active_subscription_token) + { + t_active_subscription_token = cur; + } + ~DispatchGuard() noexcept { t_active_subscription_token = prev; } +}; + +struct PathSnapshot { + bool exists{false}; + bool is_symlink{false}; + bool permission_denied{false}; + int sys_errno{0}; + std::uint64_t dev{0}; + std::uint64_t ino{0}; + std::uint32_t mode{0}; + std::uint64_t size{0}; + std::int64_t mtime_ns{0}; + std::string symlink_target{}; + + [[nodiscard]] bool operator==(const PathSnapshot&) const = default; +}; + +[[nodiscard]] PathSnapshot probe_path(const std::filesystem::path& path) +{ + PathSnapshot snap; +#ifndef _WIN32 + struct stat st {}; + if (::lstat(path.c_str(), &st) != 0) { + const int err = errno; + snap.sys_errno = err; + if (err == EACCES || err == EPERM) { + snap.permission_denied = true; + } + return snap; + } + snap.exists = true; + snap.is_symlink = S_ISLNK(st.st_mode); + snap.dev = static_cast(st.st_dev); + snap.ino = static_cast(st.st_ino); + snap.mode = static_cast(st.st_mode); + snap.size = static_cast(st.st_size); + snap.mtime_ns = + static_cast(st.st_mtim.tv_sec) * 1000000000LL + + static_cast(st.st_mtim.tv_nsec); + + if (snap.is_symlink) { + std::array link_buf{}; + const ssize_t len = + ::readlink(path.c_str(), link_buf.data(), link_buf.size()); + if (len > 0) { + snap.symlink_target.assign( + link_buf.data(), static_cast(len)); + } + } +#else + (void)path; +#endif + return snap; +} + +[[nodiscard]] bool path_within_root(const std::filesystem::path& candidate, + const std::filesystem::path& root, + std::filesystem::path& out_normalized) +{ + std::error_code ec; + const auto canon_root = std::filesystem::weakly_canonical(root, ec); + if (ec) { + return false; + } + const auto lex_cand = candidate.lexically_normal(); + for (const auto& comp : lex_cand) { + if (comp == "..") { + return false; + } + } + const auto parent = lex_cand.parent_path(); + std::filesystem::path norm_cand; + if (!parent.empty()) { + const auto canon_parent = std::filesystem::weakly_canonical(parent, ec); + if (ec) { + return false; + } + norm_cand = canon_parent / lex_cand.filename(); + } else { + norm_cand = std::filesystem::weakly_canonical(lex_cand, ec); + if (ec) { + return false; + } + } + + auto rel = norm_cand.lexically_relative(canon_root); + if (rel.empty()) { + return false; + } + for (const auto& comp : rel) { + if (comp == "..") { + return false; + } + break; + } + out_normalized = std::move(norm_cand); + return true; +} + +[[nodiscard]] WatchEvent classify_transition(const std::filesystem::path& path, + const PathSnapshot& prev, + const PathSnapshot& cur, + bool allow_symlink) +{ + WatchEvent ev; + ev.path = path; + ev.exists = cur.exists; + ev.dev = cur.dev; + ev.ino = cur.ino; + ev.size = cur.size; + ev.sys_errno = cur.sys_errno; + + if (cur.permission_denied) { + ev.kind = WatchEventKind::permission_denied; + return ev; + } + if (cur.is_symlink && !allow_symlink) { + ev.kind = WatchEventKind::permission_denied; + return ev; + } + if (!prev.exists && cur.exists) { + ev.kind = WatchEventKind::created; + return ev; + } + if (prev.exists && !cur.exists) { + ev.kind = WatchEventKind::deleted; + return ev; + } + if (prev.is_symlink || cur.is_symlink) { + ev.kind = WatchEventKind::symlink_changed; + return ev; + } + if (prev.dev != cur.dev || prev.ino != cur.ino) { + ev.kind = WatchEventKind::replaced_inode; + return ev; + } + ev.kind = WatchEventKind::modified; + return ev; +} + +} // namespace + +struct WatchSubscription::Token { + std::uint64_t id{0}; + std::filesystem::path path{}; + WatchCallback callback{}; + WatchPathOptions options{}; + std::weak_ptr service{}; + + PathSnapshot accepted{}; + PathSnapshot pending{}; + int stable_polls{0}; + bool dirty{false}; + + bool active{true}; + bool delivery_scheduled{false}; + bool dispatching{false}; + std::deque queue{}; + std::mutex mu{}; + std::condition_variable cv{}; + + [[nodiscard]] Void::Result::Result + close_and_join(); +}; + +struct WatcherService::Impl + : public std::enable_shared_from_this { + using Token = WatchSubscription::Token; + + Void::Async::Executor& executor; + WatcherLimits limits; + const Void::Time::MonotonicClock& clock; + ErrorSink error_sink{}; + + Void::Async::TaskScope scope; + std::mutex poll_mu{}; + mutable std::mutex state_mu{}; + std::condition_variable stop_cv{}; + std::uint64_t next_id{1}; + bool closed{false}; + std::size_t total_queued{0}; + std::unordered_map> subs{}; + std::thread bg_thread{}; + + Impl(Void::Async::Executor& ex, + WatcherLimits lim, + const Void::Time::MonotonicClock& clk, + ErrorSink sink) + : executor(ex), + limits(lim), + clock(clk), + error_sink(std::move(sink)), + scope(ex, Void::Async::TaskScopeOptions::unlimited(), clk) + { + } + + static void enqueue_event_locked(Impl& impl, Token& tok, WatchEvent ev) + { + std::lock_guard tlk{tok.mu}; + if (!tok.active) { + return; + } + + for (auto& existing : tok.queue) { + if (existing.path == ev.path) { + if (existing.kind != WatchEventKind::rescan_required) { + existing = std::move(ev); + } + return; + } + } + + if (impl.total_queued >= impl.limits.max_queued_events) { + if (!tok.queue.empty()) { + tok.queue.back().kind = WatchEventKind::rescan_required; + return; + } + ev.kind = WatchEventKind::rescan_required; + } + + tok.queue.push_back(std::move(ev)); + ++impl.total_queued; + } + + [[nodiscard]] static Void::Coro::Task deliver_subscription_events( + std::shared_ptr impl, + std::shared_ptr tok) + { + for (;;) { + WatchEvent ev; + { + std::lock_guard lk{impl->state_mu}; + std::lock_guard tlk{tok->mu}; + if (!tok->active || tok->queue.empty()) { + tok->delivery_scheduled = false; + tok->dispatching = false; + tok->cv.notify_all(); + co_return; + } + ev = std::move(tok->queue.front()); + tok->queue.pop_front(); + if (impl->total_queued > 0) { + --impl->total_queued; + } + tok->dispatching = true; + } + + try { + DispatchGuard dg{tok.get()}; + tok->callback(ev); + } catch (const std::exception& ex) { + if (impl->error_sink) { + impl->error_sink(Void::System::make_system_error( + Void::System::SystemErrorCode::internal, + std::format( + "Watcher callback exception: {}", ex.what()))); + } + } catch (...) { + if (impl->error_sink) { + impl->error_sink(Void::System::make_system_error( + Void::System::SystemErrorCode::internal, + "Watcher callback threw non-std exception")); + } + } + + { + std::lock_guard tlk{tok->mu}; + tok->dispatching = false; + tok->cv.notify_all(); + if (!tok->active) { + tok->delivery_scheduled = false; + co_return; + } + } + } + } + + void poll_once() + { + std::lock_guard poll_lk{poll_mu}; + + std::vector> active_subs; + { + std::lock_guard lk{state_mu}; + if (closed) { + return; + } + active_subs.reserve(subs.size()); + for (const auto& [id, tok] : subs) { + (void)id; + active_subs.push_back(tok); + } + } + + std::vector> to_schedule; + const int required_debounce = std::max(1, limits.debounce_polls); + + for (const auto& tok : active_subs) { + std::filesystem::path p; + bool allow_sym = false; + { + std::lock_guard tlk{tok->mu}; + if (!tok->active) { + continue; + } + p = tok->path; + allow_sym = tok->options.allow_symlink; + } + + const PathSnapshot cur = probe_path(p); + + std::lock_guard lk{state_mu}; + if (closed) { + break; + } + std::optional ready_event; + { + std::lock_guard tlk{tok->mu}; + if (!tok->active) { + continue; + } + if (!tok->dirty) { + if (!(cur == tok->accepted)) { + tok->pending = cur; + tok->stable_polls = 1; + tok->dirty = true; + } + } else { + if (cur == tok->pending) { + ++tok->stable_polls; + } else if (cur == tok->accepted) { + tok->dirty = false; + tok->stable_polls = 0; + } else { + tok->pending = cur; + tok->stable_polls = 1; + } + } + + if (tok->dirty && tok->stable_polls >= required_debounce) { + WatchEvent ev = classify_transition( + tok->path, tok->accepted, tok->pending, allow_sym); + tok->accepted = tok->pending; + tok->dirty = false; + tok->stable_polls = 0; + ready_event = std::move(ev); + } + } + + if (ready_event.has_value()) { + enqueue_event_locked(*this, *tok, std::move(*ready_event)); + std::lock_guard tlk{tok->mu}; + if (tok->active && !tok->delivery_scheduled && + !tok->queue.empty()) { + tok->delivery_scheduled = true; + to_schedule.push_back(tok); + } + } + } + + auto self = this->shared_from_this(); + for (const auto& tok : to_schedule) { + (void)scope.spawn(deliver_subscription_events(self, tok)); + } + } +}; + +Void::Result::Result + WatchSubscription::Token::close_and_join() +{ + auto svc = service.lock(); + if (t_active_subscription_token == this) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::self_join, + "WatchSubscription::close_and_join cannot be called from its own callback")}; + } + + if (svc != nullptr && svc->executor.is_executor_thread()) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::self_join, + "WatchSubscription::close_and_join cannot block on executor thread")}; + } + + if (svc != nullptr) { + std::lock_guard lk{svc->state_mu}; + std::lock_guard tlk{mu}; + if (svc->total_queued >= queue.size()) { + svc->total_queued -= queue.size(); + } else { + svc->total_queued = 0; + } + queue.clear(); + active = false; + svc->subs.erase(id); + } else { + std::lock_guard tlk{mu}; + queue.clear(); + active = false; + } + + std::unique_lock tlk{mu}; + cv.wait(tlk, [this] { return !dispatching; }); + return {}; +} + +WatchSubscription::~WatchSubscription() noexcept +{ + if (token_) { + (void)token_->close_and_join(); + } +} + +WatchSubscription::WatchSubscription(WatchSubscription&&) noexcept = default; +WatchSubscription& + WatchSubscription::operator=(WatchSubscription&& other) noexcept +{ + if (this != &other) { + if (token_) { + (void)token_->close_and_join(); + } + token_ = std::move(other.token_); + } + return *this; +} + +bool WatchSubscription::active() const noexcept +{ + if (!token_) { + return false; + } + std::lock_guard lk{token_->mu}; + return token_->active; +} + +Void::Result::Result + WatchSubscription::close_and_join() +{ + if (!token_) { + return {}; + } + auto res = token_->close_and_join(); + if (res.has_value()) { + token_.reset(); + } + return res; +} + +WatcherService::WatcherService(Void::Async::Executor& executor, + WatcherLimits limits, + const Void::Time::MonotonicClock& clock, + ErrorSink error_sink, + bool start_background_thread) + : impl_(std::make_shared( + executor, limits, clock, std::move(error_sink))) +{ + if (start_background_thread) { + std::weak_ptr weak_impl = impl_; + impl_->bg_thread = std::thread([weak_impl] { + for (;;) { + auto p = weak_impl.lock(); + if (!p) { + return; + } + std::chrono::milliseconds interval{250}; + { + std::unique_lock lk{p->state_mu}; + if (p->closed) { + return; + } + interval = std::max(std::chrono::milliseconds{10}, + p->limits.poll_interval); + p->stop_cv.wait_for(lk, interval, [&p] { + return p->closed; + }); + if (p->closed) { + return; + } + } + p->poll_once(); + } + }); + } +} + +WatcherService::~WatcherService() noexcept { (void)shutdown(); } + +Void::Result::Result + WatcherService::watch(const std::filesystem::path& path, + WatchCallback callback, + WatchPathOptions options) +{ + if (path.empty() || !callback) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "WatcherService::watch requires non-empty path and callback")}; + } + + std::filesystem::path target_path = path; + if (options.allowed_root.has_value()) { + std::filesystem::path normalized; + if (!path_within_root(path, *options.allowed_root, normalized)) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::permission_denied, + std::format( + "WatcherService::watch: '{}' escapes allowed_root", + path.string()))}; + } + target_path = std::move(normalized); + } + + const PathSnapshot initial = probe_path(target_path); + if (initial.is_symlink && !options.allow_symlink) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::permission_denied, + std::format( + "WatcherService::watch: '{}' is a symlink and allow_symlink is false", + target_path.string()))}; + } + + auto tok = std::make_shared(); + tok->path = std::move(target_path); + tok->callback = std::move(callback); + tok->options = std::move(options); + tok->service = impl_; + tok->accepted = initial; + tok->pending = initial; + + { + std::lock_guard lk{impl_->state_mu}; + if (impl_->closed) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::busy, + "WatcherService::watch: service is shut down")}; + } + if (impl_->subs.size() >= impl_->limits.max_watched_paths) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::limit_exceeded, + std::format( + "WatcherService::watch: max_watched_paths ({}) reached", + impl_->limits.max_watched_paths))}; + } + tok->id = impl_->next_id++; + impl_->subs.emplace(tok->id, tok); + } + + WatchSubscription sub; + sub.token_ = std::move(tok); + return sub; +} + +void WatcherService::poll_once() { impl_->poll_once(); } + +std::size_t WatcherService::watch_count() const noexcept +{ + std::lock_guard lk{impl_->state_mu}; + return impl_->subs.size(); +} + +std::size_t WatcherService::queued_event_count() const noexcept +{ + std::lock_guard lk{impl_->state_mu}; + return impl_->total_queued; +} + +Void::Result::Result WatcherService::shutdown() +{ + if (impl_->executor.is_executor_thread()) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::self_join, + "WatcherService::shutdown cannot be called on executor thread")}; + } + + std::thread bg; + { + std::lock_guard lk{impl_->state_mu}; + if (impl_->closed) { + return {}; + } + impl_->closed = true; + impl_->total_queued = 0; + for (const auto& [id, tok] : impl_->subs) { + (void)id; + std::lock_guard tlk{tok->mu}; + tok->active = false; + tok->queue.clear(); + } + impl_->subs.clear(); + impl_->stop_cv.notify_all(); + bg = std::move(impl_->bg_thread); + } + + if (bg.joinable()) { + bg.join(); + } + + impl_->scope.request_stop(); + if (impl_->executor.has_background_workers()) { + (void)impl_->scope.join_blocking(); + } else if (auto* manual = + dynamic_cast(&impl_->executor)) { + (void)impl_->scope.join_pumping(*manual); + } + return {}; +} + +} // namespace Void::SystemAsync diff --git a/src/SystemAsync/module.cmake b/src/SystemAsync/module.cmake new file mode 100644 index 0000000..75d7068 --- /dev/null +++ b/src/SystemAsync/module.cmake @@ -0,0 +1,7 @@ +void_add_module(SystemAsync + INTERNAL_DEPS System Async IO Time Functional LogState + EXTERNAL_DEPS Threads::Threads + EXTRA_HEADERS + Void/System/AsyncProcess.hpp + Void/System/AsyncWatcher.hpp +) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 2d6310c..1f5520e 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -157,7 +157,7 @@ endif() # ── Test-support executables & libraries ────────────────────────────────────── # These are NOT test files; they are helper executables/libs referenced by tests. -if(TARGET VoidTests AND TARGET Void::System) +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 diff --git a/tests/helpers/ProcessHelper.cpp b/tests/helpers/ProcessHelper.cpp index e1e568c..b34ce5a 100644 --- a/tests/helpers/ProcessHelper.cpp +++ b/tests/helpers/ProcessHelper.cpp @@ -1,9 +1,23 @@ +#include +#include +#include + +#include #include +#include #include +#include +#include #include +#include #include +#include #include #include +#include +#include + +extern char** environ; namespace { @@ -25,6 +39,45 @@ int usage_error(std::string_view msg) return 2; } +bool write_all_fd(int fd, const void* data, std::size_t len) noexcept +{ + const auto* ptr = static_cast(data); + std::size_t written = 0; + while (written < len) { + const ssize_t n = ::write(fd, ptr + written, len - written); + if (n < 0) { + if (errno == EINTR) { + continue; + } + return false; + } + written += static_cast(n); + } + return true; +} + +bool read_exact_fd(int fd, void* data, std::size_t len, bool& clean_eof) noexcept +{ + auto* ptr = static_cast(data); + std::size_t got = 0; + clean_eof = false; + while (got < len) { + const ssize_t n = ::read(fd, ptr + got, len - got); + if (n < 0) { + if (errno == EINTR) { + continue; + } + return false; + } + if (n == 0) { + clean_eof = (got == 0); + return false; + } + got += static_cast(n); + } + return true; +} + int mode_echo(int argc, char** argv) { for (int i = 2; i < argc; ++i) { @@ -126,6 +179,282 @@ int mode_lines(int argc, char** argv) return 0; } +int mode_ignore_sigterm(int argc, char** argv) +{ + std::int64_t sleep_ms = 5000; + if (argc >= 3 && !parse_i64(argv[2], sleep_ms)) { + return usage_error("ignore-sigterm duration must be an integer"); + } + if (sleep_ms < 0) { + sleep_ms = 0; + } + std::signal(SIGTERM, SIG_IGN); + std::cout << "ready\n" << std::flush; + std::this_thread::sleep_for(std::chrono::milliseconds{sleep_ms}); + return 0; +} + +int mode_simultaneous_io(int argc, char** argv) +{ + if (argc != 3) { + return usage_error("simultaneous-io requires "); + } + std::int64_t total_i64 = 0; + if (!parse_i64(argv[2], total_i64) || total_i64 < 0) { + return usage_error("simultaneous-io must be non-negative"); + } + const auto total = static_cast(total_i64); + + for (int fd : {STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO}) { + const int fl = ::fcntl(fd, F_GETFL, 0); + if (fl >= 0) { + (void)::fcntl(fd, F_SETFL, fl | O_NONBLOCK); + } + } + + std::string chunk_out(std::min(4096, std::max(1, total)), 'o'); + std::string chunk_err(std::min(4096, std::max(1, total)), 'e'); + std::size_t out_sent = 0; + std::size_t err_sent = 0; + std::size_t in_read = 0; + bool in_eof = false; + std::array in_buf{}; + + while (!in_eof || out_sent < total || err_sent < total) { + std::array pfds{}; + nfds_t nfds = 0; + if (!in_eof) { + pfds[nfds++] = {STDIN_FILENO, POLLIN, 0}; + } + if (out_sent < total) { + pfds[nfds++] = {STDOUT_FILENO, POLLOUT, 0}; + } + if (err_sent < total) { + pfds[nfds++] = {STDERR_FILENO, POLLOUT, 0}; + } + const int rc = ::poll(pfds.data(), nfds, -1); + if (rc < 0) { + if (errno == EINTR) { + continue; + } + return 1; + } + for (nfds_t i = 0; i < nfds; ++i) { + if (pfds[i].fd == STDIN_FILENO && + (pfds[i].revents & (POLLIN | POLLHUP | POLLERR)) != 0) { + for (;;) { + const ssize_t n = ::read(STDIN_FILENO, in_buf.data(), in_buf.size()); + if (n > 0) { + in_read += static_cast(n); + continue; + } + if (n == 0) { + in_eof = true; + break; + } + if (errno == EINTR) { + continue; + } + if (errno == EAGAIN || errno == EWOULDBLOCK) { + break; + } + in_eof = true; + break; + } + } else if (pfds[i].fd == STDOUT_FILENO && (pfds[i].revents & POLLOUT) != 0) { + const std::size_t rem = std::min(chunk_out.size(), total - out_sent); + const ssize_t n = ::write(STDOUT_FILENO, chunk_out.data(), rem); + if (n > 0) { + out_sent += static_cast(n); + } else if (n < 0 && errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK) { + return 1; + } + } else if (pfds[i].fd == STDERR_FILENO && (pfds[i].revents & POLLOUT) != 0) { + const std::size_t rem = std::min(chunk_err.size(), total - err_sent); + const ssize_t n = ::write(STDERR_FILENO, chunk_err.data(), rem); + if (n > 0) { + err_sent += static_cast(n); + } else if (n < 0 && errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK) { + return 1; + } + } + } + } + return (in_read > 0 || total == 0) ? 0 : 0; +} + +int mode_flood(int argc, char** argv) +{ + if (argc != 4) { + return usage_error("flood requires "); + } + std::int64_t out_n = 0; + std::int64_t err_n = 0; + if (!parse_i64(argv[2], out_n) || !parse_i64(argv[3], err_n) || out_n < 0 || err_n < 0) { + return usage_error("flood byte counts must be non-negative"); + } + std::array buf{}; + buf.fill('O'); + for (std::int64_t rem = out_n; rem > 0;) { + const auto chunk = static_cast(std::min(rem, buf.size())); + if (!write_all_fd(STDOUT_FILENO, buf.data(), chunk)) { + return 1; + } + rem -= static_cast(chunk); + } + buf.fill('E'); + for (std::int64_t rem = err_n; rem > 0;) { + const auto chunk = static_cast(std::min(rem, buf.size())); + if (!write_all_fd(STDERR_FILENO, buf.data(), chunk)) { + return 1; + } + rem -= static_cast(chunk); + } + return 0; +} + +int mode_long_line(int argc, char** argv) +{ + if (argc != 3) { + return usage_error("long-line requires "); + } + std::int64_t len = 0; + if (!parse_i64(argv[2], len) || len < 0) { + return usage_error("long-line must be non-negative"); + } + std::array buf{}; + buf.fill('a'); + for (std::int64_t rem = len; rem > 0;) { + const auto chunk = static_cast(std::min(rem, buf.size())); + if (!write_all_fd(STDOUT_FILENO, buf.data(), chunk)) { + return 1; + } + rem -= static_cast(chunk); + } + const char nl = '\n'; + return write_all_fd(STDOUT_FILENO, &nl, 1) ? 0 : 1; +} + +int mode_check_fds() +{ + std::vector open_fds; + for (int fd = 3; fd <= 64; ++fd) { + if (::fcntl(fd, F_GETFD) != -1 || errno != EBADF) { + open_fds.push_back(fd); + } + } + if (open_fds.empty()) { + std::cout << "clean\n"; + } else { + for (std::size_t i = 0; i < open_fds.size(); ++i) { + if (i > 0) { + std::cout << ' '; + } + std::cout << open_fds[i]; + } + std::cout << '\n'; + } + std::cout.flush(); + return 0; +} + +int mode_env_dump() +{ + std::vector vars; + if (environ != nullptr) { + for (char** p = environ; *p != nullptr; ++p) { + vars.emplace_back(*p); + } + } + std::sort(vars.begin(), vars.end()); + for (const auto& entry : vars) { + std::cout << entry << '\n'; + } + std::cout.flush(); + return 0; +} + +int mode_cwd() +{ + std::array buf{}; + if (::getcwd(buf.data(), buf.size()) == nullptr) { + return 1; + } + std::cout << buf.data() << '\n' << std::flush; + return 0; +} + +std::uint16_t read_u16_be(const std::uint8_t* p) noexcept +{ + return static_cast((static_cast(p[0]) << 8) | p[1]); +} + +std::uint32_t read_u32_be(const std::uint8_t* p) noexcept +{ + return (static_cast(p[0]) << 24) | + (static_cast(p[1]) << 16) | + (static_cast(p[2]) << 8) | + static_cast(p[3]); +} + +void write_u16_be(std::uint8_t* p, std::uint16_t v) noexcept +{ + p[0] = static_cast((v >> 8) & 0xffu); + p[1] = static_cast(v & 0xffu); +} + +void write_u32_be(std::uint8_t* p, std::uint32_t v) noexcept +{ + p[0] = static_cast((v >> 24) & 0xffu); + p[1] = static_cast((v >> 16) & 0xffu); + p[2] = static_cast((v >> 8) & 0xffu); + p[3] = static_cast(v & 0xffu); +} + +int mode_ipc_pipe_echo() +{ + for (;;) { + std::array hdr{}; + bool clean_eof = false; + if (!read_exact_fd(STDIN_FILENO, hdr.data(), hdr.size(), clean_eof)) { + return clean_eof ? 0 : 1; + } + if (hdr[0] != 'V' || hdr[1] != 'D' || hdr[2] != 'I' || hdr[3] != 'P') { + return 3; + } + const std::uint16_t version = read_u16_be(hdr.data() + 4); + const std::uint16_t flags_type = read_u16_be(hdr.data() + 6); + const std::uint32_t payload_len = read_u32_be(hdr.data() + 8); + const std::uint32_t stream_id = read_u32_be(hdr.data() + 12); + if (version != 1 || stream_id != 0 || payload_len > 2u * 1024u * 1024u) { + return 4; + } + std::vector payload(payload_len); + if (payload_len > 0) { + bool eof2 = false; + if (!read_exact_fd(STDIN_FILENO, payload.data(), payload_len, eof2)) { + return 5; + } + } + const std::uint8_t frame_type = static_cast(flags_type & 0xffu); + if (frame_type == 7) { // goaway + return 0; + } + if (frame_type == 1 || frame_type == 2) { // hello -> hello, request -> response + std::array out_hdr = hdr; + const std::uint8_t reply_type = (frame_type == 1) ? 1u : 3u; + write_u16_be(out_hdr.data() + 6, reply_type); + write_u32_be(out_hdr.data() + 8, payload_len); + if (!write_all_fd(STDOUT_FILENO, out_hdr.data(), out_hdr.size())) { + return 6; + } + if (payload_len > 0 && !write_all_fd(STDOUT_FILENO, payload.data(), payload.size())) { + return 7; + } + } + } +} + } // namespace int main(int argc, char** argv) @@ -153,5 +482,29 @@ int main(int argc, char** argv) if (mode == "lines") { return mode_lines(argc, argv); } + if (mode == "ignore-sigterm") { + return mode_ignore_sigterm(argc, argv); + } + if (mode == "simultaneous-io") { + return mode_simultaneous_io(argc, argv); + } + if (mode == "flood") { + return mode_flood(argc, argv); + } + if (mode == "long-line") { + return mode_long_line(argc, argv); + } + if (mode == "check-fds") { + return mode_check_fds(); + } + if (mode == "env-dump") { + return mode_env_dump(); + } + if (mode == "cwd") { + return mode_cwd(); + } + if (mode == "ipc-pipe-echo") { + return mode_ipc_pipe_echo(); + } return usage_error("unknown mode"); -} +} \ No newline at end of file diff --git a/tests/package/IPCOnly/CMakeLists.txt b/tests/package/IPCOnly/CMakeLists.txt new file mode 100644 index 0000000..46bc41a --- /dev/null +++ b/tests/package/IPCOnly/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidIPCOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS IPC) + +add_executable(void_ipc_only_consumer main.cpp) +target_link_libraries(void_ipc_only_consumer PRIVATE Void::IPC) +target_compile_features(void_ipc_only_consumer PRIVATE cxx_std_26) + +enable_testing() +add_test(NAME IPCOnlyConsumer COMMAND void_ipc_only_consumer) diff --git a/tests/package/IPCOnly/main.cpp b/tests/package/IPCOnly/main.cpp new file mode 100644 index 0000000..098c31e --- /dev/null +++ b/tests/package/IPCOnly/main.cpp @@ -0,0 +1,29 @@ +#include +#include +#include +#include + +int main() +{ + Void::Binary::ByteBuffer buf{16}; + (void)buf.writeString("hi"); + auto encoded = Void::IPC::encode_frame( + Void::IPC::FrameHeader{.type = Void::IPC::FrameType::one_way, + .request_id = 0}, + buf.view()); + if (!encoded.has_value()) { + return 1; + } + Void::IPC::FrameDecoder dec; + auto decoded = dec.feed(encoded->view()); + if (!decoded.has_value() || decoded->size() != 1) { + return 2; + } + Void::Async::ManualExecutor exec; + auto drv = Void::IO::Driver::create(exec); + if (!drv.has_value()) { + return 3; + } + (void)(*drv)->shutdown_and_join(); + return 0; +} diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index e9c6905..71012e5 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -116,6 +116,31 @@ if(_has_runtime) run_consumer(RuntimeOnly "${install_prefix}" "RuntimeOnly" ${_no_external_deps}) endif() +has_modules(_has_system System Functional Time LogState) +if(_has_system) + run_consumer(SystemOnly "${install_prefix}" "SystemOnly" + -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) +endif() + +has_modules(_has_system_async SystemAsync System Async IO Time Functional LogState) +if(_has_system_async) + run_consumer(SystemAsyncOnly "${install_prefix}" "SystemAsyncOnly" + -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) +endif() + +has_modules(_has_ipc IPC Core Functional Memory Time Binary Async IO Resilience ObservabilityHooks) +if(_has_ipc) + run_consumer(IPCOnly "${install_prefix}" "IPCOnly" ${_no_external_deps}) +endif() + has_modules(_has_obs_hooks ObservabilityHooks) if(_has_obs_hooks) run_consumer(ObservabilityHooksOnly "${install_prefix}" "ObservabilityHooksOnly" ${_no_external_deps}) diff --git a/tests/package/SystemAsyncOnly/CMakeLists.txt b/tests/package/SystemAsyncOnly/CMakeLists.txt new file mode 100644 index 0000000..10ab475 --- /dev/null +++ b/tests/package/SystemAsyncOnly/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidSystemAsyncOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS SystemAsync) + +add_executable(void_system_async_only_consumer main.cpp) +target_link_libraries(void_system_async_only_consumer PRIVATE Void::SystemAsync) +target_compile_features(void_system_async_only_consumer PRIVATE cxx_std_26) + +enable_testing() +add_test(NAME SystemAsyncOnlyConsumer COMMAND void_system_async_only_consumer) diff --git a/tests/package/SystemAsyncOnly/main.cpp b/tests/package/SystemAsyncOnly/main.cpp new file mode 100644 index 0000000..ee9377a --- /dev/null +++ b/tests/package/SystemAsyncOnly/main.cpp @@ -0,0 +1,21 @@ +#include +#include +#include +#include + +int main() +{ + Void::Async::ManualExecutor exec; + auto drv = Void::IO::Driver::create(exec); + if (!drv.has_value()) { + return 1; + } + Void::SystemAsync::ProcessManager mgr{**drv, exec}; + Void::SystemAsync::WatcherService watcher{exec}; + if (mgr.active_children() != 0 || watcher.watch_count() != 0) { + return 2; + } + (void)watcher.shutdown(); + (void)(*drv)->shutdown_and_join(); + return 0; +} diff --git a/tests/package/SystemOnly/CMakeLists.txt b/tests/package/SystemOnly/CMakeLists.txt new file mode 100644 index 0000000..00849b2 --- /dev/null +++ b/tests/package/SystemOnly/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidSystemOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS System) + +add_executable(void_system_only_consumer main.cpp) +target_link_libraries(void_system_only_consumer PRIVATE Void::System) +target_compile_features(void_system_only_consumer PRIVATE cxx_std_26) + +enable_testing() +add_test(NAME SystemOnlyConsumer COMMAND void_system_only_consumer) diff --git a/tests/package/SystemOnly/main.cpp b/tests/package/SystemOnly/main.cpp new file mode 100644 index 0000000..be4524a --- /dev/null +++ b/tests/package/SystemOnly/main.cpp @@ -0,0 +1,31 @@ +#include +#include +#include +#include + +#include + +int main() +{ + auto tmp = Void::FileSystem::TempDir::open("void_pkg_sys_"); + if (!tmp.has_value()) { + std::cerr << tmp.error().message() << '\n'; + return 1; + } + const auto cfg = tmp->path() / "item.txt"; + if (!Void::FileSystem::replace_file(cfg, "ok").has_value()) { + return 2; + } + auto content = Void::FileSystem::read_file_bounded(cfg); + if (!content.has_value() || *content != "ok") { + return 3; + } + Void::Process::SpawnOptions opts; + opts.executable = "/nonexistent/void/binary"; + opts.search_path = false; + auto bad = Void::Process::spawn(opts); + if (bad.has_value()) { + return 4; + } + return 0; +} diff --git a/tests/standalone/IPC/Ipc.cpp b/tests/standalone/IPC/Ipc.cpp new file mode 100644 index 0000000..23405b0 --- /dev/null +++ b/tests/standalone/IPC/Ipc.cpp @@ -0,0 +1,739 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +using Void::Testing::expect; +using Void::Testing::expect_eq; +using Void::Testing::require; + +[[nodiscard]] Void::Binary::FrozenBytes make_bytes(std::string_view sv) +{ + Void::Binary::ByteBuffer buf{sv.size()}; + (void)buf.writeString(sv); + return buf.freeze(); +} + +[[nodiscard]] std::string as_string(const Void::Binary::FrozenBytes& fb) +{ + return std::string{reinterpret_cast(fb.data()), fb.size()}; +} + +void pump_loop(Void::IO::Driver& driver, + Void::Async::ManualExecutor& exec, + Void::Async::TaskScope& scope, + int max_iters = 4000) +{ + for (int i = 0; i < max_iters && scope.active_count() > 0; ++i) { + (void)exec.drain(); + (void)driver.poll_once(std::chrono::milliseconds{1}); + (void)exec.drain(); + } + const bool drained = (scope.active_count() == 0); + if (!drained) { + scope.request_stop(); + for (int i = 0; i < 200 && scope.active_count() > 0; ++i) { + (void)exec.drain(); + (void)driver.poll_once(std::chrono::milliseconds{0}); + (void)exec.drain(); + } + } + require(drained); +} + +struct ShortIpcDir { + std::filesystem::path dir{}; + + ShortIpcDir() + { + static std::atomic seq{0}; + const auto id = seq.fetch_add(1, std::memory_order_relaxed); + dir = std::filesystem::path{ + std::format("/tmp/v_ipc_{}_{}", ::getpid(), id)}; + std::filesystem::remove_all(dir); + require(::mkdir(dir.c_str(), 0700) == 0); + } + + ~ShortIpcDir() + { + std::error_code ec; + std::filesystem::remove_all(dir, ec); + } + + ShortIpcDir(const ShortIpcDir&) = delete; + ShortIpcDir& operator=(const ShortIpcDir&) = delete; +}; + +[[nodiscard]] Void::Coro::Task run_handshake_task( + Void::IPC::Session* sess, + Void::IPC::HelloInfo info, + Void::Async::OperationOptions opts, + Void::Result::Result* out) +{ + *out = co_await sess->handshake(std::move(info), std::move(opts)); +} + +[[nodiscard]] Void::Coro::Task run_request_task( + Void::IPC::Session* sess, + Void::Binary::FrozenBytes req, + Void::Async::OperationOptions opts, + std::expected* out) +{ + *out = co_await sess->request(std::move(req), std::move(opts)); +} + +[[nodiscard]] Void::Coro::Task run_close_session_task( + Void::IPC::Session* sess, + Void::Async::OperationOptions opts, + Void::Result::Result* out) +{ + *out = co_await sess->close_and_join(std::move(opts)); +} + +[[nodiscard]] Void::Coro::Task< + Void::Result::Result> + echo_upper_handler(Void::Binary::FrozenBytes payload, std::stop_token) +{ + std::string s = as_string(payload); + for (char& ch : s) { + if (ch >= 'a' && ch <= 'z') { + ch = static_cast(ch - 'a' + 'A'); + } + } + co_return make_bytes(s); +} + +[[nodiscard]] Void::Coro::Task< + Void::Result::Result> + gated_echo_handler( + Void::Binary::FrozenBytes payload, + std::stop_token cancel, + std::shared_ptr> gate, + std::atomic* entered) +{ + (void)cancel; + if (entered != nullptr) { + entered->store(true, std::memory_order_release); + } + (void)co_await gate->awaitable(); + co_return payload; +} + +[[nodiscard]] Void::Coro::Task< + Void::Result::Result> + cancel_aware_wait_handler(Void::Binary::FrozenBytes payload, + std::stop_token cancel, + Void::Async::Executor* exec, + std::atomic* entered) +{ + if (entered != nullptr) { + entered->store(true, std::memory_order_release); + } + auto op = Void::Async::OperationState::create( + Void::Async::OperationOptions{.stop = cancel}, + exec, + Void::Async::StopBehavior::settle_cancelled); + (void)co_await op->awaitable(exec); + co_return payload; +} + +} // namespace + +Void::Testing::Test ipc_wire_codec_fragmentation_coalescing_and_quotas() +{ + // 1. V1 24B golden big-endian header + payload validation. + Void::IPC::FrameHeader hdr; + hdr.type = Void::IPC::FrameType::request; + hdr.request_id = 0x0102030405060708ULL; + auto f1 = Void::IPC::encode_frame(hdr, make_bytes("alpha").view()); + require(f1.has_value()); + expect_eq(f1->size(), Void::IPC::kFrameHeaderSize + std::size_t{5}); + expect_eq(static_cast((*f1).data()[0]), 'V'); + expect_eq(static_cast((*f1).data()[1]), 'D'); + expect_eq(static_cast((*f1).data()[2]), 'I'); + expect_eq(static_cast((*f1).data()[3]), 'P'); + + // Request/response/cancel require nonzero request_id; hello/one_way/goaway forbid it. + expect(!Void::IPC::validate_frame_header( + Void::IPC::FrameHeader{.type = Void::IPC::FrameType::request, + .request_id = 0}, + Void::IPC::IpcLimits{}) + .has_value()); + expect(!Void::IPC::validate_frame_header( + Void::IPC::FrameHeader{.type = Void::IPC::FrameType::hello, + .request_id = 7}, + Void::IPC::IpcLimits{}) + .has_value()); + expect(!Void::IPC::validate_frame_header( + Void::IPC::FrameHeader{.version = 99, + .type = Void::IPC::FrameType::request, + .request_id = 1}, + Void::IPC::IpcLimits{}) + .has_value()); + expect(!Void::IPC::validate_frame_header( + Void::IPC::FrameHeader{.stream_id = 1, + .request_id = 1}, + Void::IPC::IpcLimits{}) + .has_value()); + + // 2. Fragmentation (1 byte at a time) + coalescing + exact global/session quota enforcement. + auto gq = Void::IPC::BufferQuota::create(128); + auto sq = Void::IPC::BufferQuota::create(128); + Void::IPC::IpcLimits lim; + lim.max_frame_payload = 64; + + Void::IPC::FrameDecoder decoder{lim, gq, sq}; + auto f2 = Void::IPC::encode_frame( + Void::IPC::FrameHeader{.type = Void::IPC::FrameType::response, + .request_id = 42}, + make_bytes("beta").view()); + require(f2.has_value()); + + std::vector combined; + combined.insert(combined.end(), f1->view().begin(), f1->view().end()); + combined.insert(combined.end(), f2->view().begin(), f2->view().end()); + + std::vector out_frames; + for (std::size_t i = 0; i < combined.size(); ++i) { + auto fed = decoder.feed(std::span{&combined[i], 1}); + require(fed.has_value()); + for (auto& df : *fed) { + out_frames.push_back(std::move(df)); + } + } + require(out_frames.size() == 2); + expect_eq(as_string(out_frames[0].payload), std::string{"alpha"}); + expect_eq(out_frames[1].header.request_id, std::uint64_t{42}); + expect_eq(as_string(out_frames[1].payload), std::string{"beta"}); + expect_eq(gq->used(), + Void::IPC::FrameDecoder::frame_quota_cost(5) + + Void::IPC::FrameDecoder::frame_quota_cost(4)); + out_frames.clear(); + expect_eq(gq->used(), std::size_t{0}); + expect_eq(sq->used(), std::size_t{0}); + + // Oversize payload_len fails BEFORE reserving quota. + std::array big_hdr{}; + require(Void::IPC::encode_frame_header( + Void::IPC::FrameHeader{.type = Void::IPC::FrameType::request, + .payload_len = 65, + .request_id = 9}, + big_hdr) + .has_value()); + Void::IPC::FrameDecoder oversize_dec{lim, gq, sq}; + auto ov_res = oversize_dec.feed(big_hdr); + require(!ov_res.has_value()); + expect_eq(ov_res.error().code().value, + static_cast(Void::IPC::IpcErrorCode::frame_too_large)); + expect_eq(gq->used(), std::size_t{0}); +} + +Void::Testing::Test ipc_uds_security_stale_recovery_and_pipe_pair_session() +{ + ShortIpcDir tmp; + Void::Async::ManualExecutor exec; + auto drv_res = Void::IO::Driver::create(exec); + require(drv_res.has_value()); + auto& driver = **drv_res; + + // 1. Reject >= 108B sun_path, 0755 dir, and symlink paths. + { + const std::string long_path = "/tmp/" + std::string(110, 'x') + ".sock"; + auto r = Void::IPC::LocalListener::listen(long_path); + require(!r.has_value()); + expect_eq(r.error().code().value, + static_cast( + Void::IPC::IpcErrorCode::invalid_argument)); + } + { + const auto bad_dir = tmp.dir / "world"; + require(::mkdir(bad_dir.c_str(), 0755) == 0); + (void)::chmod(bad_dir.c_str(), 0755); + auto r = Void::IPC::LocalListener::listen(bad_dir / "s.sock"); + require(!r.has_value()); + expect_eq(r.error().code().value, + static_cast( + Void::IPC::IpcErrorCode::permission_denied)); + } + { + const auto priv_dir = tmp.dir / "priv"; + require(::mkdir(priv_dir.c_str(), 0700) == 0); + const auto sym = priv_dir / "link.sock"; + std::filesystem::create_symlink(tmp.dir / "missing", sym); + auto r = Void::IPC::LocalListener::listen(sym); + require(!r.has_value()); + expect_eq(r.error().code().value, + static_cast( + Void::IPC::IpcErrorCode::permission_denied)); + } + + // 2. Stale socket recovery succeeds safely without disturbing active sockets. + const auto sock_path = tmp.dir / "svc.sock"; + { + const int stale_fd = ::socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); + require(stale_fd >= 0); + sockaddr_un un{}; + un.sun_family = AF_UNIX; + std::memcpy(un.sun_path, sock_path.native().data(), sock_path.native().size()); + require(::bind(stale_fd, + reinterpret_cast(&un), + static_cast( + offsetof(sockaddr_un, sun_path) + + sock_path.native().size() + 1)) == 0); + ::close(stale_fd); // leaves stale unbound/non-listening socket file! + } + + auto listener_res = Void::IPC::LocalListener::listen(sock_path); + require(listener_res.has_value()); + auto& listener = *listener_res; + + struct stat sock_st {}; + require(::lstat(sock_path.c_str(), &sock_st) == 0); + expect_eq(static_cast(sock_st.st_mode & 0777), 0600U); + + // Live listener refuses second concurrent listener. + auto dup_listener = Void::IPC::LocalListener::listen(sock_path); + require(!dup_listener.has_value()); + expect_eq(dup_listener.error().code().value, + static_cast( + Void::IPC::IpcErrorCode::already_exists)); + + // Wrong UID policy rejected cleanly on connect. + auto deny_res = Void::IPC::connect_local( + driver, + sock_path, + Void::IPC::PeerPolicy{.require_uid_match = true, + .set_allowed_uid_to_current_user = false, + .allowed_uid = ::geteuid() + 1000}); + require(!deny_res.has_value()); + expect_eq(deny_res.error().code().value, + static_cast( + Void::IPC::IpcErrorCode::permission_denied)); + { + auto stale = listener.try_accept(driver); + (void)stale; + (void)driver.poll_once(std::chrono::milliseconds{0}); + } + + // Accept & full-duplex handshake + echo request over AF_UNIX. + auto client_tr = Void::IPC::connect_local(driver, sock_path); + require(client_tr.has_value()); + auto server_opt = listener.try_accept(driver); + require(server_opt.has_value() && server_opt->has_value()); + expect((*server_opt)->credentials().available); + + Void::IPC::Session client_sess{driver, exec, std::move(*client_tr)}; + Void::IPC::Session server_sess{driver, exec, std::move(**server_opt)}; + require(server_sess + .start([](Void::Binary::FrozenBytes payload, std::stop_token st) { + return echo_upper_handler(std::move(payload), st); + }) + .has_value()); + + Void::Result::Result h1; + Void::Result::Result h2; + { + Void::Async::TaskScope scope{exec}; + require(scope + .spawn(run_handshake_task(&client_sess, {}, {}, &h1)) + .has_value()); + require(scope + .spawn(run_handshake_task(&server_sess, {}, {}, &h2)) + .has_value()); + pump_loop(driver, exec, scope); + } + require(h1.has_value() && h2.has_value()); + + std::expected rpc_out{ + std::unexpected{Void::IPC::CallFailure{}}}; + { + Void::Async::TaskScope scope{exec}; + require(scope + .spawn(run_request_task( + &client_sess, make_bytes("hello_uds"), {}, &rpc_out)) + .has_value()); + pump_loop(driver, exec, scope); + } + require(rpc_out.has_value()); + expect_eq(as_string(*rpc_out), std::string{"HELLO_UDS"}); + + Void::Result::Result c1; + Void::Result::Result c2; + { + Void::Async::TaskScope scope{exec}; + require(scope.spawn(run_close_session_task(&client_sess, {}, &c1)) + .has_value()); + require(scope.spawn(run_close_session_task(&server_sess, {}, &c2)) + .has_value()); + pump_loop(driver, exec, scope); + } + require(c1.has_value() && c2.has_value()); + listener.close(); + + // 3. adopt_pipe_pair with supervised VoidProcessHelper ipc-pipe-echo child. + int to_child[2]{-1, -1}; + int from_child[2]{-1, -1}; + require(::pipe2(to_child, O_CLOEXEC) == 0); + require(::pipe2(from_child, O_CLOEXEC) == 0); + + const pid_t cpid = ::fork(); + require(cpid >= 0); + if (cpid == 0) { + ::dup2(to_child[0], STDIN_FILENO); + ::dup2(from_child[1], STDOUT_FILENO); + ::close(to_child[0]); + ::close(to_child[1]); + ::close(from_child[0]); + ::close(from_child[1]); + const std::string helper = VOID_PROCESS_HELPER_PATH; + char arg0[] = "VoidProcessHelper"; + char arg1[] = "ipc-pipe-echo"; + char* argv[] = {arg0, arg1, nullptr}; + ::execv(helper.c_str(), argv); + ::_exit(127); + } + ::close(to_child[0]); + ::close(from_child[1]); + + auto pipe_tr = Void::IPC::adopt_pipe_pair(driver, from_child[0], to_child[1]); + require(pipe_tr.has_value()); + expect(!pipe_tr->credentials().available); + + Void::IPC::Session pipe_sess{driver, exec, std::move(*pipe_tr)}; + Void::Result::Result ph; + { + Void::Async::TaskScope scope{exec}; + require(scope + .spawn(run_handshake_task(&pipe_sess, {}, {}, &ph)) + .has_value()); + pump_loop(driver, exec, scope); + } + require(ph.has_value()); + + std::expected pipe_reply{ + std::unexpected{Void::IPC::CallFailure{}}}; + { + Void::Async::TaskScope scope{exec}; + require(scope + .spawn(run_request_task( + &pipe_sess, make_bytes("pipe_echo_ok"), {}, &pipe_reply)) + .has_value()); + pump_loop(driver, exec, scope); + } + require(pipe_reply.has_value()); + expect_eq(as_string(*pipe_reply), std::string{"pipe_echo_ok"}); + + { + Void::Result::Result pc; + Void::Async::TaskScope scope{exec}; + require(scope + .spawn(run_close_session_task(&pipe_sess, {}, &pc)) + .has_value()); + pump_loop(driver, exec, scope); + require(pc.has_value()); + } + + int cstat = 0; + while (::waitpid(cpid, &cstat, 0) < 0 && errno == EINTR) { + } + expect(WIFEXITED(cstat) && WEXITSTATUS(cstat) == 0); + (void)driver.shutdown_and_join(); +} + +Void::Testing::Test ipc_session_control_lane_timeouts_tombstones_and_disconnect() +{ + Void::Async::ManualExecutor exec; + Void::Time::ManualClock clock{ + Void::Time::MonotonicClock::time_point{std::chrono::seconds{10}}}; + auto drv_res = + Void::IO::Driver::create(exec, Void::IO::BackendOptions{}, clock); + require(drv_res.has_value()); + auto& driver = **drv_res; + + // 1. Handshake timeout via injected ManualClock. + { + auto pair = Void::IPC::create_socket_pair_transports(driver); + require(pair.has_value()); + Void::IPC::IpcLimits lim; + lim.handshake_timeout = std::chrono::milliseconds{100}; + Void::IPC::Session client{driver, exec, std::move(pair->first), lim, clock}; + Void::IPC::Session silent_server{ + driver, exec, std::move(pair->second), lim, clock}; + (void)silent_server; + + Void::Result::Result hs_res; + Void::Async::TaskScope scope{exec, {}, clock}; + require(scope.spawn(run_handshake_task(&client, {}, {}, &hs_res)) + .has_value()); + for (int i = 0; i < 4; ++i) { + (void)exec.drain(); + (void)driver.poll_once(std::chrono::milliseconds{0}); + (void)exec.drain(); + } + (void)clock.advance(std::chrono::milliseconds{150}); + pump_loop(driver, exec, scope, 200); + require(!hs_res.has_value()); + expect_eq(hs_res.error().code().value, + static_cast(Void::IPC::IpcErrorCode::timed_out)); + } + + // 2. Saturated handlers + reserved control-lane overload + late response tombstone + cancel. + { + auto pair = Void::IPC::create_socket_pair_transports(driver); + require(pair.has_value()); + Void::IPC::IpcLimits lim; + lim.max_active_handlers = 1; + lim.max_outbound_frames = 32; + lim.rate_limit_burst = 64.0; + lim.rate_limit_per_sec = 10000.0; + + Void::IPC::Session client{driver, exec, std::move(pair->first), lim, clock}; + Void::IPC::Session server{driver, exec, std::move(pair->second), lim, clock}; + + auto gate = Void::Async::OperationState::create({}, &exec); + std::atomic gate_acquired{false}; + require(server + .start([gate, &gate_acquired]( + Void::Binary::FrozenBytes payload, + std::stop_token cancel) { + return gated_echo_handler( + std::move(payload), cancel, gate, &gate_acquired); + }) + .has_value()); + + Void::Result::Result h1; + Void::Result::Result h2; + { + Void::Async::TaskScope scope{exec, {}, clock}; + require(scope.spawn(run_handshake_task(&client, {}, {}, &h1)) + .has_value()); + require(scope.spawn(run_handshake_task(&server, {}, {}, &h2)) + .has_value()); + pump_loop(driver, exec, scope); + } + require(h1.has_value() && h2.has_value()); + + std::expected slow_call{ + std::unexpected{Void::IPC::CallFailure{}}}; + std::expected ov_call{ + std::unexpected{Void::IPC::CallFailure{}}}; + + Void::Async::TaskScope scope{exec, {}, clock}; + gate->acquire_backend_ref(); + require(scope + .spawn(run_request_task( + &client, + make_bytes("slow_one"), + Void::Async::OperationOptions{ + .deadline = + clock.now() + std::chrono::milliseconds{100}}, + &slow_call)) + .has_value()); + + // Pump until server handler enters gate. + for (int i = 0; i < 400 && !gate_acquired.load(); ++i) { + (void)exec.drain(); + (void)driver.poll_once(std::chrono::milliseconds{1}); + (void)exec.drain(); + } + require(gate_acquired.load()); + + // 2nd concurrent request hits max_active_handlers == 1 -> immediate control-lane overloaded error! + require(scope + .spawn(run_request_task(&client, make_bytes("second"), {}, &ov_call)) + .has_value()); + for (int i = 0; i < 400 && ov_call.error().error.message().empty(); ++i) { + (void)exec.drain(); + (void)driver.poll_once(std::chrono::milliseconds{1}); + (void)exec.drain(); + } + require(!ov_call.has_value()); + expect_eq(ov_call.error().error.code().value, + static_cast( + Void::IPC::IpcErrorCode::overloaded)); + expect(ov_call.error().effect == Void::IPC::EffectStatus::not_sent); + + // Advance ManualClock so slow_call times out cleanly -> EffectStatus::unknown & tombstone added. + (void)clock.advance(std::chrono::milliseconds{150}); + for (int i = 0; i < 400 && slow_call.error().error.message().empty(); + ++i) { + (void)exec.drain(); + (void)driver.poll_once(std::chrono::milliseconds{1}); + (void)exec.drain(); + } + require(!slow_call.has_value()); + expect_eq(slow_call.error().error.code().value, + static_cast( + Void::IPC::IpcErrorCode::timed_out)); + expect(slow_call.error().effect == Void::IPC::EffectStatus::unknown); + expect(slow_call.error().may_have_executed); + + // Release server handler -> late response arrives and is dropped cleanly via tombstone! + if (auto t = gate->try_commit_value(); t.has_value()) { + t->dispatch(); + } + gate->release_backend_ref_and_dispatch(); + for (int i = 0; + i < 400 && client.stats().late_responses_dropped == 0; + ++i) { + (void)exec.drain(); + (void)driver.poll_once(std::chrono::milliseconds{1}); + (void)exec.drain(); + } + pump_loop(driver, exec, scope); + expect(client.stats().late_responses_dropped >= 1); + + // Self-join rejected inside synchronous OneWayHandler. + std::optional self_join_err; + Void::IPC::Session* client_ptr = &client; + require(client + .start(echo_upper_handler, + [client_ptr, &self_join_err]( + Void::Binary::FrozenBytes) { + auto task = client_ptr->close_and_join(); + auto res = task.run(); + if (!res.has_value()) { + self_join_err = res.error(); + } + }) + .has_value()); + require(server.send_one_way(make_bytes("trigger_sj")).has_value()); + for (int i = 0; i < 400 && !self_join_err.has_value(); ++i) { + (void)exec.drain(); + (void)driver.poll_once(std::chrono::milliseconds{1}); + (void)exec.drain(); + } + require(self_join_err.has_value()); + expect_eq(self_join_err->code().value, + static_cast( + Void::IPC::IpcErrorCode::self_join)); + + // Peer disconnect faults in-flight request once with transport_lost + unknown. + std::expected disc_call{ + std::unexpected{Void::IPC::CallFailure{}}}; + std::atomic entered_stuck{false}; + require(server + .start([&exec, &entered_stuck]( + Void::Binary::FrozenBytes payload, + std::stop_token cancel) { + return cancel_aware_wait_handler( + std::move(payload), cancel, &exec, &entered_stuck); + }) + .has_value()); + + Void::Async::TaskScope dc_scope{exec, {}, clock}; + require(dc_scope + .spawn(run_request_task( + &client, make_bytes("in_flight"), {}, &disc_call)) + .has_value()); + for (int i = 0; i < 400 && !entered_stuck.load(); ++i) { + (void)exec.drain(); + (void)driver.poll_once(std::chrono::milliseconds{1}); + (void)exec.drain(); + } + require(entered_stuck.load()); + // Close server cleanly while client has an unfulfilled request -> client sees transport_lost / closed. + Void::Result::Result s_close; + require(dc_scope + .spawn(run_close_session_task(&server, {}, &s_close)) + .has_value()); + pump_loop(driver, exec, dc_scope); + require(!disc_call.has_value()); + expect(disc_call.error().error.code().value == + static_cast( + Void::IPC::IpcErrorCode::transport_lost) || + disc_call.error().error.code().value == + static_cast( + Void::IPC::IpcErrorCode::closed)); + expect(disc_call.error().effect == Void::IPC::EffectStatus::unknown); + expect(disc_call.error().may_have_executed); + + // Rate limit rejects bursts beyond token bucket capacity via control lane. + { + auto rpair = Void::IPC::create_socket_pair_transports(driver); + require(rpair.has_value()); + Void::IPC::IpcLimits rlim; + rlim.rate_limit_burst = 1.0; + rlim.rate_limit_per_sec = 0.001; + Void::IPC::Session rcli{ + driver, exec, std::move(rpair->first), rlim, clock}; + Void::IPC::Session rsrv{ + driver, exec, std::move(rpair->second), rlim, clock}; + require(rsrv.start(echo_upper_handler).has_value()); + + std::expected + rok{std::unexpected{Void::IPC::CallFailure{}}}; + std::expected + rlim_res{std::unexpected{Void::IPC::CallFailure{}}}; + Void::Async::TaskScope rscope{exec, {}, clock}; + require(rscope + .spawn(run_request_task( + &rcli, make_bytes("ok"), {}, &rok)) + .has_value()); + require(rscope + .spawn(run_request_task( + &rcli, make_bytes("excess"), {}, &rlim_res)) + .has_value()); + pump_loop(driver, exec, rscope); + require(rok.has_value()); + expect_eq(as_string(*rok), std::string{"OK"}); + require(!rlim_res.has_value()); + expect_eq(rlim_res.error().error.code().value, + static_cast( + Void::IPC::IpcErrorCode::rate_limited)); + expect(rlim_res.error().effect == Void::IPC::EffectStatus::not_sent); + + Void::Result::Result rc1; + Void::Result::Result rc2; + Void::Async::TaskScope rc_scope{exec, {}, clock}; + require(rc_scope.spawn(run_close_session_task(&rcli, {}, &rc1)) + .has_value()); + require(rc_scope.spawn(run_close_session_task(&rsrv, {}, &rc2)) + .has_value()); + pump_loop(driver, exec, rc_scope); + require(rc1.has_value() && rc2.has_value()); + } + + Void::Result::Result c_close; + Void::Async::TaskScope fin_scope{exec, {}, clock}; + require(fin_scope + .spawn(run_close_session_task(&client, {}, &c_close)) + .has_value()); + pump_loop(driver, exec, fin_scope); + } + + (void)driver.shutdown_and_join(); +} diff --git a/tests/standalone/System/ProcessStream.cpp b/tests/standalone/System/ProcessStream.cpp index 2a8e355..acf7b30 100644 --- a/tests/standalone/System/ProcessStream.cpp +++ b/tests/standalone/System/ProcessStream.cpp @@ -7,60 +7,59 @@ namespace { - using Void::Testing::Test; - struct ProcessStream : Void::Testing::Suite { - // stdout lines are delivered to the callback as they arrive, and - // the full output is still captured. - Test streams_stdout_lines() - { - std::vector lines; - Void::Process::StreamCallbacks cb; - cb.on_stdout = [&](std::string_view l) { - lines.emplace_back(l); - }; +using Void::Testing::Test; - auto r = Void::Process::run_streaming( - "/bin/sh", {"-c", "printf 'a\\nb\\nc\\n'"}, cb); - Void::Testing::expect(r.has_value()); - Void::Testing::expect_eq(r->exit_code, 0); +struct ProcessStream : Void::Testing::Suite { + Test streams_stdout_lines() + { + std::vector lines; + Void::Process::StreamCallbacks cb; + cb.on_stdout = [&](std::string_view l) { + lines.emplace_back(l); + }; - const std::vector expected{"a", "b", "c"}; - Void::Testing::expect(lines == expected); - Void::Testing::expect_eq(r->out, std::string{"a\nb\nc\n"}); - } + auto r = Void::Process::run_streaming( + VOID_PROCESS_HELPER_PATH, {"lines", "a", "b", "c"}, cb); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(r->exit_code, 0); - // A trailing partial line (no newline) is flushed at EOF. - Test flushes_trailing_partial_line() - { - std::vector lines; - Void::Process::StreamCallbacks cb; - cb.on_stdout = [&](std::string_view l) { - lines.emplace_back(l); - }; + const std::vector expected{"a", "b", "c"}; + Void::Testing::expect(lines == expected); + Void::Testing::expect_eq(r->out, std::string{"a\nb\nc\n"}); + } - auto r = Void::Process::run_streaming( - "/bin/sh", {"-c", "printf 'no-newline'"}, cb); - Void::Testing::expect(r.has_value()); - Void::Testing::expect_eq(lines.size(), std::size_t{1}); - Void::Testing::expect_eq(lines.at(0), - std::string{"no-newline"}); - } + Test flushes_trailing_partial_line() + { + std::vector lines; + Void::Process::StreamCallbacks cb; + cb.on_stdout = [&](std::string_view l) { + lines.emplace_back(l); + }; - // stderr is routed to its own callback. - Test streams_stderr_separately() - { - std::vector errs; - Void::Process::StreamCallbacks cb; - cb.on_stderr = [&](std::string_view l) { - errs.emplace_back(l); - }; + auto r = Void::Process::run_streaming( + VOID_PROCESS_HELPER_PATH, + {"lines", "--no-newline", "no-newline"}, + cb); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(lines.size(), std::size_t{1}); + Void::Testing::expect_eq(lines.at(0), std::string{"no-newline"}); + } + + Test streams_stderr_separately() + { + std::vector errs; + Void::Process::StreamCallbacks cb; + cb.on_stderr = [&](std::string_view l) { + errs.emplace_back(l); + }; + + auto r = Void::Process::run_streaming( + VOID_PROCESS_HELPER_PATH, {"lines", "--stderr", "oops"}, cb); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(errs.size(), std::size_t{1}); + Void::Testing::expect_eq(errs.at(0), std::string{"oops"}); + } +}; - auto r = Void::Process::run_streaming( - "/bin/sh", {"-c", "printf 'oops\\n' 1>&2"}, cb); - Void::Testing::expect(r.has_value()); - Void::Testing::expect_eq(errs.size(), std::size_t{1}); - Void::Testing::expect_eq(errs.at(0), std::string{"oops"}); - } - }; } // namespace diff --git a/tests/standalone/System/SystemHardening.cpp b/tests/standalone/System/SystemHardening.cpp new file mode 100644 index 0000000..224e6e6 --- /dev/null +++ b/tests/standalone/System/SystemHardening.cpp @@ -0,0 +1,296 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +using Void::Testing::expect; +using Void::Testing::expect_eq; +using Void::Testing::require; + +} // namespace + +Void::Testing::Test system_spawn_distinguishes_exec_failure_and_hygiene() +{ + // 1. spawn() returns exec_failed distinct from a child exiting 127. + Void::Process::SpawnOptions missing_opts; + missing_opts.executable = "/nonexistent/void/missing_binary"; + missing_opts.search_path = false; + auto missing_res = Void::Process::spawn(missing_opts); + require(!missing_res.has_value()); + expect_eq(missing_res.error().code().domain, Void::Result::kSystemErrorDomain); + expect_eq(missing_res.error().code().value, + static_cast(Void::System::SystemErrorCode::exec_failed)); + + Void::Process::SpawnOptions exit127_opts; + exit127_opts.executable = VOID_PROCESS_HELPER_PATH; + exit127_opts.arguments = {"exit", "127"}; + auto exit127_child = Void::Process::spawn(exit127_opts); + require(exit127_child.has_value()); + auto exit127_res = Void::Process::communicate_blocking(*exit127_child); + require(exit127_res.has_value()); + expect(exit127_res->status.exited); + expect_eq(exit127_res->status.code, 127); + + // 2. Non-CLOEXEC inherited fds in parent are never leaked across spawn(). + int dummy_pipe[2]{-1, -1}; + require(::pipe(dummy_pipe) == 0); + Void::System::OwnedFd leak0{dummy_pipe[0]}; + Void::System::OwnedFd leak1{dummy_pipe[1]}; + + Void::Process::SpawnOptions fd_opts; + fd_opts.executable = VOID_PROCESS_HELPER_PATH; + fd_opts.arguments = {"check-fds"}; + auto fd_child = Void::Process::spawn(fd_opts); + require(fd_child.has_value()); + auto fd_res = Void::Process::communicate_blocking(*fd_child); + require(fd_res.has_value()); + expect_eq(fd_res->out, std::string{"clean\n"}); + + // 3. EnvironmentPolicy allowlist & explicit_only + working_directory. + Void::FileSystem::TempDir tmp{"void_sys_cwd_"}; + Void::Process::SpawnOptions env_opts; + env_opts.executable = VOID_PROCESS_HELPER_PATH; + env_opts.arguments = {"env-dump"}; + env_opts.environment.mode = Void::Process::EnvMode::explicit_only; + env_opts.environment.set_vars = {{"VOID_Z", "two"}, {"VOID_A", "one"}}; + auto env_child = Void::Process::spawn(env_opts); + require(env_child.has_value()); + auto env_res = Void::Process::communicate_blocking(*env_child); + require(env_res.has_value()); + expect_eq(env_res->out, std::string{"VOID_A=one\nVOID_Z=two\n"}); + + Void::Process::SpawnOptions cwd_opts; + cwd_opts.executable = VOID_PROCESS_HELPER_PATH; + cwd_opts.arguments = {"cwd"}; + cwd_opts.working_directory = tmp.path(); + auto cwd_child = Void::Process::spawn(cwd_opts); + require(cwd_child.has_value()); + auto cwd_res = Void::Process::communicate_blocking(*cwd_child); + require(cwd_res.has_value()); + expect_eq(cwd_res->out, std::filesystem::canonical(tmp.path()).string() + "\n"); + + // 4. argv+env limit rejected cleanly before fork(). + Void::Process::SpawnOptions big_opts; + big_opts.executable = VOID_PROCESS_HELPER_PATH; + big_opts.arguments = {std::string(Void::Process::kMaxSpawnInputBytes + 64, 'x')}; + auto big_res = Void::Process::spawn(big_opts); + require(!big_res.has_value()); + expect_eq(big_res.error().code().value, + static_cast(Void::System::SystemErrorCode::limit_exceeded)); +} + +Void::Testing::Test system_communicate_duplex_limits_escalation_and_cancel() +{ + // 1. Full-duplex simultaneous 256 KiB stdin + stdout + stderr without deadlock. + const std::size_t payload_bytes = 256ULL * 1024ULL; + const std::string big_in(payload_bytes, 'i'); + Void::Process::SpawnOptions sim_opts; + sim_opts.executable = VOID_PROCESS_HELPER_PATH; + sim_opts.arguments = {"simultaneous-io", std::to_string(payload_bytes)}; + auto sim_child = Void::Process::spawn(sim_opts); + require(sim_child.has_value()); + Void::Process::CaptureLimits sim_lim; + sim_lim.max_line_bytes = 512ULL * 1024ULL; + auto sim_res = Void::Process::communicate_blocking( + *sim_child, + big_in, + sim_lim, + std::chrono::milliseconds{0}); // explicit zero-timeout completes normally + require(sim_res.has_value()); + expect(!sim_res->timed_out); + expect_eq(sim_res->status.code, 0); + expect_eq(sim_res->out.size(), payload_bytes); + expect_eq(sim_res->err.size(), payload_bytes); + + // 2. Capture limit fail_and_terminate vs drain_and_truncate, plus line_limit. + { + Void::Process::SpawnOptions flood_opts; + flood_opts.executable = VOID_PROCESS_HELPER_PATH; + flood_opts.arguments = {"flood", "4096", "0"}; + auto ch = Void::Process::spawn(flood_opts); + require(ch.has_value()); + Void::Process::CaptureLimits lim; + lim.max_stdout_bytes = 512; + lim.overflow_policy = Void::Process::OverflowPolicy::fail_and_terminate; + auto res = Void::Process::communicate_blocking(*ch, {}, lim); + require(!res.has_value()); + expect_eq(res.error().code().value, + static_cast(Void::System::SystemErrorCode::output_limit)); + } + { + Void::Process::SpawnOptions flood_opts; + flood_opts.executable = VOID_PROCESS_HELPER_PATH; + flood_opts.arguments = {"flood", "4096", "256"}; + auto ch = Void::Process::spawn(flood_opts); + require(ch.has_value()); + Void::Process::CaptureLimits lim; + lim.max_stdout_bytes = 512; + lim.overflow_policy = Void::Process::OverflowPolicy::drain_and_truncate; + auto res = Void::Process::communicate_blocking(*ch, {}, lim); + require(res.has_value()); + expect(res->overflowed); + expect(res->stdout_truncated); + expect_eq(res->out.size(), std::size_t{512}); + expect_eq(res->err.size(), std::size_t{256}); + } + { + Void::Process::SpawnOptions long_opts; + long_opts.executable = VOID_PROCESS_HELPER_PATH; + long_opts.arguments = {"long-line", "2048"}; + auto ch = Void::Process::spawn(long_opts); + require(ch.has_value()); + Void::Process::CaptureLimits lim; + lim.max_line_bytes = 128; + lim.overflow_policy = Void::Process::OverflowPolicy::fail_and_terminate; + auto res = Void::Process::communicate_blocking(*ch, {}, lim); + require(!res.has_value()); + expect_eq(res.error().code().value, + static_cast(Void::System::SystemErrorCode::line_limit)); + } + + // 3. SIGTERM-ignoring child escalates to SIGKILL within short kill_grace. + { + Void::Process::SpawnOptions sig_opts; + sig_opts.executable = VOID_PROCESS_HELPER_PATH; + sig_opts.arguments = {"ignore-sigterm", "10000"}; + sig_opts.kill_grace = std::chrono::milliseconds{40}; + auto ch = Void::Process::spawn(sig_opts); + require(ch.has_value()); + auto res = Void::Process::communicate_blocking( + *ch, {}, Void::Process::CaptureLimits{}, std::chrono::milliseconds{80}); + require(res.has_value()); + expect(res->timed_out); + expect(!res->status.exited); + expect_eq(res->status.signal, SIGKILL); + } + + // 4. Stop token cancels child cleanly. + { + Void::Process::SpawnOptions wait_opts; + wait_opts.executable = VOID_PROCESS_HELPER_PATH; + wait_opts.arguments = {"ignore-sigterm", "10000"}; + wait_opts.kill_grace = std::chrono::milliseconds{20}; + auto ch = Void::Process::spawn(wait_opts); + require(ch.has_value()); + std::stop_source ss; + ss.request_stop(); + auto res = ch->wait_blocking( + std::chrono::milliseconds{5000}, + ss.get_token(), + std::chrono::milliseconds{20}); + require(!res.has_value()); + expect_eq(res.error().code().value, + static_cast(Void::System::SystemErrorCode::cancelled)); + } +} + +Void::Testing::Test system_replace_file_temp_ownership_and_metrics() +{ + Void::FileSystem::TempDir tmp{"void_sys_fs_"}; + struct stat tmp_st {}; + require(::lstat(tmp.path().c_str(), &tmp_st) == 0); + expect_eq(static_cast(tmp_st.st_mode & 0777), 0700U); + + const auto target = tmp / "state.cfg"; + require(Void::FileSystem::replace_file(target, "initial").has_value()); + expect_eq(Void::FileSystem::read_file(target).value(), std::string{"initial"}); + + // Fault during write/sync/rename removes ONLY owned temp and leaves target intact. + for (auto phase : {Void::FileSystem::ReplacePhase::write_stage, + Void::FileSystem::ReplacePhase::sync_stage, + Void::FileSystem::ReplacePhase::rename}) { + Void::FileSystem::ReplaceOptions opts; + opts.fault_hook = [phase](Void::FileSystem::ReplacePhase p) + -> std::optional { + return (p == phase) ? std::optional{EIO} : std::nullopt; + }; + auto fail_res = Void::FileSystem::replace_file(target, "bad", opts); + require(!fail_res.has_value()); + expect(!fail_res.error().visible_on_disk); + expect(!fail_res.error().durability_unknown); + expect_eq(Void::FileSystem::read_file(target).value(), + std::string{"initial"}); + } + + // Post-rename parent sync failure reports visible_on_disk + durability_unknown. + { + Void::FileSystem::ReplaceOptions opts; + opts.fault_hook = [](Void::FileSystem::ReplacePhase p) + -> std::optional { + return (p == Void::FileSystem::ReplacePhase::sync_parent) + ? std::optional{EIO} + : std::nullopt; + }; + auto sync_res = Void::FileSystem::replace_file(target, "committed", opts); + require(!sync_res.has_value()); + expect(sync_res.error().visible_on_disk); + expect(sync_res.error().durability_unknown); + expect_eq(Void::FileSystem::read_file(target).value(), + std::string{"committed"}); + } + + // Bounded read_file & list_directory. + auto small_read = Void::FileSystem::read_file_bounded( + target, Void::FileSystem::ReadFileOptions{.max_bytes = 4}); + require(!small_read.has_value()); + expect_eq(small_read.error().code().value, + static_cast(Void::System::SystemErrorCode::limit_exceeded)); + + (void)Void::FileSystem::write_file(tmp / "extra1.txt", "1"); + (void)Void::FileSystem::write_file(tmp / "extra2.txt", "2"); + auto bounded_list = Void::FileSystem::list_directory_bounded( + tmp.path(), Void::FileSystem::ListDirectoryOptions{.max_entries = 1}); + require(!bounded_list.has_value()); + expect_eq(bounded_list.error().code().value, + static_cast(Void::System::SystemErrorCode::limit_exceeded)); + + // TempFile 0600 mode & symlink-swap refusal (destructor must not delete swap target). + const auto victim = tmp / "victim.txt"; + require(Void::FileSystem::write_file(victim, "keep_me").has_value()); + std::filesystem::path tf_path; + { + auto tf = Void::FileSystem::TempFile::open_in(tmp.path(), "tf_"); + require(tf.has_value()); + tf_path = tf->path(); + struct stat tf_st {}; + require(::lstat(tf_path.c_str(), &tf_st) == 0); + expect_eq(static_cast(tf_st.st_mode & 0777), 0600U); + + // Replace tf_path with symlink to victim; ~TempFile must NOT unlink it! + std::filesystem::remove(tf_path); + std::filesystem::create_symlink(victim, tf_path); + } + expect(std::filesystem::exists(victim)); + expect(std::filesystem::is_symlink(tf_path)); + std::filesystem::remove(tf_path); + + // CpuSampler::sample with injected ManualClock distinguishes valid vs zero interval. + Void::Time::ManualClock clock; + Void::SystemInfo::CpuSampler sampler{&clock}; + expect(!sampler.sample().valid); // zero elapsed delta on ManualClock + (void)clock.advance(std::chrono::seconds{1}); + const auto sample = sampler.sample(); + expect(sample.valid); + expect(sample.ratio >= 0.0); +} diff --git a/tests/standalone/SystemAsync/SystemAsync.cpp b/tests/standalone/SystemAsync/SystemAsync.cpp new file mode 100644 index 0000000..ad5179c --- /dev/null +++ b/tests/standalone/SystemAsync/SystemAsync.cpp @@ -0,0 +1,357 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +using Void::Testing::expect; +using Void::Testing::expect_eq; +using Void::Testing::require; + +void pump_loop(Void::IO::Driver& driver, + Void::Async::ManualExecutor& exec, + Void::Async::TaskScope& scope) +{ + for (int iter = 0; iter < 5000 && scope.active_count() > 0; ++iter) { + (void)exec.drain(); + (void)driver.poll_once(std::chrono::milliseconds{1}); + (void)exec.drain(); + } + if (scope.active_count() > 0) { + (void)scope.join_pumping(exec); + } +} + +[[nodiscard]] Void::Coro::Task run_communicate_task( + Void::SystemAsync::ProcessManager* mgr, + Void::SystemAsync::ManagedChild* child, + std::string stdin_data, + Void::Process::CaptureLimits limits, + Void::Async::OperationOptions opts, + Void::Result::Result* + out) +{ + *out = co_await mgr->communicate( + *child, std::move(stdin_data), limits, std::move(opts)); +} + +[[nodiscard]] Void::Coro::Task run_close_join_task( + Void::SystemAsync::ProcessManager* mgr, + Void::Result::Result* out) +{ + *out = co_await mgr->close_and_join(); +} + +} // namespace + +Void::Testing::Test system_async_process_manager_duplex_overflow_escalation_and_close() +{ + Void::Async::ManualExecutor exec; + auto drv_res = Void::IO::Driver::create(exec); + require(drv_res.has_value()); + auto& driver = **drv_res; + + Void::SystemAsync::ProcessManager mgr{ + driver, + exec, + Void::SystemAsync::ProcessManagerOptions{ + .max_active_children = 2, + .default_kill_grace = std::chrono::milliseconds{40}, + }}; + + // 1. max_active_children slot cap enforced cleanly. + { + Void::Process::SpawnOptions sleep_opts; + sleep_opts.executable = VOID_PROCESS_HELPER_PATH; + sleep_opts.arguments = {"ignore-sigterm", "2000"}; + sleep_opts.kill_grace = std::chrono::milliseconds{20}; + auto c1 = mgr.spawn(sleep_opts); + auto c2 = mgr.spawn(sleep_opts); + require(c1.has_value() && c2.has_value()); + auto c3 = mgr.spawn(sleep_opts); + require(!c3.has_value()); + expect_eq(c3.error().code().value, + static_cast( + Void::System::SystemErrorCode::limit_exceeded)); + expect_eq(mgr.active_children(), std::size_t{2}); + } + expect_eq(mgr.active_children(), std::size_t{0}); + + // 2. Full-duplex 256 KiB async communicate via Void::IO without deadlock. + { + const std::size_t payload_bytes = 256ULL * 1024ULL; + Void::Process::SpawnOptions sim_opts; + sim_opts.executable = VOID_PROCESS_HELPER_PATH; + sim_opts.arguments = {"simultaneous-io", std::to_string(payload_bytes)}; + auto ch = mgr.spawn(sim_opts); + require(ch.has_value()); + + Void::Process::CaptureLimits lim; + lim.max_line_bytes = 512ULL * 1024ULL; + Void::Result::Result + out{std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::internal, "unset")}}; + Void::Async::TaskScope scope{exec}; + require(scope + .spawn(run_communicate_task( + &mgr, + &*ch, + std::string(payload_bytes, 'i'), + lim, + {}, + &out)) + .has_value()); + pump_loop(driver, exec, scope); + require(out.has_value()); + expect(!out->timed_out); + expect_eq(out->status.code, 0); + expect_eq(out->out.size(), payload_bytes); + expect_eq(out->err.size(), payload_bytes); + } + + // 3. Overflow limit terminates child and returns output_limit. + { + Void::Process::SpawnOptions flood_opts; + flood_opts.executable = VOID_PROCESS_HELPER_PATH; + flood_opts.arguments = {"flood", "4096", "0"}; + auto ch = mgr.spawn(flood_opts); + require(ch.has_value()); + + Void::Process::CaptureLimits lim; + lim.max_stdout_bytes = 256; + lim.overflow_policy = Void::Process::OverflowPolicy::fail_and_terminate; + Void::Result::Result + out{std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::internal, "unset")}}; + Void::Async::TaskScope scope{exec}; + require(scope + .spawn(run_communicate_task(&mgr, &*ch, {}, lim, {}, &out)) + .has_value()); + pump_loop(driver, exec, scope); + require(!out.has_value()); + expect_eq(out.error().code().value, + static_cast( + Void::System::SystemErrorCode::output_limit)); + } + + // 4. SIGTERM-ignoring child escalates on OperationOptions deadline -> SIGKILL. + { + Void::Process::SpawnOptions sig_opts; + sig_opts.executable = VOID_PROCESS_HELPER_PATH; + sig_opts.arguments = {"ignore-sigterm", "10000"}; + sig_opts.kill_grace = std::chrono::milliseconds{30}; + auto ch = mgr.spawn(sig_opts); + require(ch.has_value()); + + Void::Async::OperationOptions opts{ + .deadline = Void::Time::SystemMonotonicClock::instance().now() + + std::chrono::milliseconds{60}}; + Void::Result::Result + out{std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::internal, "unset")}}; + Void::Async::TaskScope scope{exec}; + require(scope + .spawn(run_communicate_task( + &mgr, &*ch, {}, Void::Process::CaptureLimits{}, opts, &out)) + .has_value()); + pump_loop(driver, exec, scope); + require(out.has_value()); + expect(out->timed_out); + expect_eq(out->status.signal, SIGKILL); + } + + // 5. close_and_join closes admission and drains cleanly. + { + Void::Result::Result close_res; + Void::Async::TaskScope scope{exec}; + require(scope.spawn(run_close_join_task(&mgr, &close_res)).has_value()); + pump_loop(driver, exec, scope); + require(close_res.has_value()); + expect(mgr.closed()); + + Void::Process::SpawnOptions blocked_opts; + blocked_opts.executable = VOID_PROCESS_HELPER_PATH; + blocked_opts.arguments = {"exit", "0"}; + auto late = mgr.spawn(blocked_opts); + require(!late.has_value()); + expect_eq(late.error().code().value, + static_cast(Void::System::SystemErrorCode::busy)); + } + + (void)driver.shutdown_and_join(); +} + +Void::Testing::Test system_async_watcher_deterministic_events_overflow_and_join() +{ + Void::FileSystem::TempDir tmp{"void_w6a_watch_"}; + Void::FileSystem::TempDir outside{"void_w6a_out_"}; + Void::Time::ManualClock clock; + Void::Async::ManualExecutor exec; + + std::vector errors; + Void::SystemAsync::WatcherService svc{ + exec, + Void::SystemAsync::WatcherLimits{ + .max_watched_paths = 32, + .max_queued_events = 2, + .debounce_polls = 1, + }, + clock, + [&](const Void::Result::Error& err) { + errors.push_back(err.message()); + }, + /*start_background_thread=*/false}; + + // 1. Rejects path outside allowed_root and rejects forbidden symlinks. + const auto outside_file = outside / "secret.txt"; + require(Void::FileSystem::write_file(outside_file, "x").has_value()); + { + auto esc = svc.watch( + tmp.path() / ".." / outside.path().filename() / "secret.txt", + [](const Void::SystemAsync::WatchEvent&) {}, + Void::SystemAsync::WatchPathOptions{.allowed_root = tmp.path()}); + expect(!esc.has_value()); + expect_eq(esc.error().code().value, + static_cast( + Void::System::SystemErrorCode::permission_denied)); + } + + const auto sym_path = tmp / "forbidden_link"; + std::filesystem::create_symlink(outside_file, sym_path); + { + auto sym_rej = svc.watch( + sym_path, + [](const Void::SystemAsync::WatchEvent&) {}, + Void::SystemAsync::WatchPathOptions{.allow_symlink = false}); + expect(!sym_rej.has_value()); + expect_eq(sym_rej.error().code().value, + static_cast( + Void::System::SystemErrorCode::permission_denied)); + } + + // 2. Detects created -> replaced_inode -> deleted -> self_join -> close_and_join. + const auto target = tmp / "watched.cfg"; + std::vector kinds; + Void::SystemAsync::WatchSubscription* sub_ptr = nullptr; + std::optional self_join_err; + bool throw_on_next = false; + + auto sub_res = svc.watch( + target, + [&](const Void::SystemAsync::WatchEvent& ev) { + kinds.push_back(ev.kind); + if (throw_on_next) { + throw std::runtime_error("intentional watcher callback throw"); + } + if (sub_ptr != nullptr && + ev.kind == Void::SystemAsync::WatchEventKind::deleted) { + auto sj = sub_ptr->close_and_join(); + if (!sj.has_value()) { + self_join_err = sj.error(); + } + } + }, + Void::SystemAsync::WatchPathOptions{.allowed_root = tmp.path()}); + require(sub_res.has_value()); + sub_ptr = &*sub_res; + + require(Void::FileSystem::replace_file(target, "v1").has_value()); + svc.poll_once(); + (void)exec.drain(); + require(kinds.size() == 1); + expect(kinds[0] == Void::SystemAsync::WatchEventKind::created); + + require(Void::FileSystem::replace_file(target, "v2_longer").has_value()); + svc.poll_once(); + (void)exec.drain(); + require(kinds.size() == 2); + expect(kinds[1] == Void::SystemAsync::WatchEventKind::replaced_inode); + + std::filesystem::remove(target); + svc.poll_once(); + (void)exec.drain(); + require(kinds.size() == 3); + expect(kinds[2] == Void::SystemAsync::WatchEventKind::deleted); + require(self_join_err.has_value()); + expect_eq(self_join_err->code().value, + static_cast( + Void::System::SystemErrorCode::self_join)); + + // Callback exceptions are caught and routed to ErrorSink without crashing. + throw_on_next = true; + require(Void::FileSystem::replace_file(target, "v3").has_value()); + svc.poll_once(); + (void)exec.drain(); + expect_eq(errors.size(), std::size_t{1}); + throw_on_next = false; + + sub_ptr = nullptr; + expect(sub_res->close_and_join().has_value()); + expect_eq(svc.watch_count(), std::size_t{0}); + + // 3. Allowed symlink target change detected + queue overflow rescan_required. + std::vector sym_kinds; + const auto sym_ok = tmp / "allowed_link"; + std::filesystem::create_symlink("target_a", sym_ok); + auto sym_sub = svc.watch( + sym_ok, + [&](const Void::SystemAsync::WatchEvent& ev) { + sym_kinds.push_back(ev.kind); + }, + Void::SystemAsync::WatchPathOptions{.allow_symlink = true}); + require(sym_sub.has_value()); + + std::filesystem::remove(sym_ok); + std::filesystem::create_symlink("target_b", sym_ok); + svc.poll_once(); + (void)exec.drain(); + require(sym_kinds.size() == 1); + expect(sym_kinds[0] == Void::SystemAsync::WatchEventKind::symlink_changed); + + // Queue overflow across 3 watched paths when max_queued_events == 2 triggers rescan_required. + std::vector ov_kinds; + const auto f1 = tmp / "ov1"; + const auto f2 = tmp / "ov2"; + const auto f3 = tmp / "ov3"; + auto s1 = svc.watch(f1, [&](const auto& ev) { ov_kinds.push_back(ev.kind); }); + auto s2 = svc.watch(f2, [&](const auto& ev) { ov_kinds.push_back(ev.kind); }); + auto s3 = svc.watch(f3, [&](const auto& ev) { ov_kinds.push_back(ev.kind); }); + require(s1.has_value() && s2.has_value() && s3.has_value()); + + require(Void::FileSystem::write_file(f1, "1").has_value()); + require(Void::FileSystem::write_file(f2, "2").has_value()); + require(Void::FileSystem::write_file(f3, "3").has_value()); + svc.poll_once(); + (void)exec.drain(); + bool saw_rescan = false; + for (auto k : ov_kinds) { + if (k == Void::SystemAsync::WatchEventKind::rescan_required) { + saw_rescan = true; + } + } + expect(saw_rescan); + + expect(svc.shutdown().has_value()); +}